CodeRigor

LESSON

A byte-pair tokenizer

Turn text into UTF-8 bytes, learn merges by counting adjacent pairs, then encode by merge rank and decode back, with every round trip checked against a slow oracle.

A language model reads integers, not text. A tokenizer is the fixed, reversible map between the two, and it is built before the model is trained. This lesson pairs with Let's build the GPT Tokenizer by Andrej Karpathy, linked under Watch & read. You build that map in plain Python: count pairs, merge them, learn a vocabulary from a text, then encode with it and decode back.

Start from bytes. text.encode("utf-8") turns any string into integers from 0 to 255, so a vocabulary of 256 ids can write every possible text and never meets an unknown character. Letters of the English alphabet take one byte, é takes two and the rocket emoji takes four.

Python
s = "café 🚀"
data = s.encode("utf-8")
print(len(s), len(data), list(data))
print(list("é".encode("utf-8")), list("🚀".encode("utf-8")))

Byte-pair encoding grows the vocabulary by repetition. Count every adjacent pair of ids, take the most frequent pair, give it the next unused id (256 first) and replace the pair everywhere. The text is now shorter, and the new id can take part in new pairs. Repeat until the vocabulary has the size you asked for or no pair is worth merging. What you keep is the list of merges in the order they were learned, each written as ((a, b), new_id). That list is the tokenizer.

Three merges shrink eleven bytes to five ids
start / 4
Training on aaabdaaabac. Each step merges the most frequent pair into the next id: 256, 257, 258.
Three merges shrink eleven bytes to five ids
Training on aaabdaaabac. Each step merges the most frequent pair into the next id: 256, 257, 258.

Merging needs care. Scan from the left, and when the pair matches, write the new id and skip both ids that matched. In [97, 97, 97] the pair (97, 97) starts at position 0 and at position 1. The first match uses both of its ids, so the result is [256, 97]. A loop that moves on by one after a match reuses the middle id and turns three ids into two merged tokens, which no longer spell the text.

Python
def pair_counts(ids):
    counts = {}
    for pair in zip(ids, ids[1:]):
        counts[pair] = counts.get(pair, 0) + 1
    return counts


def merge(ids, pair, new_id):
    out, i = [], 0
    while i < len(ids):
        if i + 1 < len(ids) and (ids[i], ids[i + 1]) == pair:
            out.append(new_id)
            i += 2
        else:
            out.append(ids[i])
            i += 1
    return out


ids = list(b"aaabdaaabac")
counts = pair_counts(ids)
print(sorted(counts.items(), key=lambda kv: (-kv[1], kv[0]))[:2])
print(merge(ids, (97, 97), 256))
print(merge([97, 97, 97], (97, 97), 256))

Two rules make training repeatable. When two pairs have the same count, merge the smaller pair, comparing the tuples. Without that rule the winner depends on dictionary order, and two correct-looking trainers disagree. And stop when the best pair occurs only once: merging it would replace two ids by one and spend a vocabulary entry on something that will rarely come up again. Count over the current ids each round, not over the original bytes, because merged ids form pairs of their own.

Encoding a new text ignores that text's own counts. Replay the merges in the order they were learned: among the pairs present, apply the one with the lowest merge id, then look again. Order matters because a merge such as (256, 257) only makes sense after 256 and 257 exist. Choosing the most frequent pair in the new text is a tempting shortcut. It still produces ids that decode to the right string, so a round trip cannot reveal it, but they are not the ids the vocabulary was trained to produce.

Python
def merge(ids, pair, new_id):
    out, i = [], 0
    while i < len(ids):
        if i + 1 < len(ids) and (ids[i], ids[i + 1]) == pair:
            out.append(new_id)
            i += 2
        else:
            out.append(ids[i])
            i += 1
    return out


rank = {(98, 99): 256, (97, 98): 257}
by_rank = by_count = list(b"abcabbab")
while True:
    present = [p for p in zip(by_rank, by_rank[1:]) if p in rank]
    if not present:
        break
    by_rank = merge(by_rank, min(present, key=rank.get), rank[min(present, key=rank.get)])
while True:
    present = [p for p in zip(by_count, by_count[1:]) if p in rank]
    if not present:
        break
    best = max(present, key=present.count)
    by_count = merge(by_count, best, rank[best])
print(by_rank)
print(by_count)

Decoding runs the other way. Build a table in which ids 0 to 255 stand for one byte each and every merge adds the bytes of its two parts. Join the bytes of all the ids, then decode them as UTF-8. An id sequence that a model produced can cut a multi-byte character in half, so decode with errors="replace" and accept the replacement character U+FFFD instead of a crash. An id that is neither a byte nor a merge is a real error and raises ValueError.

Encode and decode are two walks over the same merge list
start / 4
Encoding goes down to bytes and merges upward by rank. Decoding expands every id through a byte table and reads the bytes as UTF-8.
Encode and decode are two walks over the same merge list
Encoding goes down to bytes and merges upward by rank. Decoding expands every id through a byte table and reads the bytes as UTF-8.

The mistakes follow from the steps above. Letting a merge overlap itself. Encoding by frequency instead of by rank. Breaking ties by whatever the dictionary returns. Counting pairs once on the original bytes and never again. Treating a token as a whole character: tokens are made of bytes, so one id can hold half of an emoji.

The tests check the result against slower code that cannot share your mistakes. One trainer counts pairs with nested loops and merges by string replacement. The encoder is compared with replaying every merge in learned order, and round trips run over accents, Japanese text and emoji. That evidence shows your functions do what the specification says. It does not show that the vocabulary is good: a vocabulary learned from a few sentences compresses those sentences well and may split other text into many single bytes, and no test here measures what helps a language model.

Watch & read

Free lectures, talks and readings that cover this skill from another angle. All resources →

Covers Unicode and UTF-8, the byte-pair encoding algorithm, counting and merging pairs, training with a loop, then encoding and decoding. Watch the algorithm and implementation chapters first, then build your own version here against a different oracle.