Lesson 01 · Tokens and serialization

The Input Becomes a Sequence of Integers

A network computes on numbers in a fixed order. Text has neither; a point cloud has numbers but no order. This lesson builds the sequence on both sides, one definition at a time, with the course code run on the real data.

map · flow · code: code/llm/c01_tokenization.py, code/pc/c01_serialization.py · book: chapter 2 (ch02.ipynb)

The five lessons; lesson 01 highlighted Both pipelines bottom to top with example values; the rows this lesson covers are marked

Where we are. Top: the five lessons, this one highlighted. Bottom: the two pipelines drawn with real values (book Figure 2.4 style); the dashed green box marks the rows this lesson builds. The question we answer: how does the input become a sequence of integers?

1The chain of this lesson

Every card below has the same anatomy: What (the definition), Why we need it (the amber strip), then the two instances of the concept side by side, the GPT one with the book's figure and the point-cloud one drawn with numbers from the car, each with its real output and the ⚙ line that produces it. The bridge between cards is the question the previous card leaves open.

Definition · unit (token · cell) A unit is the smallest piece of input the model will treat as one thing. For text it is a word or a subword; for a point cloud it is a grid cell: every point inside the same 5 cm cube becomes the same unit.

Why we need it: the model's first layer multiplies numbers. "journey" cannot be multiplied, and 24 949 floating-point coordinates cannot be compared for equality. A unit is something we can count and name: there are finitely many of them, and two inputs that fall on the same unit are, for the model, identical.

LLM

Split the story on whitespace and punctuation. The regular expression keeps the punctuation as its own pieces.

Book Figure 2.6: tokenization breaks the training text into individual tokens, then the unique tokens form the vocabulary
['Hello', ',', 'world', '.', 'Is', 'this', '--', 'a', 'test', '?']
⚙ re.split(r'([,.:;?_!"()\']|--|\s)', text) · run it: c01_tokenization.py § split
code
text = "Hello, world. Is this-- a test?"
result = re.split(r'([,.:;?_!"()\']|--|\s)', text)
result = [item.strip() for item in result if item.strip()]
print(result)
Point cloud

Divide every coordinate by the grid size and round down. The car's 24 949 points land in 6 485 occupied cells.

Four real points of the car: continuous coordinates divided by 0.05 and floored give integer grid cells
grid size 0.05 m -> cells span [(0, 33), (0, 80), (0, 33)]
unique occupied cells: 6485  (of 24949 points; 3.85 points per cell)
  P0     ( 0.268,  0.193,  0.789) -> cell (5, 3, 15)
  P1     ( 0.312,  0.157,  0.630) -> cell (6, 3, 12)
  P100   ( 0.184,  0.222,  1.031) -> cell (3, 4, 20)
  P24948 ( 1.666,  3.723,  0.653) -> cell (33, 74, 13)
⚙ np.floor(coords / 0.05).astype(int) · run it: c01_serialization.py § quantize
code
def quantize_to_grid(coords: np.ndarray, grid_size: float = 0.1) -> np.ndarray:
    """Convert continuous 3D coordinates to discrete grid coordinates."""
    grid_coords = np.floor(coords / grid_size).astype(np.int64)
    return grid_coords

↓ a unit is a name, not a number — the network needs an integer per unit

Definition · integer id (vocabulary id · curve code) An id is the integer the model stores instead of the unit. The LLM gets it from a vocabulary, the sorted list of all distinct units of the training text: the id is the unit's row number. The point cloud gets it from a space-filling curve: the id is the cell's position along a path that visits every cell of the grid once.

Why we need it: an integer can index a table (lesson 2) and can be sorted. The two ids differ in one respect that matters for everything after: a vocabulary id is arbitrary (id 5 and id 6 have nothing in common), a curve code is ordered in space: cells with nearby codes are nearby cubes. That is what will let the point cloud skip neighbour search.

LLM

The story has 4 690 tokens and 1 130 distinct ones; sorted alphabetically, punctuation comes first.

