7. Tokenization

Why this layer exists

A language model does not read text. It reads a sequence of integers, each an index into a fixed vocabulary of VV entries, and it outputs, at every position, a distribution over those same VV entries. Something has to turn a string into ids on the way in and ids back into a string on the way out, and whatever does it decides what a “token” is. That decision is fixed before training starts and cannot be changed afterwards without retraining, because every weight that touches the input or the output is indexed by it.

Three things downstream depend on it directly. The vocabulary size VV sizes both ends of the model: chapter 8’s bigram model is a (V, V) table of logits, chapter 9’s embedding table is (V, d) for a model width dd, and the output layer of chapter 9’s model and the transformers after it is a (d, V) matrix followed by a softmax over VV entries. The tokenizer’s compression sets the cost of every context window: Part V budgets context in tokens, not bytes or words, so a tokenizer that spends more tokens on your text gives you less of it per window. And constrained decoding, in chapter 18, masks the model’s choices one token at a time while the grammar it enforces is written over characters, so wherever a token and a grammar symbol disagree about boundaries, the mask has to reason about both.

In your stack, a GGUF file carries its tokenizer with it. The GGUF specification (docs/gguf.md in the ggml repository) defines the metadata keys tokenizer.ggml.model, whose value gpt2 means the GPT-2 style byte-level BPE this chapter builds, tokenizer.ggml.tokens, the list of token strings indexed by id, and tokenizer.ggml.merges, the BPE merge rules, along with tokenizer.ggml.token_type, which marks each token as normal, control, byte and so on. llama-server exposes the result as POST /tokenize and POST /detokenize. Passing "with_pieces": true to /tokenize returns each id with its piece, and the server documentation (as of llama.cpp commit da89bb3, 2026-09-29) says the piece comes back as a byte array instead of a string when it is not valid Unicode on its own. By the end of this chapter you will know why that case exists.

This chapter builds tinygpt.bpe, a byte-level byte-pair-encoding tokenizer, and trains it on Jane Austen’s Persuasion (1818), the main corpus of the transformer chapters (11 to 15): py/data/persuasion.txt, 469,020 bytes of UTF-8, generated from Project Gutenberg’s text by py/data/make_persuasion.py. Chapters 8 and 9, and several later scripts and lab fixtures, use the smaller py/data/tiny-corpus.txt, whose words can be read off a table.

Mechanism

Code points and encodings

Unicode assigns each character an integer code point, written U+ and hex: a is U+0061, é is U+00E9, ’ (the right single quotation mark Persuasion uses as its apostrophe) is U+2019, and 🙂 is U+1F642. Code points run to U+10FFFF, which needs 21 bits. A file or a socket carries bytes, not code points, so an encoding maps each code point to a byte string and back.

UTF-8, specified in RFC 3629, uses one to four bytes per code point. The number of leading 1 bits in the first byte says how many bytes the character has; every following byte starts with 10; the remaining bits, the xs, hold the code point, most significant first:

Code points Bits Byte 1 Byte 2 Byte 3 Byte 4
U+0000 to U+007F 7 0xxxxxxx
U+0080 to U+07FF 11 110xxxxx 10xxxxxx
U+0800 to U+FFFF 16 1110xxxx 10xxxxxx 10xxxxxx
U+10000 to U+10FFFF 21 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx

Take é. U+00E9 is 233, above 127 and below 2048, so it takes two bytes and 11 payload bits: 00011 101001. The first five go after 110 and the last six after 10:

11000011 10101001=C3 A9. \texttt{11000011}\ \texttt{10101001} = \texttt{C3}\ \texttt{A9} .

🙂 is U+1F642, above U+FFFF, so it takes four bytes and 21 payload bits. In binary, 0x1F642 is 1 1111 0110 0100 0010, padded on the left to 21 bits and split 3, 6, 6, 6: 000 011111 011001 000010. With the prefixes,

11110000 10011111 10011001 10000010=F0 9F 99 82. \texttt{11110000}\ \texttt{10011111}\ \texttt{10011001}\ \texttt{10000010} = \texttt{F0}\ \texttt{9F}\ \texttt{99}\ \texttt{82} .

Three properties of this design matter for tokenization. ASCII is unchanged: a 7-bit character is its own byte, so English prose is mostly one byte per character (Persuasion is 464,441 characters in 469,020 bytes; its only non-ASCII characters are é, œ, the dash — and four curly quotes). No byte of a multi-byte character is below 0x80, so an ASCII byte such as / or " found in a UTF-8 stream is always that character, never part of another. And the encoding is self-synchronising: a continuation byte, 10xxxxxx, can never be mistaken for the first byte of a character, so from any position in a stream you find the next character boundary by skipping at most three continuation bytes. A decoder that starts mid-stream, or loses bytes, recovers at the next character.

Bytes as the base alphabet

