Lecture 17 · Animations
Text
How byte-pair encoding builds a subword vocabulary one merge at a time, and why the vocabulary it builds cannot miss. Press Step to advance one merge and read what happened; press Play to let it run.
All data on this page is synthetic: the corpus is a made-up list of sixteen review words. Reset always gives back the same picture.
1Byte-pair encoding, one merge at a time
A tiny training corpus of sixteen words, each with how often it occurs. Every word starts as single characters. Each step counts every adjacent pair of tokens across the corpus (weighted by the word's count), merges the commonest pair everywhere, and adds the result to the vocabulary. On the right, the pair counts the next step will choose from. At the bottom, four words that are not in the corpus, split with the merges learned so far.
For a corpus of words $w$ with counts $n_w$, the count of an adjacent pair $(a, b)$ is
$$\text{count}(a, b) = \sum_{w} n_w \, m_w(a, b),$$where $m_w(a, b)$ is the number of places in $w$ where token $a$ is directly followed by token $b$.
Each merge picks the pair with the largest count (ties go to the pair met first in the corpus list), replaces every occurrence of $a\,b$ by the new token $ab$, and adds $ab$ to the vocabulary. A merge of a pair with count $n$ removes exactly $n$ tokens from the corpus. New text is split by replaying the merges in the order they were learned. Training stops here when no pair occurs twice.
- The first four merges build
watchletter by letter: it is the commonest stem in the corpus. - After merge 18, the unseen word
unwatchablesplits asun+watch+able: three pieces the model has vectors for, and the negation survives. - Merge 36 produces
uncle, fromunclear: a merge is chosen by counting, and knows nothing about meaning.
- Step to merge 18 and read the token count in the side panel: each merge removed exactly as many tokens as its pair count.
- Play to the end. Every corpus word becomes a single token, but the unseen words never do: they stay as pieces, and nothing is ever out of vocabulary, because the single characters are never removed.