All courses

Byte-pair encoding tokenizers

Train BPE by repeatedly merging the most frequent adjacent pair, and encode new text by applying the merges in order. Explain how starting from bytes guarantees any string can be encoded.

Builds on: Why subword tokens: characters vs words

▶ Watch this lesson Start the whole course

What the animation says

Any text, no unknowns

A tokenizer needs a fixed vocabulary of tens of thousands of pieces. And it must split any text into them: typos, code, Chinese, emoji. There can be no 'unknown' token. Byte-pair encoding starts from bytes. UTF-8 stores every string as numbers from zero to two fifty-five. An English letter is one byte. An accented e is two. This emoji is four. So the starting vocabulary is just those 256 byte values. Predict: what happens to text the tokenizer has never seen, like a brand-new typo?

Count pairs, fuse the winner

It always encodes. In the worst case, you get one token per byte. Now training. Here's a tiny corpus: hug ten times, pug five, pun twelve, bun four, hugs five. Count every adjacent pair, weighted by how often each word appears. u then g shows up twenty times, the most. So fuse u and g into one new token, number two fifty-six, everywhere. Then write that merge down. Now recount. Which pair wins merge two?

The merge list

u n wins with sixteen. p u fell to twelve, because pug now holds ug instead. Merge two: u plus n becomes un. Recount again. h followed by ug: fifteen. Merge three: h plus ug becomes hug. Each merge adds one token. Three merges give two fifty-six plus three. Real tokenizers run tens of thousands of merges. Common words become single tokens, and rare words stay in pieces. What training produces is this ordered list.

Encode: replay in order

To encode new text, take its bytes and replay the merges, in the order they were learned. Each merge sweeps the whole sequence, left to right, before the next one starts. Take 'thugs'. Merge one: u g becomes ug. Merge two finds no u followed by n. Merge three: h and ug become hug. The result is t, hug, s. The letter t never appeared in the corpus, but it's a byte, so it's a token. Your turn: with the same three merges, how is 'puns' encoded?

Byte-level BPE in code

p, un, s. A token exists only if some merge built it. Here's training in Python. It counts adjacent pairs, takes the commonest, records it, and merges it. That repeats n times. The merge helper swaps each hit for the new id, left to right, never overlapping. Encoding is shorter. Bytes go in, then every merge is replayed in order. The new id is 256 plus the merge's position. Real tokenizers also split on word boundaries first, so merges never cross words. This toy skips that. Tap the line that guarantees any string can be encoded.

Who decides what the subword tokens are?

Subwords are the compromise between characters and words, but *which* subwords? A tokenizer needs a fixed vocabulary of tens of thousands of pieces. It also needs a rule that splits **any** text into those pieces, including typos, code, Chinese and emoji, with no "unknown" fallback. Byte-pair encoding (BPE) does both. It learns the pieces by counting, and its starting point makes every string encodable.

Start from bytes, fuse the commonest pair

Computers store all text as bytes, numbers from 0 to 255. The standard scheme, UTF-8, uses 1 byte per English letter and 2–4 bytes for other characters. Begin with the 256 possible byte values as tokens. Write the training text as bytes. Find the adjacent pair that occurs most often, say `t` followed by `h`. Fuse it into one new token `th` everywhere, and record that merge. Recount and repeat: `th`+`e` may come next. Each merge adds one token. Frequent words end up as single tokens, and rare words stay as several pieces. To encode new text, take its bytes and replay the merges in recorded order.

The BPE algorithm

**Train:** set ids ← UTF-8 bytes of the corpus and vocab = {0,…,255}. For $j=1\ldots n$: 1. Count every adjacent pair $(a,b)$. 2. Pick the most frequent pair and give it the new id $255+j$. 3. Replace its non-overlapping occurrences, left to right. 4. Append $(a,b)$ to the merge list. The result has $V = 256 + n$. **Encode:** take the bytes, then apply merge 1, merge 2, …, merge $n$ in that order. Most production tokenizers first apply pre-tokenization, so merges never cross word boundaries.

Three merges by hand

Word counts: hug×10, pug×5, pun×12, bun×4, hugs×5. Each letter is one byte, so it is already a base token. - Pair counts: u g = 10+5+5 = **20**, p u = 17, u n = 16, h u = 15. Merge 1: u+g→`ug`. - Recount: u n = **16**, h ug = 15, p u = 12. Merge 2: u+n→`un`. - Recount: h ug = **15**, p un = 12. Merge 3: h+ug→`hug`. Encode "thugs": t h u g s → (1) t h ug s → (2) no match → (3) **t, hug, s**. The letter t never appeared in the corpus, yet it is still a token.

Byte-level BPE in 13 lines

`text.encode()` turns *any* string into bytes 0–255, and all of them are in the base vocabulary. For example, `é` → [195, 169] and 😀 → 4 bytes. Encoding can never fail. In the worst case you get one token per byte, and merges only shorten that. To encode new text: `ids = list(s.encode())`, then `for j, p in enumerate(merges): ids = merge(ids, p, 256+j)`. This toy version skips pre-tokenization.
from collections import Counter
def merge(ids, pair, new):
    out, i = [], 0
    while i < len(ids):
        hit = tuple(ids[i:i+2]) == pair
        out.append(new if hit else ids[i]); i += 2 if hit else 1
    return out
def train(text, n):  # returns merges in learned order
    ids, merges = list(text.encode()), []
    for j in range(n):
        merges.append(Counter(zip(ids, ids[1:])).most_common(1)[0][0])
        ids = merge(ids, merges[-1], 256 + j)
    return merges

Remember this

BPE starts from the 256 byte values and repeatedly fuses the most frequent adjacent pair into a new token, recording each merge. New text is encoded by replaying those merges in the learned order. Every string is a sequence of bytes and every byte is a token, so nothing is ever unencodable. Unfamiliar text just costs more tokens.

On Bytewise this lesson comes in small steps with a check at the end, and the app brings it back right before you would forget it.