A tokenizer needs a base alphabet: the symbols every string can be written in, before any merging. Characters are a poor choice: there are 1,114,112 code points, most of which will never appear in the training text, and a character the tokenizer has never seen has no id. Tokenizers built on characters therefore reserve an “unknown” token and map anything unseen to it, which destroys the round trip: the model can neither read nor write the character.

Bytes have none of these problems. There are exactly 256 of them, every string is a byte string, and every byte string decodes, if not always to valid UTF-8. A tokenizer whose ids 0–255 are the 256 bytes can encode any input at all, with no unknown token, and decode it back exactly. The cost is length: a character outside ASCII costs two to four ids before any merging, and an emoji four. Merging recovers most of that for the characters the training text uses often.

Between characters and words

Every tokenizer trades sequence length against vocabulary size. At one extreme, a byte or character vocabulary is tiny and the sequences are as long as the text: 469,020 tokens for Persuasion at one per byte. The model spends its context and its compute on spelling, and has to learn from scratch at every position that t, h, e is a word.

At the other extreme, a word vocabulary makes sequences short, one token per word, but the vocabulary is large and still incomplete. Persuasion alone has 7,814 distinct words, counting a word with a leading space and without as different, and 5,759 ignoring case and the space. Every entry costs a row of the (V, d) embedding table and a column of the (d, V) output matrix, and many of those rows are trained on a handful of examples: 3,807 of the book’s 7,910 distinct chunks (defined below) occur exactly once. And the next text will contain words this one lacks.

Subword vocabularies sit between. Frequent words become single tokens; rare words are spelled from frequent pieces; and with bytes underneath, anything at all can still be spelled one byte at a time. Byte-pair encoding is the standard way to choose the pieces.

BPE as greedy compression

Byte-pair encoding was introduced by Gage (1994) as a data-compression algorithm: find the most frequent pair of adjacent symbols, replace every occurrence with a new symbol, record the replacement, and repeat. Sennrich, Haddow and Birch (2016) applied it to words to build subword vocabularies for machine translation, and GPT-2 (Radford et al., 2019) ran it over bytes. Training a BPE tokenizer is exactly Gage’s loop, stopped when the vocabulary reaches the size you want: start from ids 0–255, and merge ii, counting from 0, adds id 256+i256 + i. Below, “merge ii” always means that index, and “token 256+i256 + i” the id it creates.

Why the most frequent pair? Let a token sequence have length NN, and suppose the pair (a,b)(a, b) occurs cc times, counted as the replacement will find them: scanning left to right, and resuming after each match. Each match replaces two tokens by one, so shortens the sequence by exactly 1, and matches do not overlap, so the shortenings add:

N′=N−c. N' = N - c .

Of all the merges available at this step, the one with the largest cc gives the shortest sequence afterwards: the most frequent pair is the largest one-step compression. It is greedy, not optimal. A merge that saves less now can enable larger merges later, and BPE never looks ahead.

“Counted as the replacement will find them” matters only for a run of one repeated symbol. In aaa, the pair (a, a) occurs at two adjacent positions, but the replacement, scanning left to right, merges the first two as and then has one a left over: aa then a, a reduction of 1, not 2. A run of kk copies has k−1k - 1 adjacent pairs but allows only ⌊k/2⌋\lfloor k/2 \rfloor replacements. The training loop below counts adjacent pairs, which is simpler and cheaper, and so overcounts runs. On Persuasion this changes a count once in 768 merges: the pair of two newlines, which becomes token 705, is counted 101 times and shortens the text by 78, because 23 of the chunks it occurs in are runs of four newlines: each holds three adjacent pairs, 69 of the 101 counted, and the replacement merges only two of them.

Pretokenization

Run BPE over Persuasion as one long byte string and it will learn merges across word boundaries: the space and the first letter of the next word, then pairs like e t from “the tea”, which are frequent only because two unrelated frequent words happen to meet. A token for e t is spent on a pair of words, not on either of them, and it makes the same word tokenize differently depending on what follows it.

So text is first cut into chunks that merges may not cross, and BPE runs within each chunk. Chunking is by a regular expression, the one tinygpt.bpe calls PATTERN. It is adapted from the chunking rule of GPT-2’s released encoder, rewritten for Python’s re, which lacks the Unicode classes \p{L} (letters) and \p{N} (numbers):

'(?:s|t|re|ve|m|ll|d)
 ?[^\W\d_]+
 ?\d+
 ?(?:[^\s\w]|_)+
\s+(?!\S)
\s+

