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
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.
Start from bytes, fuse the commonest pair
The BPE algorithm
Three merges by hand
Byte-level BPE in 13 lines
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
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.
Bytewise
All courses