Book Figure 2.7: a new text is tokenized and mapped to token ids through the existing vocabulary
Total number of character: 20479
I HAD always thought Jack Gisburn rather a cheap genius--though a good fellow enough--so it was no 
tokens in the story: 4690
vocab size: 1130
('!', 0)
('"', 1)
("'", 2)
('(', 3)
(')', 4)
(',', 5)
('--', 6)
('.', 7)
⚙ vocab = {tok: i for i, tok in enumerate(sorted(set(preprocessed)))} · c01_tokenization.py § vocab
Point cloud

▶ Animation: watch a curve number the cells and order the points

Z-order (Morton) code: write x, y, z in binary and interleave the bits. One cell of the car, done by hand:

The cell (7, 28, 30) written in 7 bits per axis, interleaved to the 21-bit Z-order code 28137
cell (3, 4, 20):  x=00000011  y=00000100  z=00010100
interleave (z_i y_i x_i) from the top bit down: 000 000 000 100 000 110 001 001
Z-order code = 000000000100000110001001 = 16777
Hilbert code of the same cell (8 bits per axis) = 4415
⚙ codes |= (x_bit << 3*i) | (y_bit << 3*i+1) | (z_bit << 3*i+2) for each bit i · c01_serialization.py § morton
code (Z-order, from your serialization notebook)
def z_order_encode(grid_coords: np.ndarray, depth: int = 16) -> np.ndarray:
    """Encode 3D grid coordinates into Z-order (Morton) codes by interleaving bits."""
    x = grid_coords[:, 0].astype(np.uint64)
    y = grid_coords[:, 1].astype(np.uint64)
    z = grid_coords[:, 2].astype(np.uint64)

    codes = np.zeros(len(x), dtype=np.uint64)

    for i in range(depth):
        x_bit = (x >> np.uint64(i)) & np.uint64(1)
        y_bit = (y >> np.uint64(i)) & np.uint64(1)
        z_bit = (z >> np.uint64(i)) & np.uint64(1)

        codes |= (x_bit << np.uint64(3 * i))      # x at position 3i
        codes |= (y_bit << np.uint64(3 * i + 1))  # y at position 3i+1
        codes |= (z_bit << np.uint64(3 * i + 2))  # z at position 3i+2

    return codes


def z_order_encode_trans(grid_coords: np.ndarray, depth: int = 16) -> np.ndarray:
    """Trans Z-order: swap x and y axes before encoding."""
    transposed = grid_coords[:, [1, 0, 2]]
    return z_order_encode(transposed, depth)
code (true 3-D Hilbert curve, added; every step adjacent)
def hilbert_encode(grid_coords: np.ndarray, bits: int = 16) -> np.ndarray:
    """Hilbert index of integer grid coordinates. Consecutive indices are adjacent cells."""
    X = grid_coords.astype(np.uint64).copy()
    n = X.shape[1]
    M = np.uint64(1) << np.uint64(bits - 1)
    one = np.uint64(1)

    # Inverse undo
    Q = M
    while Q > one:
        P = Q - one
        for i in range(n):
            hit = (X[:, i] & Q) != 0
            X[hit, 0] ^= P                                   # invert
            t = (X[~hit, 0] ^ X[~hit, i]) & P                # exchange
            X[~hit, 0] ^= t
            X[~hit, i] ^= t
        Q >>= one

    # Gray encode
    for i in range(1, n):
        X[:, i] ^= X[:, i - 1]
    t = np.zeros(len(X), dtype=np.uint64)
    Q = M
    while Q > one:
        hit = (X[:, n - 1] & Q) != 0
        t[hit] ^= (Q - one)
        Q >>= one
    for i in range(n):
        X[:, i] ^= t

    # Interleave the transposed bits into one integer (axis 0 most significant)
    codes = np.zeros(len(X), dtype=np.uint64)
    for b in range(bits):
        for i in range(n):
            bit = (X[:, i] >> np.uint64(b)) & one
            codes |= bit << np.uint64(b * n + (n - 1 - i))
    return codes


def hilbert_encode_trans(grid_coords: np.ndarray, bits: int = 16) -> np.ndarray:
    return hilbert_encode(grid_coords[:, [1, 0, 2]], bits)