The real pattern joins these six alternatives with | on one line; three of them begin with a space. findall takes, at each position, the first alternative that matches:

  • '(?:s|t|re|ve|m|ll|d) splits English contractions with an ASCII apostrophe: don't becomes don and 't. Persuasion uses the curly ’, which this rule does not match, so its contractions fall to the symbol rule.
  • r" ?[^\W\d_]+" is a run of letters, optionally led by one space. \w is letters, numeric characters and underscore; [^\W\d_] is \w minus decimal digits and underscore, which leaves letters, in any script, since a str pattern is Unicode-aware, plus numeric characters that are not decimal digits, such as ², ½ and Ⅻ. So "x²" is one chunk, where GPT-2’s \p{L}/\p{N} split would cut it in two; for English prose the difference does not arise.
  • r" ?\d+" is a run of digits, optionally led by a space.
  • r" ?(?:[^\s\w]|_)+" is a run of everything else, optionally led by a space: punctuation, symbols, emoji, and the underscore.
  • \s+(?!\S) is a run of whitespace not followed by a non-space. In "the cat sat.", at the double space it takes the first space and stops, because the second is followed by s; that second space then becomes part of " sat". The result is ["the", " cat", " ", " sat", "."].
  • \s+ takes whatever whitespace is left, such as a newline before a word.

The leading-space convention attaches the space before a word to the word. " cat" and cat are then different chunks with different ids, but the space costs nothing: in Persuasion 76,100 chunks begin with a space and not one is a lone space, so a vocabulary that learns " the" never spends a separate token on the gap before it.

The explicit _ in the symbol rule is there because the underscore is a \w character that is neither a letter nor a digit. Without it, [^\s\w] excludes _ and the letter and digit rules exclude it too, so no alternative matches an underscore. findall does not fail on characters no alternative matches; it skips them. Without the _, "snake_case x_1" chunks as ["snake", "case", " x", "1"], and the underscores are silently gone from the encoding. With it, the chunks are ["snake", "_", "case", " x", "_", "1"]. The lab’s snake_case test case exists for this: it checks that "".join(pretokenize(text)) == text, which is the property that makes the round trip possible.

The first five merges of byte-pair encoding The string “low lower lowest newer wider” is pretokenized into five chunks: low, space-lower, space-lowest, space-newer and space-wider, shown as rows of byte cells, one box per token. Merge 0: e plus r, count 3, becomes token 256; the chunks are then l | o | w; space | l | o | w | er; space | l | o | w | e | s | t; space | n | e | w | er; space | w | i | d | er. Merge 1: l plus o, count 3, becomes token 257; the chunks are then lo | w; space | lo | w | er; space | lo | w | e | s | t; space | n | e | w | er; space | w | i | d | er. Merge 2: lo plus w, count 3, becomes token 258; the chunks are then low; space | low | er; space | low | e | s | t; space | n | e | w | er; space | w | i | d | er. Merge 3: space plus low, count 2, becomes token 259; the chunks are then low; space low | er; space low | e | s | t; space | n | e | w | er; space | w | i | d | er. Merge 4: space plus n, count 1, becomes token 260; the chunks are then low; space low | er; space low | e | s | t; space n | e | w | er; space | w | i | d | er. the five chunks as raw bytes, one box per token l o w l o w e r l o w e s t n e w e r w i d e r 256 = e + r, count 3 l o w l o w e r l o w e s t n e w e r w i d e r 257 = l + o, count 3 l o w l o w e r l o w e s t n e w e r w i d e r 258 = lo + w, count 3 l o w l o w e r l o w e s t n e w e r w i d e r 259 = space + low, count 2 l o w l o w e r l o w e s t n e w e r w i d e r 260 = space + n, count 1 l o w l o w e r l o w e s t n e w e r w i d e r

The figure runs five merges on low lower lowest newer wider, whose chunks are "low", " lower", " lowest", " newer" and " wider". At the first step four pairs are tied at 3: er, lo, ow and we. The tie goes to the smallest pair of ids, (101, 114), which is e r, for reasons given below. Tokens 257, l o, and 258, lo w, build low in two steps; ow, tied with lo at 3, is gone after lo is merged, because no o is left next to a w. Token 259 attaches the space: " low" occurs twice, and the chunk low without a space keeps its own token, 258. By the fifth merge, which creates token 260, every pair left occurs once, and the smallest, a space and n, wins.

Encoding by merge rank

Training produces an ordered list of merges. Encoding a new chunk replays them: start from the chunk’s bytes, find the adjacent pair with the lowest rank (the earliest merge) among those present, replace every occurrence, and repeat until no adjacent pair is in the merge list.

That this reproduces training’s segmentation needs an argument, since training applied the merges in order to every chunk, including merges that found nothing, while encoding jumps straight to the lowest-ranked pair present. The key fact is that merges never re-create a lower-ranked pair. Merge ii replaces pairs with the new id 256+i256 + i, so the only adjacent pairs it creates contain 256+i256 + i. Every merge j≤ij \le i was recorded before id 256+i256 + i existed, so its pair contains only ids below 256+i256 + i: no pair merge ii creates has rank ii or lower. So once the sequence contains no pair of rank at most ii, it never will again.

