Subword Tokenization as Compression: BPE, WordPiece, and Unigram LM
Three ways to spell an open vocabulary with a closed one — greedy merges, likelihood merges, and a probabilistic lattice — compared as codes, and tested against a morphology we planted
Overview & Motivation
The previous topic ended with a warning. Heaps’ law says a corpus keeps meeting new word types as it grows, and a vocabulary of fixed size cannot keep pace: its coverage saturates while the text does not. Here is the warning in numbers. Train a word vocabulary on the finance corpus — tokens, word types — and read fresh documents from the same generator. They contain word types the vocabulary has never seen: colevys, nonroyaltys, supplierers, crosspremium. That is only of the held-out tokens, but every one of them is a word the model cannot represent, and over half the training vocabulary () was seen exactly once anyway.
The way out is to stop treating words as atoms. A subword tokenizer keeps a fixed inventory of pieces — letters, frequent fragments like in, ing, non, and whole frequent words — and spells every word as a sequence of pieces. nonroyaltys is unseen, but non, royalty, and s are not.
That raises three questions this topic answers with proofs:
- Which inventories work, and how many ways are there to spell a word? Every word can be spelled exactly when the inventory contains the alphabet, but a word of letters has up to spellings, so choosing one is a search problem.
- How do we choose the inventory? Three standard answers. BPE repeatedly merges the most frequent adjacent pair. WordPiece merges the pair that most increases the likelihood of the data. The Unigram LM starts large, gives every piece a probability, and prunes. We show what each one optimizes, where greedy merging falls short of the best possible merges, and why the likelihood criterion is a pointwise mutual information in disguise.
- In what sense is this compression? All three are codes. We compare them in bits, find that a two-part description length prefers neither letters nor words, and then test them against a corpus whose rare words were built from known morphemes.
The laboratory below lets you watch both mechanisms before the algebra. In panel A, run BPE or WordPiece for more merges and watch the words fuse into pieces; the lower strip shows the Unigram LM’s spelling at the same vocabulary size, and the gold marks show where the corpus generator actually joined morphemes. Panel B draws one word’s lattice — every way to spell it — with arc widths set by probability; it will make full sense after the section on the Unigram LM.
Arcs below a posterior of 0.005 are not drawn. The sandwich of Proposition 7 holds for every word and size: the Viterbi code wastes at most log₂|Seg(x)| bits over the marginal code, and in practice a fraction of a bit.
The open-vocabulary problem
Fix a finite alphabet — here the lowercase letters — and let be the nonempty strings over it. Training data is a collection of words with counts; tokenizers work inside words, so no piece ever crosses a space.
Definition 1 (Vocabulary and segmentation).
A vocabulary is a finite set of pieces. A segmentation of a string is a tuple whose concatenation equals . We write for the set of segmentations of . Encoding chooses one segmentation; decoding concatenates its pieces.
Proposition 1 (Completeness).
Every string has at least one segmentation if and only if . In that case decoding inverts every encoding.
Proof.
If , the letters of themselves form a segmentation. Conversely, if some letter is missing from , every piece of a segmentation of the one-letter string would have to be a nonempty substring of , which is itself — so there is none. Decoding concatenates the pieces, and by definition they concatenate to .
∎This is the whole fix for the open vocabulary: keep the letters, and no word is ever out of reach. The harness confirms it on every one of the unseen held-out words. The price is choice. If many fragments are pieces, a word can be cut many ways.
Proposition 2 (Counting segmentations).
If every substring of is a piece and , then . If pieces are limited to length at most , then , where and — the -step Fibonacci numbers.
Proof.
A segmentation is determined by which of the gaps between adjacent letters are piece boundaries, and when every substring is a piece, every subset of gaps occurs: choices. With pieces of length at most , sort the segmentations of the first letters by the length of their last piece; removing that piece leaves a segmentation of the first letters, and every such pair arises once.
∎A sixteen-letter word has segmentations when every fragment is allowed. No tokenizer enumerates them; each of the three below either builds the segmentation up greedily or finds the best one by dynamic programming.
BPE: greedy compression
Byte-pair encoding began as a file compressor (Gage 1994): find the most frequent pair of adjacent bytes, replace it everywhere by a new symbol, repeat. Sennrich, Haddow, and Birch (2016) applied the same loop to the letters of words.
Definition 2 (Merges and merge sequences).
To merge the pair in a token sequence, scan left to right and replace each adjacent occurrence of followed by with the single token , resuming the scan after the new token, so that no two replacements overlap. Let be the number of replacements. A merge sequence defines vocabularies and . Rank replay encodes a word by starting from its letters and applying merges in order.
Definition 3 (Greedy BPE and utility).
BPE training chooses, at each step, the pair with the largest window count — the number of adjacent positions , summed over the training words with their counts — and merges it in every word. Ties go to the pair that comes first in a fixed order of tokens: letters alphabetically, then merged tokens in the order they were created. The utility of a merge sequence on a text is the number of tokens it saves.
On the finance corpus the first ten merges are in, an, er, re, en, ed, es, or, an·d, th, with window counts from down to : English inflection and function words surface first. Each merge buys exactly what it replaces — with one subtlety.
Proposition 3 (Merge accounting).
Merging shortens a token sequence by exactly , the number of replacements. If , then equals the window count of . If , a maximal run of consecutive copies of contains windows but yields only replacements.
Proof.
Each replacement consumes two tokens and emits one, and every other token is copied, so the length falls by . If , two occurrences cannot overlap: windows at positions and would require and at once. The scan skips only the second token of a window it has just replaced, and that token cannot start another occurrence, so every occurrence is replaced and equals the window count. If , the scan pairs a run’s tokens as , giving replacements; distinct runs are separated by other tokens and do not interact.
∎So the count BPE ranks by over-values runs: aaaa shows three windows of , but merging saves only two tokens. In letters of English words the effect is small, but it is the first sign that BPE’s ranking is a proxy for compression rather than compression itself.
Proposition 4 (Rank replay reproduces training).
Replaying merges on a training word yields exactly that word’s segmentation after training merges. Moreover, the first merges of a greedy run of any length are the -merge model.
Proof.
Training applies merge to every word’s current sequence with the same deterministic map that replay applies, starting from the same letters; induct on . For the second claim, greedy’s choice at step depends only on the state after merges and on a deterministic tie rule, not on how many merges will follow.
∎Prefix-closure is why a single long training run gives every smaller vocabulary for free, and why the laboratory’s merge slider is honest: the -merge model is the first merges of the -merge model. The companion code checks its trainer against Hugging Face’s tokenizers library on the same corpus: the two merge lists agree exactly for all merges, and the two encoders agree on every held-out word.
Greedy is not optimal
BPE is greedy: it never revisits a merge. Is the most frequent pair always the best next step? No — and the gap is fundamental, not a matter of tuning.
Theorem 1 (Optimal merging is hard — cited).
(i) Finding a merge sequence of maximum utility on a string is APX-complete; greedy BPE always achieves at least of the optimal utility, and there are inputs on which it achieves at most of it (Kozma and Voderholzer). (ii) The decision versions of both bottom-up tokenization (choosing merges) and direct tokenization (choosing a vocabulary) are NP-complete (Whittington, Bachmann, and Pimentel 2025). (iii) Greedy BPE achieves a fraction of the optimal utility, where measures the curvature of the utility function (Zouhar et al. 2023).
We do not prove these results here; their proofs are reductions and submodularity arguments well outside this topic. What we can do is exhibit the failure. Exhaustive search over all strings of length at most nine on alphabets of size at most three finds the shortest strings on which every greedy run — however ties are broken — loses. They have nine letters, and up to renaming the letters there are two, and ; here is the first:
Example 1 (aaaabaaab with three merges).
In the pair makes three replacements (two in the first run, one in the second), more than any other pair, so greedy must merge it first: . Every pair left now occurs once, and two more merges save two more tokens: utility in every greedy run. The optimum instead merges , then , then , building the repeated unit and ending at — utility . Greedy’s forced first move breaks both copies of the structure the optimum exploits.
On random short strings every greedy run stays above the guaranteed of the optimum, and some fall strictly short of it — consistent with Theorem 1, which is the actual guarantee.
WordPiece: a likelihood criterion
WordPiece (Schuster and Nakajima 2012) keeps BPE’s merge loop but changes the question. Instead of which pair is most frequent, it asks which merge makes the training data most probable under a unigram model of the current tokens. Write for the count of token in the training data and . The maximum-likelihood unigram model is , and its log-likelihood is
Proposition 5 (The likelihood gain of a merge).
If merging with makes replacements, then the exact change in is
and it decomposes as
Proof.
A merge changes only four quantities: and each fall by , the new token goes from count to , and falls to . Substituting into gives the first display. For the second, fix , put , and let . Expanding gives
Now , , and , so . Setting gives . Applying the identity to , , and and collecting terms, the leading part is , as claimed.
∎The leading term reads , where is the pointwise mutual information of the pair and . BPE ranks by alone; WordPiece weights by how much more often and occur together than independence would predict. It prefers cohesive pairs, whose parts occur together far more often than chance. On the finance corpus the two agree on in and an, then split at the third merge: BPE takes , with count ; WordPiece takes , with a gain of nats, because an is followed by d far more often than chance. The harness checks the exact formula against a recount for the first WordPiece merges and the remainder bound on random instances.
The tokenizers also differ in how they encode. BPE replays its merges. WordPiece’s encoder, MaxMatch, repeatedly takes the longest vocabulary piece that starts the remaining text. The Unigram LM of the next section takes the most probable segmentation. Given the same vocabulary these are three different functions: with WordPiece’s -piece vocabulary, acquisition comes out as a c qu i s it ion under MaxMatch but a c qu i s i tion under replay.
The Unigram LM
The Unigram LM (Kudo 2018) turns tokenization into probability. Instead of a merge history it keeps a probability for every piece, scores a whole segmentation, and picks the best one.
Definition 4 (Unigram LM).
A Unigram LM is a probability vector on a vocabulary . A segmentation has probability , and a string has marginal probability . Encoding uses the Viterbi segmentation .
Picture the segmentations of a word as paths. Put a node at each of the gaps of an -letter word, from before the first letter to after the last, and draw an arc from gap to gap whenever — letters through — is a piece. Every segmentation is a path from the first node to the last, and its log-probability is the sum of its arcs’ weights . That graph is the lattice in panel B of the laboratory. Finding the best segmentation is finding the heaviest path, which dynamic programming does in one sweep.
Theorem 2 (Viterbi decoding).
Let pieces have length at most , set , and for let
with when no qualifies. Then , and it is exactly when has no segmentation. The recursion uses vocabulary lookups, and recording the maximizing at each recovers .
Proof.
We show by induction on that is the largest log-probability of a segmentation of the prefix . For the empty segmentation has log-probability . Every segmentation of consists of a segmentation of some prefix followed by one last piece , and its log-probability is the sum of the two parts. Maximizing over the last piece and then over the segmentations of gives by the induction hypothesis. If no last piece is in , there is no segmentation and the maximum over an empty set is .
∎Replacing the maximum by a sum gives the total probability of all paths.
Proposition 6 (Forward–backward and the lattice posteriors).
Let , , and symmetrically , . Then . The posterior probability that the segmentation uses the piece from gap to gap is
and for every letter position , the posteriors of the arcs covering it sum to one: .
Proof.
The induction of Theorem 2 with sums in place of maxima, using the distributive law, gives as the total probability of all segmentations of ; the same holds for from the right. The segmentations that use the arc are exactly a segmentation of , then , then a segmentation of , so their total probability is ; dividing by gives . Each segmentation has exactly one piece covering position , so summing over the covering arcs sums over every segmentation, which is .
∎The arc widths in panel B are these posteriors. Try underwriting at : many arcs are possible, but nearly all the probability flows along a handful of them.
Training by EM
The piece probabilities are learned from data, and the segmentations are hidden. This is the setting of expectation–maximization: guess , compute the expected number of times each piece is used under the posterior of Proposition 6, renormalize those expected counts into a new , and repeat.
Theorem 3 (EM never lowers the likelihood).
Fix and a Unigram LM . For training words with counts , let be the posterior over under , and let
be the expected count of piece . Then the update satisfies , where .
Proof.
For any model , Jensen’s inequality applied to the concave logarithm gives
with equality when , because then the ratio inside is the constant . Weight by , sum over words, and subtract the equality case: , where . Write . Then , which Gibbs’ inequality, (see KL Divergence), maximizes exactly at . Hence .
∎EM climbs; it does not promise the top. The vocabulary itself is chosen by a heuristic. Starting from the letters and the most frequent substrings (scored by count times length), training alternates two EM steps with pruning: drop the non-letter pieces whose removal costs the least likelihood, estimated by SentencePiece’s rule of reassigning each piece’s Viterbi frequency to its best alternative spelling (Kudo and Richardson 2018). Each round drops a quarter of the current vocabulary’s size, letters included in the count, or fewer if that would overshoot the next target size. Letters are never pruned, so Proposition 1 always applies. We stop at . Our M-step is the plain maximum-likelihood update of Theorem 3; SentencePiece itself uses a smoothed variant. As a check that our decoder is the standard one, we train SentencePiece on the same text and feed its piece scores to our Viterbi: it reproduces SentencePiece’s own spelling of every held-out word.
Tokenization as compression
A Unigram LM is a code. Spending bits on piece is the Shannon code for the distribution (see Shannon Entropy & Mutual Information), so a segmentation costs bits, and the Viterbi segmentation is the cheapest single spelling. A cleverer coder could charge for the word as a whole, bits, summed over all spellings. The two are never far apart.
Proposition 7 (The segmentation sandwich).
For every string with at least one segmentation,
Proof.
The gap equals , the posterior surprisal of the Viterbi segmentation, which is nonnegative. Since has the largest posterior among possibilities, , which bounds the gap by .
∎The Viterbi code wastes exactly the surprisal of its own choice; “bits-back” coding (Townsend, Bird, and Barber 2019) is a way to recover it. In practice there is little to recover. At , nonroyaltys costs bits under its Viterbi spelling non · royalty · s and bits marginally, although would allow a gap of over four bits. The lattice’s posterior is concentrated, which panel B shows as one thick path.
How large should the vocabulary be?
Compression also suggests a way to choose . A bigger vocabulary spells the corpus in fewer, likelier tokens, but the vocabulary itself must be described. The two-part code of minimum description length (Rissanen 1978; see Minimum Description Length) charges for both:
where spells each piece letter by letter with an end marker, and codes the training tokens under their own maximum-likelihood unigram model. Along BPE’s merge path on the finance corpus:
| vocabulary | two-part code length |
|---|---|
| letters only | bits |
| BPE after merges ( pieces) | bits — the minimum |
| whole words ( types) | bits |
Too few pieces make the data long; too many make the lexicon long. The minimum sits between letters and words, which is the trade-off morphology learners like Morfessor were built around (Creutz and Lagus 2007). Where exactly it falls depends on how we chose to code the lexicon, so we read it as an argument for subwords, not as a law fixing .
The open vocabulary of the previous topic is now closed in the useful sense. Of the training corpus’s word types, occur once; of the pieces BPE uses at , do. Rare words have become combinations of common parts.
Finance case study: planted morphemes
Where this goes next
- Perplexity needs a unit. A language model over subword tokens reports perplexity per token, and changing the tokenizer changes the token count. Comparing models across tokenizers requires normalizing per character or per word — the subject of the later topic on perplexity and cross-entropy, which also makes the compression reading of this topic exact.
- n-grams over pieces. The n-gram models of the next language-modeling topic work over whatever tokens the tokenizer produces; subwords trade a sparse word vocabulary for longer sequences.
- Better criteria. Beyond compressed length, Zouhar et al.’s Rényi efficiency is an empirical predictor of how well a tokenizer will serve a translation model — a correlation, not a theorem.
Honest caveats
Implementation
The companion notebook (notebookPath) imports subword_tokenization_bpe_unigram.py, which owns every number on this page. Running it as a script executes a harness of assertion-based tests in about ten seconds on a laptop CPU. The tests cover:
- Propositions 1–4 on random inputs and on the corpus, including the run-counting subtlety of Proposition 3.
- Agreement with Hugging Face
tokenizers(identical merge lists and encodings) and withsentencepiece(identical Viterbi spellings). - The greedy counterexample by exhaustive search, and the guarantee on random strings.
- Proposition 5’s exact formula against recounts, and its remainder bound.
- Viterbi and forward–backward against brute-force enumeration, the posterior coverage identity, and EM’s monotonicity.
- The segmentation sandwich on every held-out word, the two-part code’s interior minimum, and the three beats of the finance case study.
The laboratory reads its data from a JSON file that one of those tests requires to equal the module’s viz_payload() exactly, so the figure cannot drift from the code.
References & Further Reading
- paper A New Algorithm for Data Compression — Philip Gage (1994) C Users Journal 12 (2): 23–38. Byte-pair encoding as a general-purpose compressor
- paper Neural Machine Translation of Rare Words with Subword Units — Rico Sennrich, Barry Haddow, and Alexandra Birch (2016) ACL 2016, 1715–25. BPE adapted to open-vocabulary translation
- paper Japanese and Korean Voice Search — Mike Schuster and Kaisuke Nakajima (2012) ICASSP 2012, 5149–52. The WordPiece likelihood criterion
- paper Google's Neural Machine Translation System: Bridging the Gap between Human and Machine Translation — Yonghui Wu et al. (2016) arXiv:1609.08144. WordPiece in neural machine translation
- paper Subword Regularization: Improving Neural Network Translation Models with Multiple Subword Candidates — Taku Kudo (2018) ACL 2018, 66–75. The Unigram LM tokenizer, trained by EM
- documentation SentencePiece: A Simple and Language Independent Subword Tokenizer and Detokenizer for Neural Text Processing — Taku Kudo and John Richardson (2018) EMNLP 2018 System Demonstrations, 66–71. The library and its vocabulary-pruning loss
- paper A Formal Perspective on Byte-Pair Encoding — Vilém Zouhar, Clara Meister, Juan Luis Gastaldi, Li Du, Tim Vieira, Mrinmaya Sachan, and Ryan Cotterell (2023) Findings of ACL 2023, 598–614. A curvature-dependent approximation bound for greedy BPE
- paper Theoretical Analysis of Byte-Pair Encoding — László Kozma and Johannes Voderholzer (2026) ESA 2026, LIPIcs 388 (arXiv:2411.08671). APX-completeness and the 1/3 guarantee
- paper Tokenisation Is NP-Complete — Philip Whittington, Gregor Bachmann, and Tiago Pimentel (2025) ACL 2025, 28133–53. NP-completeness of bottom-up and direct tokenization
- paper Tokenization and the Noiseless Channel — Vilém Zouhar, Clara Meister, Juan Luis Gastaldi, Li Du, Mrinmaya Sachan, and Ryan Cotterell (2023) ACL 2023, 5184–207. Rényi efficiency as an empirical predictor of tokenizer quality
- paper Byte Pair Encoding Is Suboptimal for Language Model Pretraining — Kaj Bostrom and Greg Durrett (2020) Findings of EMNLP 2020, 4617–24. Unigram LM pieces align better with morphology
- paper Maximum Likelihood from Incomplete Data via the EM Algorithm — A. P. Dempster, N. M. Laird, and D. B. Rubin (1977) Journal of the Royal Statistical Society, Series B 39 (1): 1–38
- paper Error Bounds for Convolutional Codes and an Asymptotically Optimum Decoding Algorithm — Andrew J. Viterbi (1967) IEEE Transactions on Information Theory 13 (2): 260–69
- paper Modeling by Shortest Data Description — Jorma Rissanen (1978) Automatica 14 (5): 465–71. The two-part code
- paper Unsupervised Models for Morpheme Segmentation and Morphology Learning — Mathias Creutz and Krista Lagus (2007) ACM Transactions on Speech and Language Processing 4 (1): 3. Morfessor: MDL for morphology
- paper Practical Lossless Compression with Latent Variables Using Bits Back Coding — James Townsend, Tom Bird, and David Barber (2019) ICLR 2019. Recovering the Viterbi code's wasted bits