↓ we can now go from input to ids — and we need the way back

Definition · encode and decode (order and inverse) Encode maps the input to its sequence of ids; decode maps ids back. For the point cloud, "encode" is a sort: order the points by their curve code. Nothing is copied; the result is a permutation array order, and inverse = argsort(order) puts everything back.

Why we need it: the model's output comes back as ids (next-token ids for the LLM, per-point logits in serialized order for the point cloud). Without the inverse map there is no text to read and no label on the original points. For the point cloud the inverse is also what makes four different orders cheap: each is just another index array over the same points.

LLM Book Figure 2.8: encode turns text into ids via the vocabulary, decode turns ids back into text via the inverse vocabulary
[1, 56, 2, 850, 988, 602, 533, 746, 5, 1126, 596, 5, 1, 67, 7, 38, 851, 1108, 754, 793, 7]
" It' s the last he painted, you know," Mrs. Gisburn said with pardonable pride.

Round trip exact, except the space the regex inserted inside "It's": the apostrophe was split off as its own token.

⚙ tokenizer.encode(text), tokenizer.decode(ids) (Listing 2.3) · c01_tokenization.py § encode
code (SimpleTokenizerV1)
class SimpleTokenizerV1:
    def __init__(self, vocab):
        self.str_to_int = vocab
        self.int_to_str = {i:s for s,i in vocab.items()}

    def encode(self, text):
        preprocessed = re.split(r'([,.:;?_!"()\']|--|\s)', text)
        preprocessed = [
            item.strip() for item in preprocessed if item.strip()
        ]
        ids = [self.str_to_int[s] for s in preprocessed]
        return ids

    def decode(self, ids):
        text = " ".join([self.int_to_str[i] for i in ids])
        # Replace spaces before the specified punctuations
        text = re.sub(r'\s+([,.?!"()\'])', r'\1', text)
        return text
Point cloud Four real points in file order with their Z codes, and the same points after sorting by code; arrows show where each one moved
rank  orig idx  cell             Z code       xyz (m)
0     5986      (3, 6, 7)        445          (0.19, 0.34, 0.40)
1     12914     (3, 7, 7)        447          (0.18, 0.38, 0.40)
2     3368      (4, 5, 7)        486          (0.20, 0.28, 0.40)
3     3376      (4, 5, 7)        486          (0.22, 0.28, 0.38)
4     10835     (4, 5, 7)        486          (0.23, 0.28, 0.39)
5     17231     (4, 5, 7)        486          (0.25, 0.28, 0.39)
6     17237     (5, 5, 7)        487          (0.25, 0.29, 0.40)
7     17243     (5, 5, 7)        487          (0.27, 0.29, 0.39)
... nothing was moved: 'order' is a permutation, 'inverse' undoes it
check inverse[order] == arange: True
⚙ order = np.argsort(codes); inverse = np.argsort(order) · c01_serialization.py § sort

↓ encode assumes every unit has an id — what if the input contains one it never saw?