Now run the two procedures side by side on one chunk: the ordered replay, which applies merge 0, then merge 1, and so on, as training did; and encoding by rank. Suppose both hold the same sequence, and the replay is about to apply merge j0j_0 with no pair of rank below j0j_0 present. That holds at the start with j0=0j_0 = 0. Encoding by rank picks the lowest-ranked pair present, rank j≥j0j \ge j_0. In the replay, merges j0j_0 to j−1j - 1 find nothing to replace, and then merge jj runs the same _merge on the same sequence. Afterwards pair jj is gone, since a left-to-right scan leaves no unreplaced match, and by the fact above no pair of rank jj or below has been created, so the same situation holds with j0=j+1j_0 = j + 1. When encoding by rank stops, no merged pair is present at all, and the rest of the replay finds nothing to do either. The two end in the same place, and training’s segmentation of a chunk is the ordered replay’s, because training applied each merge to every chunk in order. The lab test test_encode_matches_greedy_merge_order checks this on four chunks against a literal replay of all 144 merges of a 400-token vocabulary.

Decoding, and cutting a character in half

Decoding is concatenation: each id stands for a byte string, vocab[id], so join them and decode the bytes as UTF-8. Nothing forces a token boundary to fall on a character boundary. Merges are learned over bytes, and a frequent prefix of several characters’ encodings becomes a token of its own. Persuasion’s curly quotes ‘ ’ “ ” and dash — are E2 80 98, E2 80 99, E2 80 9C, E2 80 9D and E2 80 94: all start with E2 80, which is so frequent that it is the 28th merge a 1,024-token vocabulary learns, id 283, two bytes that are not a character.

So a single id, or a prefix of an id sequence, can end partway through a character, and decoding it is not valid UTF-8. decode(ids, errors="replace") replaces each malformed stretch with U+FFFD, the replacement character �. That is right for a complete sequence that really is malformed, and wrong for a sequence that is merely incomplete. Chapter 17’s server streams tokens to a client as the model produces them; if it decoded each token by itself, a ’ split across two tokens would reach the client as two replacement characters. It has to buffer bytes until they form complete characters, which UTF-8’s first byte makes easy: it says how many bytes the character needs. llama-server’s /tokenize returns such a piece as a byte array for the same reason.

Deterministic training

When several pairs tie for the highest count, which one wins is arbitrary but must not be accidental. A model’s weights are indexed by token id: row 283 of its embedding table was trained on whatever token 283 was when the data was tokenized. If retraining the tokenizer on the same text, on another machine or with another Python, broke a tie differently, ids would shift, and every row after the first difference would belong to a different token. The model would read garbage. That is why a GGUF file ships its tokenizer’s tokens and merges instead of the recipe for learning them.

BPE.train breaks ties by the smallest pair, comparing (a, b) as tuples of ids, so the result depends only on the text. The pair counts live in a Counter whose iteration order follows insertion, so even max(counts, key=counts.get), with no tie-break, would be deterministic in CPython today, returning whichever tied pair was inserted first, but only through an implementation detail: iterate a set of strings instead, and Python’s per-process hash randomisation reorders it from run to run. An explicit key removes the question.

Compression on Persuasion

Trained on all of Persuasion, a 512-token vocabulary (256 merges) encodes the book in 213,887 tokens, 2.19 bytes per token, and a 1,024-token vocabulary in 163,443, 2.87 bytes per token (the lab’s run, below). The returns diminish quickly. By the length identity above, each merge removes as many tokens as its count. The first, he (token 256), removes 9,855; the one that creates token 511, " one", removes 207; the last, token 1023, " while", removes 50. The first 256 merges remove 255,133 tokens between them, and the next 512 remove 50,444. Each merge adds a row to the embedding table and a column to the output layer whatever it saves, and training data per token thins out as the vocabulary grows: a 1,024-token vocabulary suits a corpus of half a megabyte, where production tokenizers trained on terabytes use vocabularies in the tens or hundreds of thousands.

Walkthrough

The reference module is py/tinygpt/bpe.py.

# Letters, digits, and other non-space symbols form separate chunks, each
# optionally led by one space; runs of whitespace form their own chunks.
# Underscore is a \w character but neither a letter nor a digit, so the
# symbol class names it explicitly: every character lands in some chunk.
PATTERN = re.compile(r"'(?:s|t|re|ve|m|ll|d)| ?[^\W\d_]+| ?\d+| ?(?:[^\s\w]|_)+|\s+(?!\S)|\s+")


def pretokenize(text):
    """Split text into chunks that merges may not cross; "".join(chunks) == text."""
    return PATTERN.findall(text)

pretokenize is findall with the pattern of the mechanism section, which is why its correctness rests on every character being matched by some alternative. The final \s+ matches any whitespace, and the letter, digit and symbol rules together cover every non-space character: letters are \w minus digits and underscore, and the symbol rule takes everything outside \w plus the underscore. The contraction rule only adds a way to match.

def _merge(seq, pair, new_id):
    """Replace every non-overlapping occurrence of pair in seq, left to right, with new_id."""
    out, i = [], 0
    while i < len(seq):
        if i + 1 < len(seq) and seq[i] == pair[0] and seq[i + 1] == pair[1]:
            out.append(new_id)
            i += 2
        else:
            out.append(seq[i])
            i += 1
    return out

_merge is the replacement the length identity counted: left to right, and after a match it skips both tokens, so (a, a) in a a a merges once. Training and encoding share it, so they agree on what a merge does.

@classmethod
def train(cls, text, vocab_size):
    """Learn vocab_size - 256 merges from text, most frequent adjacent pair first."""
    if vocab_size < 256:
        raise ValueError("vocab_size must be at least 256, one id per byte")
    chunks = collections.Counter(pretokenize(text))
    words = [list(c.encode("utf-8")) for c in chunks]
    freqs = list(chunks.values())
    merges = []
    while 256 + len(merges) < vocab_size:
        counts = collections.Counter()
        for w, n in zip(words, freqs):
            for pair in zip(w, w[1:]):
                counts[pair] += n
        if not counts:
            break  # every chunk is a single token: nothing left to merge
        best = min(counts, key=lambda p: (-counts[p], p))  # ties: smallest pair
        new_id = 256 + len(merges)
        merges.append(best)
        words = [_merge(w, best, new_id) if len(w) > 1 else w for w in words]
    return cls(merges)

train never works on the corpus as one sequence. Counter(pretokenize(text)) reduces Persuasion’s 106,480 chunks to 7,910 distinct ones with their frequencies, 61,409 bytes in all, and each iteration counts the pairs in each distinct chunk once, weighted by how often the chunk occurs: the same counts as scanning all 469,020 bytes, since merges never cross chunks, for about an eighth of the work. words holds each distinct chunk’s current token sequence and freqs its count, in matching order.

Each iteration recounts every pair from scratch, picks the winner with the key (-counts[p], p) (highest count, then smallest pair), records it, and applies it to every chunk; a single-token chunk is skipped, since it has no pairs. When no chunk has two tokens left, counts is empty and training stops short of vocab_size: BPE.train("ab ab", 1000) stops at 258. The constructor builds vocab, each new id’s bytes as the concatenation of its pair’s, and ranks, each pair’s merge index, and rejects a merge that refers to an id not yet defined, which a hand-edited or corrupted merges file could contain.

_cache_limit = 1 << 16  # chunks remembered; a server fed unbounded text must not grow it forever

def _encode_chunk(self, data):
    seq = list(data)
    while len(seq) > 1:
        pair = min(zip(seq, seq[1:]), key=lambda p: self.ranks.get(p, len(self.ranks)))
        if pair not in self.ranks:
            break  # no adjacent pair was ever merged
        seq = _merge(seq, pair, 256 + self.ranks[pair])
    return seq

def encode(self, text):
    """Token ids for text: apply the merges to each chunk's UTF-8 bytes in the order they were learned."""
    ids = []
    for chunk in pretokenize(text):
        if chunk not in self._cache:
            if len(self._cache) >= self._cache_limit:
                self._cache.clear()
            self._cache[chunk] = self._encode_chunk(chunk.encode("utf-8"))
        ids.extend(self._cache[chunk])
    return ids

def decode(self, ids, errors="replace"):
    """Concatenate the tokens' bytes and decode as UTF-8; a cut through a character becomes U+FFFD."""
    return b"".join(self.vocab[i] for i in ids).decode("utf-8", errors=errors)

_encode_chunk is encoding by rank. min over the adjacent pairs, keyed by rank, with len(self.ranks) as the rank of a pair never merged, finds the lowest-ranked pair present; if even that one was never merged, no pair was, and the chunk is done. Each pass is a scan of the chunk, and a chunk of nn bytes takes at most n−1n - 1 passes, so a chunk costs O(n2)O(n^2), which is fine because chunks are words.

encode adds a cache from chunk to ids. Chunk frequencies are heavily skewed: in Persuasion the 100 commonest distinct chunks (the newline, ,, " the", ., " to", …) are 60% of all chunks and the 300 commonest are 73%, and encoding the whole book computes only 7,910 chunk encodings for 106,480 chunks. Every other chunk is one dictionary lookup. The cache holds at most _cache_limit chunks, 65,536, and is emptied when it fills: a tokenizer that lives as long as one training run never reaches the limit (Persuasion has 7,910 distinct chunks), and a long-running server fed arbitrary text must not grow it without bound. Emptying the whole cache is cruder than evicting the least recently used entry, and it costs only recomputation. decode is the concatenation and errors passes straight to bytes.decode: "replace" by default, "strict" to raise on malformed input instead.

save writes {"merges": [[a, b], ...]} and load rebuilds from it: the merges determine everything else.

Exercises

(a) Write out the UTF-8 bytes of naïve by hand from the bit patterns, in binary and hex, and check with "naïve".encode("utf-8").

Answer

n, a, v and e are ASCII, U+006E, U+0061, U+0076 and U+0065, one byte each: 01101110, 01100001, 01110110, 01100101. ï is U+00EF, 239, in the two-byte range. Its 11 payload bits are 00011 101111; with the prefixes, 11000011 10101111, which is C3 AF. The whole word is six bytes for five characters:

6E 61 C3 AF 76 65