Definition · unknown input (<|unk|> · subwords · nothing) A unit that is not in the vocabulary has no id. The word-level tokenizer fails, then is patched with a catch-all token <|unk|> (and <|endoftext|> to separate documents). Byte-pair encoding (GPT-2's tokenizer) removes the problem: unknown words are split into known subwords, down to single characters if needed. The point cloud never has the problem: any coordinate floors to some cell, and any cell has a code.

Why we need it: a model that crashes on a new word is useless, and one that maps every new word to the same id loses the information. This is also the first place the two sides differ in kind: a vocabulary is a finite list learned from data, quantization is a formula.

LLM
KeyError: 'Hello'  <- 'Hello' never occurs in the story, so V1 has no id for it
vocab size with special tokens: 1132
[1131, 5, 355, 1126, 628, 975, 10, 1130, 55, 988, 956, 984, 722, 988, 1131, 7]
<|unk|>, do you like tea? <|endoftext|> In the sunlit terraces of the <|unk|>.
Book Figure 2.9: the vocabulary is extended with the special tokens unk and endoftext Book Figure 2.11: a BPE tokenizer breaks an unknown word into subword ids
[15496, 11, 466, 345, 588, 8887, 30, 50256, 818, 262, 4252, 18250, 8812, 2114, 286, 617, 34680, 27271, 13]
['Hello', ',', ' do', ' you', ' like', ' tea', '?', '<|endoftext|>', 'In', ' the', ' sun', 'lit', ' terr', 'aces', ' of', ' some', 'unknown', 'Place', '.']
Hello, do you like tea?<|endoftext|>In the sunlit terraces of someunknownPlace.
vocabulary size of the GPT-2 BPE tokenizer: 50257
⚙ tiktoken.get_encoding("gpt2").encode(text, allowed_special={"<|endoftext|>"}) · c01_tokenization.py § bpe
code (SimpleTokenizerV2 with unk)
class SimpleTokenizerV2:
    def __init__(self, vocab):
        self.str_to_int = vocab
        self.int_to_str = {i:s for s,i in vocab.items()}

    def encode(self, text):
        preprocessed = re.split(r'([,.:;?!"()\']|--|\s)', text)
        preprocessed = [item.strip() for item in preprocessed if item.strip()]
        preprocessed = [
            item if item in self.str_to_int
            else "<|unk|>" for item in preprocessed
        ]
        ids = [self.str_to_int[s] for s in preprocessed]
        return ids

    def decode(self, ids):
        text = " ".join([self.int_to_str[i] for i in ids])
        text = re.sub(r'\s+([,.:;?!"()\'])', r'\1', text)
        return text
Point cloud

No special tokens exist. A point 2 km away still floors to a cell; a cell nobody has seen still has a curve code. The only "special" value is the batch index, packed into the high bits of the same 64-bit integer so that one sort orders a whole batch:

code = (b ≪ k) | φ−1(⌊ p / g ⌋)b batch index · k bits reserved for the curve position · φ−1 the curve (Z-order or Hilbert) · g grid size. Paper Section 4.1.
⚙ the course notebook keeps one batch, so b = 0; the sort above is the whole encode step

↓ we have one long sequence of ids — attention cannot look at all of it at once

Definition · group for attention (context window · patch) Attention compares every unit of a group with every other unit of the same group, at a cost that grows with the square of the group size. So the sequence is cut into groups: the LLM trains on windows of context_length tokens (1 024 for GPT-2), the point cloud attends inside consecutive patches of the sorted sequence (64 here, 1 024 in the paper), padding the last patch by borrowing points so that all patches have the same size.

Why we need it: 24 949² is 622 million pairs; 390 patches × 64² is 1.6 million. The LLM's window also defines the training signal: the target of each position is the next token. For the point cloud there is a price: a patch boundary can separate two spatial neighbours. The measurement on the right says how often.

LLM

Sliding window over the id stream: input of length 4, target shifted by one.

inputs : [[40, 367, 2885, 1464]] -> I HAD always
targets: [[367, 2885, 1464, 1807]] ->  HAD always thought
inputs : [[367, 2885, 1464, 1807]]
targets: [[2885, 1464, 1807, 3619]]

The order of the sequence is the learning signal, which is why lesson 4 needs a causal mask.

⚙ GPTDatasetV1(txt, tokenizer, max_length=4, stride=1) (Listing 2.5) · c01_tokenization.py § window
code (GPTDatasetV1)
class GPTDatasetV1(Dataset):
    def __init__(self, txt, tokenizer, max_length, stride):
        self.input_ids = []
        self.target_ids = []

        # Tokenize the entire text
        token_ids = tokenizer.encode(txt, allowed_special={"<|endoftext|>"})

        # Use a sliding window to chunk the book into overlapping sequences of max_length
        for i in range(0, len(token_ids) - max_length, stride):
            input_chunk = token_ids[i:i + max_length]
            target_chunk = token_ids[i + 1: i + max_length + 1]
            self.input_ids.append(torch.tensor(input_chunk))
            self.target_ids.append(torch.tensor(target_chunk))

    def __len__(self):
        return len(self.input_ids)

    def __getitem__(self, idx):
        return self.input_ids[idx], self.target_ids[idx]


def create_dataloader_v1(txt, batch_size=4, max_length=256,
                         stride=128, shuffle=True, drop_last=True):
    import tiktoken
    tokenizer = tiktoken.get_encoding("gpt2")
    dataset = GPTDatasetV1(txt, tokenizer, max_length, stride)
    return DataLoader(dataset, batch_size=batch_size, shuffle=shuffle, drop_last=drop_last)
Point cloud Twelve real points of the car cut into toy patches of four under Z-order and under Hilbert: the boundaries move
of each point's 8 nearest neighbours in space, how many share its patch? (2500-point subsample)
  patch  32: z: 5.31   z-trans: 5.23   hilbert: 5.33   hilbert-trans: 5.34   | reached by at least one of the 4 orders: 6.76 of 8
  patch  64: z: 6.15   z-trans: 6.09   hilbert: 6.04   hilbert-trans: 6.05   | reached by at least one of the 4 orders: 7.13 of 8
  patch 128: z: 6.65   z-trans: 6.65   hilbert: 6.71   hilbert-trans: 6.62   | reached by at least one of the 4 orders: 7.40 of 8

About 6 of a point's 8 true nearest neighbours share its patch under any one order; 7 of 8 are reachable through at least one of the four. The gap is what lesson 4 closes.

⚙ group_into_patches(n, order, patch_size=64) (your notebook, Step 6) · c01_serialization.py § patches, § neighbours
code (group_into_patches)
def group_into_patches(n_points, sorted_indices, patch_size=64):
    """Group serialized points into non-overlapping patches; pad the last one by borrowing."""
    patches = []
    for i in range(0, n_points, patch_size):
        end_idx = min(i + patch_size, n_points)
        patch_indices = sorted_indices[i:end_idx].copy()
        if len(patch_indices) < patch_size and i > 0:
            pad_size = patch_size - len(patch_indices)
            padding = sorted_indices[i - pad_size:i]
            patch_indices = np.concatenate([patch_indices, padding])
        patches.append(patch_indices)
    return patches


def patch_id_of(inverse_indices, patch_size):
    """Patch id for every point (in original order) under one serialization."""
    return inverse_indices // patch_size

↓ the ids are integers, and integers are labels, not vectors — lesson 2 turns them into vectors

2What serialization buys, measured

One number says why the point cloud bothers with curves at all. Walk the sequence and measure how far each point is from the next one:

mean distance between consecutive points in the sequence (m):
  random order   1.538   (median 1.384, max 4.00)
  z              0.041   (median 0.027, max 2.93)
  z-trans        0.042   (median 0.028, max 2.93)
  hilbert        0.038   (median 0.027, max 3.77)
  hilbert-trans  0.038   (median 0.027, max 3.09)

In the file's order the next point is on average 1.5 m away, the other end of the car. After sorting along any of the four curves it is 4 cm away. "Next in the sequence" has become a usable substitute for "nearby in space", which is the only reason attention on a slice of the sequence makes sense.

The course's own summary table Summary table from the course notebooks: raw input, tokenization, ordering, embedding, position, input to attention, for text transformers and PTv3

3Try it

LLM · tokenize your own sentence

Orange chips are unknown to the word-level tokenizer; BPE never produces an unknown.

Point cloud · the car, serialized

Top view of a 2 500-point subsample. Hover a point.

Colours repeat every 8 patches. Switch the pattern: the points stay, the patch boundaries move.

4What this lesson established

Why does the LLM need special tokens but the point cloud does not?

A vocabulary is finite and built from training text, so new words have no id. Quantization is a formula: every coordinate maps to a cell, every cell has a curve code.

Both sides produce integers. In which one does the integer carry meaning?

Only the curve code; sorting it already groups nearby points. Token ids are labels; the embedding table of lesson 2 gives them meaning.

Why four serialization patterns instead of the best one?

Any single curve splits some neighbours into different patches (about 2 of 8 here). A different curve splits a different set, so cycling patterns across layers lets each point meet the neighbours it missed.