and "naïve".encode("utf-8").hex(" ") prints 6e 61 c3 af 76 65. é is U+00E9, two below ï, and shares its first byte, C3: every character from U+00C0 to U+00FF does.

(b) Run three merges of BPE by hand on low lower lowest, giving every pair’s count at each step and the tie-break where there is one, and check against BPE.train("low lower lowest", 259).

Answer

The chunks are "low", " lower" and " lowest". Step 1: lo 3, ow 3, " l" 2, we 2, er 1, es 1, st 1. lo is (108, 111) and ow is (111, 119); the smaller wins, and lo becomes 256.

Step 2, on [lo, w], [" ", lo, w, e, r], [" ", lo, w, e, s, t]: (lo, w) 3, (" ", lo) 2, (w, e) 2, and er, es, st 1 each. (256, 119), low, becomes 257.

Step 3, on [low], [" ", low, e, r], [" ", low, e, s, t]: (" ", low) 2, (low, e) 2, the rest 1. The tie is between (32, 257) and (257, 101), and (32, 257), " low", becomes 258. The chunks end as [low], [" low", e, r] and [" low", e, s, t].

>>> BPE.train("low lower lowest", 259).merges
[(108, 111), (256, 119), (32, 257)]

(c) Prove that merging a pair occurring cc times, counted as non-overlapping matches from the left, shortens a sequence by exactly cc tokens. What is the reduction for merging (a, a) in aaaa, and how many times does BPE.train count the pair?

Answer

Let the sequence have length NN and let the left-to-right scan find matches at positions p1<p2<⋯<pcp_1 < p_2 < \cdots < p_c. The scan resumes two positions after each match, so pk+1≥pk+2p_{k+1} \ge p_k + 2 and the matched spans {pk,pk+1}\{p_k, p_k + 1\} are disjoint. The output contains one token per match and one per position not in any span: c+(N−2c)=N−cc + (N - 2c) = N - c tokens.

In aaaa the scan matches at positions 0 and 2, giving aa aa: length 2, a reduction of 2. BPE.train counts adjacent pairs with zip(w, w[1:]), which finds (a, a) at positions 0, 1 and 2: 3. In general a run of kk equal tokens contributes k−1k - 1 to the count and ⌊k/2⌋\lfloor k/2 \rfloor to the reduction; outside such runs the two agree, since two overlapping occurrences of (x,y)(x, y) at positions pp and p+1p + 1 need y=xy = x and x=yx = y.

(d) With a tokenizer trained on Persuasion, " the" and "the" get different ids. Why? What does a prompt that ends in a space do to the next-token distribution of a model trained on text tokenized this way?

Answer

They are different chunks: the pretokenizer attaches a leading space to a word, so " the" (the word after a space, 2,968 times in the book) and "the" (after a newline or at the start of a text) are counted separately by training and merged into separate tokens, 265 and 459 in the 1,024-token vocabulary. "The" is a third, 389.

A prompt ending in a space, "said Anne ", pretokenizes with a final chunk " ", a lone space, and encodes with id 32 last. In Persuasion’s chunks a lone space occurs zero times, because every space before a word is part of the word’s chunk. So the model is asked to continue a context it never saw in training. Worse, the continuation it would naturally produce, " was", carries its own space; after the lone space the text needs "was" spelled without its space, the form a word takes at the start of a line: 61 times in the book, against 1,269 for " was", and never after a space. The model’s distribution at that position is poorly trained and shifted away from the likely words. Remove trailing whitespace from prompts, or back the prompt up by one token and constrain the first generated token to start with the removed text, which some libraries call token healing.

(e) BPE.train recounts every pair in every distinct chunk after each merge. Design an incremental update of the pair counts, and state the cost of one merge.

Answer

Keep, besides counts, an index from each pair to the set of distinct chunks that contain it. When merging (a,b)(a, b) into zz, visit only the chunks in the index entry for (a,b)(a, b). In a chunk ww of frequency nn, for each match at position pp with left neighbour xx and right neighbour yy (if any): subtract nn from the counts of (x,a)(x, a), (a,b)(a, b) and (b,y)(b, y), add nn to (x,z)(x, z) and (z,y)(z, y), and update the index for the pairs added and those whose count in ww fell to zero. Runs need care: when two matches are adjacent, (b,a)(b, a) between them becomes (z,z)(z, z), not (b,z)(b, z) and (z,a)(z, a). The simplest correct approach is to subtract the chunk’s old pair counts and add its new ones for each touched chunk.

Finding the winner is a max over counts; a heap keyed by (-count, pair) with lazy deletion (push a new entry on every change, discard popped entries whose count is stale) makes that O(logP)O(\log P) per change for PP distinct pairs. One merge then costs time proportional to the total length of the chunks containing the merged pair, times logP\log P, instead of the total length of all distinct chunks. Late merges touch few chunks: the last, token 1023, " while", occurs 50 times, where each iteration of the reference loop rescans all 7,910 distinct chunks.

(f) Train a tokenizer on Persuasion with vocab_size=1024 and measure bytes per token on Persuasion, on py/data/tiny-corpus.txt, and on a Go source file of yours. Which is most expensive per byte, and why?

Answer

With go/cmd/aec-doctor/doctor.go from this repository as the Go file:

persuasion.txt  469020 bytes  163443 tokens  2.87 bytes/token
tiny-corpus.txt  61544 bytes   32581 tokens  1.89 bytes/token
doctor.go         1771 bytes    1189 tokens  1.49 bytes/token

Go is the most expensive per byte. The merges are the most frequent pairs in Austen: whole common words with their leading space, suffixes like ently, the curly-quote prefix. "\tif err != nil {" encodes as ["\t", "if", " ", "er", "r", " ", "!", "=", " n", "il", " ", "{"]: err costs two tokens, and each space before a symbol costs one because the book never puts a space before ! or {. The tiny corpus is English, but its words are not the book’s commonest: " queen" is [" qu", "e", "en"], and its " ." costs two tokens because the book never puts a space before a full stop. A tokenizer’s compression is a property of the tokenizer and the text together, which is why the same prompt costs different numbers of tokens with different models, and why production tokenizers train on code as well as prose.

(g) Send a line of your own notes to your llama-server’s POST /tokenize with "with_pieces": true, and tokenize it with a 1,024-token tokenizer trained on Persuasion. Compare the counts, and find a piece the server returns as a byte array.

Answer
import json
import pathlib
import urllib.request

from tinygpt.bpe import BPE

tok = BPE.train(pathlib.Path("data/persuasion.txt").read_text(), 1024)


def server_pieces(text):
    body = {"model": "ornith-1.5-35b-a3b", "content": text, "with_pieces": True}
    req = urllib.request.Request("http://straylight:11434/tokenize", data=json.dumps(body).encode(),
                                 headers={"Content-Type": "application/json"})
    with urllib.request.urlopen(req, timeout=60) as r:
        return [t["piece"] for t in json.load(r)["tokens"]]


for text in ["* TODO Anne’s reply to Captain Wentworth", "ship it 🚢 by Friday"]:
    pieces = server_pieces(text)
    print(f"{len(text.encode())} bytes: server {len(pieces)} tokens, Persuasion {len(tok.encode(text))}")
    print("  server:    ", json.dumps(pieces, ensure_ascii=False))
    print("  Persuasion:", [tok.vocab[i] for i in tok.encode(text)])

Run from py/ with PYTHONPATH=., against the ornith-1.5-35b-a3b model loaded on straylight, captured on 2026-09-29; the server’s llama.cpp build and the GGUF file behind that model name were not recorded, and the server’s pieces depend on that file’s tokenizer:

42 bytes: server 9 tokens, Persuasion 13
  server:     ["*", " TODO", " Anne", "’s", " reply", " to", " Captain", " Went", "worth"]
  Persuasion: [b'*', b' T', b'O', b'D', b'O', b' Anne', b'\xe2\x80\x99', b's', b' rep', b'ly', b' to', b' Captain', b' Wentworth']
22 bytes: server 7 tokens, Persuasion 15
  server:     ["ship", " it", [32, 240, 159], [154], [162], " by", " Friday"]
  Persuasion: [b's', b'hi', b'p', b' it', b' ', b'\xf0', b'\x9f', b'\x9a', b'\xa2', b' by', b' ', b'F', b'r', b'id', b'ay']

The server’s tokenizer spends 9 tokens on the first line and the Persuasion tokenizer 13. Each has merges the other lacks: the server’s has " TODO" and "’s" as single tokens, while Persuasion spells TODO out and has no merge joining the apostrophe to the s; Persuasion has " Wentworth" as one token, because the book repeats it, and the server needs two. The emoji is four bytes, F0 9F 9A A2. The server’s tokenizer merged the space before it with its first two bytes into one token, [32, 240, 159], and left the last two bytes as a token each. None of those three pieces is valid UTF-8 on its own, so /tokenize returns each as a list of byte values: the case this chapter’s opening promised to explain. A server streaming that reply token by token must hold F0 9F until 9A and A2 arrive. The Persuasion tokenizer never saw the emoji: no merge applies inside that chunk, so it stays the space and four single bytes, five tokens.

Lab

Implement BPE.train, BPE.encode and BPE.decode in py/labs/ch07/starter.py. pretokenize, the constructor, vocab_size, save and load are there complete: the chunking rule is a design choice this chapter explains, not the exercise. Run

make lab CH=07 IMPL=mine

until it passes. Read py/labs/ch07/test_lab.py first. The pretokenizer tests pass from the start: ten strings with leading and trailing spaces, tabs and newline runs, underscores, contractions, accented and CJK letters, a combining accent and a zero-width space, digits, emoji and curly quotes must each come back exactly from "".join(pretokenize(text)), and "the cat sat." must chunk as in the mechanism section. The rest pin your code. An untrained BPE([]) must encode "aé" as the bytes [0x61, 0xC3, 0xA9]. Training on "aaab aaab aaab" must pick (a, a) first; on "dcab", where three pairs tie at 1, it must pick (97, 98); on "ab ab" it must stop at 258 however large a vocabulary is asked for; and a vocab_size below 256 must raise ValueError. No learned token may contain a space except as its first byte. A 400-token vocabulary trained on the first 12,000 characters of Persuasion must round-trip all ten strings and the sample exactly, compress the sample below 0.6 tokens per byte, agree with a literal ordered replay of its merges, decode the lone byte 0xC3 as U+FFFD, survive save and load, and come out the same when trained twice.

Then train on the whole book. Save this script outside the repository, for example as /tmp/bpe_lab.py:

import pathlib
import time

from tinygpt.bpe import BPE

text = pathlib.Path("data/persuasion.txt").read_text()
n_bytes = len(text.encode("utf-8"))
print(f"{len(text)} characters, {n_bytes} bytes")
for vocab_size in [256, 512, 1024]:
    start = time.time()
    tok = BPE.train(text, vocab_size)
    seconds = time.time() - start
    ids = tok.encode(text)
    assert tok.decode(ids) == text
    print(f"vocab {vocab_size:4d}: {len(ids):6d} tokens, {n_bytes / len(ids):.2f} bytes/token, trained in {seconds:.1f}s")
tok = BPE.train(text, 1024)
print("first merges:", [tok.vocab[256 + i].decode() for i in range(10)])
print("last merges: ", [tok.vocab[i].decode() for i in range(1014, 1024)])
print("Anne Elliot:", [tok.vocab[i] for i in tok.encode("Anne Elliot’s")])

and run it from py/ with PYTHONPATH=. uv run python /tmp/bpe_lab.py. Change the import to from labs.ch07.starter import BPE to run yours. The reference prints:

464441 characters, 469020 bytes
vocab  256: 469020 tokens, 1.00 bytes/token, trained in 0.0s
vocab  512: 213887 tokens, 2.19 bytes/token, trained in 3.7s
vocab 1024: 163443 tokens, 2.87 bytes/token, trained in 12.4s
first merges: ['he', ' t', ' a', 'in', ' w', ' s', 'er', ' o', 'ha', ' the']
last merges:  [' interest', 'mer', 'sw', 'vant', ' count', ' bec', 'ently', 'cei', 'light', ' while']
Anne Elliot: [b'Anne', b' Elliot', b'\xe2\x80\x99', b's']

The token counts and merges of a correct implementation match exactly, since training is deterministic; the times depend on your machine, and these are from talos, a laptop with an Intel i3-1315U.

  • The first merges are the pieces of the commonest English words: he, then a space before t, a, w, s and o, and by the tenth " the", built from " t" and he. The last ones are word fragments (sw, cei) and less common whole words, each of which occurs about 50 times.
  • Doubling the merges does not double the gain. The first 256 merges take the book from 469,020 tokens to 213,887; the next 512 take it to 163,443. Going from 512 to 1,024 cuts the length by 24% and doubles the size of the embedding table and output layer.
  • ’ is one token. The three bytes E2 80 99 of the apostrophe became a single id, reached through the merge E2 80 that also starts the other curly quotes and the dash. Anne and " Elliot" are whole tokens, as frequent names in the book should be, and the possessive s stands alone after the apostrophe, because the chunking rule’s contraction case matches only the ASCII '.
  • Training time grows with the number of merges, since each one recounts every pair: 3.7 s for 256 merges, 12.4 s for 768. Exercise (e) is the fix.

Further reading

  • Philip Gage, “A New Algorithm for Data Compression”, The C Users Journal 12(2) (February 1994). Byte-pair encoding as a compressor: repeatedly replace the most frequent pair of bytes with an unused byte value, recording the table for the decompressor.
  • Rico Sennrich, Barry Haddow and Alexandra Birch, “Neural Machine Translation of Rare Words with Subword Units”, Proceedings of ACL (2016). BPE applied to words to learn a subword vocabulary, so that a translation model can handle rare and unseen words as sequences of pieces.
  • Alec Radford, Jeffrey Wu, Rewon Child, David Luan, Dario Amodei and Ilya Sutskever, “Language Models are Unsupervised Multitask Learners” (OpenAI, 2019). The GPT-2 paper; its section on input representation motivates byte-level BPE and the rule that merges must not cross character categories.
  • F. Yergeau, “UTF-8, a transformation format of ISO 10646”, RFC 3629 (2003). The UTF-8 specification: the bit patterns, the limit at U+10FFFF, and which byte sequences are invalid.
  • Taku Kudo and John Richardson, “SentencePiece: A simple and language independent subword tokenizer and detokenizer for Neural Text Processing”, Proceedings of EMNLP: System Demonstrations (2018). The tokenizer library behind the llama value of tokenizer.ggml.model: it treats the input as a raw stream with whitespace as an ordinary symbol, so no language-specific pretokenizer is needed.

results matching ""

    No results matching ""