intermediate text-as-data 40 min read

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 — 63,18263{,}182 tokens, 3,4253{,}425 word types — and read 100100 fresh documents from the same generator. They contain 7979 word types the vocabulary has never seen: colevys, nonroyaltys, supplierers, crosspremium. That is only 0.73%0.73\% of the 21,00621{,}006 held-out tokens, but every one of them is a word the model cannot represent, and over half the training vocabulary (54.8%54.8\%) 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:

  1. 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 nn letters has up to 2n−12^{n-1} spellings, so choosing one is a search problem.
  2. 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.
  3. 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.

A · Run the merges — 374 merges on the 26 letters
merges
374
tokens per held-out word (BPE)
2.257
(WordPiece at the same |V|)
2.560

B · Read the lattice — the Unigram LM at |V| = 400
Viterbi segmentation
non · royalty · s
−log₂ P(x), marginal
21.65 bits
−log₂ P(t*), Viterbi
21.66 bits
log₂ |Seg(x)|
4.32
Boundary F1 against the planted morphemes at |V| = 400: BPE 0.512, WordPiece 0.528, Unigram LM 0.780.

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 Σ\Sigma — here the 2626 lowercase letters — and let Σ+\Sigma^+ 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 V⊂Σ+V \subset \Sigma^+ of pieces. A segmentation of a string xx is a tuple (t1,…,tk)∈Vk(t_1, \dots, t_k) \in V^k whose concatenation t1t2⋯tkt_1 t_2 \cdots t_k equals xx. We write SegV(x)\mathrm{Seg}_V(x) for the set of segmentations of xx. Encoding chooses one segmentation; decoding concatenates its pieces.

Proposition 1 (Completeness).

Every string x∈Σ+x \in \Sigma^+ has at least one segmentation if and only if Σ⊆V\Sigma \subseteq V. In that case decoding inverts every encoding.

Proof.

If Σ⊆V\Sigma \subseteq V, the letters of xx themselves form a segmentation. Conversely, if some letter c∈Σc \in \Sigma is missing from VV, every piece of a segmentation of the one-letter string cc would have to be a nonempty substring of cc, which is cc itself — so there is none. Decoding concatenates the pieces, and by definition they concatenate to xx.

∎

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 7979 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 xx is a piece and ∣x∣=n|x| = n, then ∣Seg(x)∣=2n−1|\mathrm{Seg}(x)| = 2^{n-1}. If pieces are limited to length at most LL, then ∣Seg(x)∣=SL(n)|\mathrm{Seg}(x)| = S_L(n), where SL(0)=1S_L(0) = 1 and SL(m)=∑k=1min⁡(L,m)SL(m−k)S_L(m) = \sum_{k=1}^{\min(L, m)} S_L(m - k) — the LL-step Fibonacci numbers.

Proof.

A segmentation is determined by which of the n−1n - 1 gaps between adjacent letters are piece boundaries, and when every substring is a piece, every subset of gaps occurs: 2n−12^{n-1} choices. With pieces of length at most LL, sort the segmentations of the first mm letters by the length k≤min⁡(L,m)k \le \min(L, m) of their last piece; removing that piece leaves a segmentation of the first m−km - k letters, and every such pair arises once.

∎

A sixteen-letter word has 32,76832{,}768 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 (a,b)(a, b) in a token sequence, scan left to right and replace each adjacent occurrence of aa followed by bb with the single token abab, resuming the scan after the new token, so that no two replacements overlap. Let rr be the number of replacements. A merge sequence μ=((a1,b1),…,(aM,bM))\mu = ((a_1, b_1), \dots, (a_M, b_M)) defines vocabularies V0=ΣV_0 = \Sigma and Vj=Vj−1∪{ajbj}V_j = V_{j-1} \cup \{a_j b_j\}. Rank replay encodes a word by starting from its letters and applying merges 1,2,…,M1, 2, \dots, M 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 (ti,ti+1)=(a,b)(t_i, t_{i+1}) = (a, b), 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 10,84310{,}843 down to 4,1024{,}102: English inflection and function words surface first. Each merge buys exactly what it replaces — with one subtlety.

Proposition 3 (Merge accounting).

Merging (a,b)(a, b) shortens a token sequence by exactly rr, the number of replacements. If a≠ba \neq b, then rr equals the window count of (a,b)(a, b). If a=ba = b, a maximal run of ℓ\ell consecutive copies of aa contains ℓ−1\ell - 1 windows but yields only ⌊ℓ/2⌋\lfloor \ell / 2 \rfloor replacements.

Proof.

Each replacement consumes two tokens and emits one, and every other token is copied, so the length falls by rr. If a≠ba \ne b, two occurrences cannot overlap: windows at positions ii and i+1i + 1 would require ti+1=bt_{i+1} = b and ti+1=at_{i+1} = a 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 rr equals the window count. If a=ba = b, the scan pairs a run’s tokens as (1,2),(3,4),…(1, 2), (3, 4), \dots, giving ⌊ℓ/2⌋\lfloor \ell/2 \rfloor 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 (a,a)(a, a), 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 1,…,k1, \dots, k on a training word yields exactly that word’s segmentation after kk training merges. Moreover, the first kk merges of a greedy run of any length M≥kM \ge k are the kk-merge model.

Proof.

Training applies merge jj to every word’s current sequence with the same deterministic map that replay applies, starting from the same letters; induct on jj. For the second claim, greedy’s choice at step jj depends only on the state after j−1j - 1 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 174174-merge model is the first 174174 merges of the 774774-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 4,0004{,}000 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 1/31/3 of the optimal utility, and there are inputs on which it achieves at most 0.6250.625 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 1σ(1−e−σ)\frac{1}{\sigma}\bigl(1 - e^{-\sigma}\bigr) of the optimal utility, where σ\sigma 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, aaaabaaab\texttt{aaaabaaab} and aaabaaaab\texttt{aaabaaaab}; here is the first:

Example 1 (aaaabaaab with three merges).

In aaaabaaab\texttt{aaaabaaab} the pair (a,a)(a, a) makes three replacements (two in the first run, one in the second), more than any other pair, so greedy must merge it first: aa  aa  b  aa  a  b\texttt{aa}\;\texttt{aa}\;\texttt{b}\;\texttt{aa}\;\texttt{a}\;\texttt{b}. Every pair left now occurs once, and two more merges save two more tokens: utility 55 in every greedy run. The optimum instead merges (a,b)(a, b), then (a,ab)(a, ab), then (a,aab)(a, aab), building the repeated unit aaab\texttt{aaab} and ending at a  aaab  aaab\texttt{a}\;\texttt{aaab}\;\texttt{aaab} — utility 66. Greedy’s forced first move breaks both copies of the structure the optimum exploits.

On 300300 random short strings every greedy run stays above the guaranteed 1/31/3 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 ctc_t for the count of token tt in the training data and N=∑tctN = \sum_t c_t. The maximum-likelihood unigram model is p^(t)=ct/N\hat p(t) = c_t / N, and its log-likelihood is

L  =  ∑tctlog⁡ctN  =  ∑tctlog⁡ct  −  Nlog⁡N.\mathcal{L} \;=\; \sum_t c_t \log \frac{c_t}{N} \;=\; \sum_t c_t \log c_t \;-\; N \log N .

Proposition 5 (The likelihood gain of a merge).

If merging (a,b)(a, b) with a≠ba \ne b makes mm replacements, then the exact change in L\mathcal{L} is

ΔL=mlog⁡m+∑c∈{ca, cb}[(c−m)log⁡(c−m)−clog⁡c]−[(N−m)log⁡(N−m)−Nlog⁡N],\Delta\mathcal{L} = m\log m + \sum_{c \in \{c_a,\, c_b\}} \bigl[(c - m)\log(c - m) - c\log c\bigr] - \bigl[(N - m)\log(N - m) - N\log N\bigr],

and it decomposes as

ΔL  =  m[log⁡mNca cb−1]+Rca+Rcb−RN,0  ≤  Rc  ≤  m22(c−m).\Delta\mathcal{L} \;=\; m\Bigl[\log\frac{mN}{c_a\, c_b} - 1\Bigr] + R_{c_a} + R_{c_b} - R_N, \qquad 0 \;\le\; R_c \;\le\; \frac{m^2}{2(c - m)} .
Proof.

A merge changes only four quantities: cac_a and cbc_b each fall by mm, the new token abab goes from count 00 to mm, and NN falls to N−mN - m. Substituting into L\mathcal{L} gives the first display. For the second, fix c>mc > m, put x=m/cx = m/c, and let g(x)=(1−x)log⁡(1−x)+xg(x) = (1 - x)\log(1 - x) + x. Expanding log⁡(c−m)=log⁡c+log⁡(1−x)\log(c - m) = \log c + \log(1 - x) gives

(c−m)log⁡(c−m)−clog⁡c  =  −mlog⁡c−m+c g(m/c).(c - m)\log(c - m) - c\log c \;=\; -m\log c - m + c\,g(m/c).

Now g(0)=0g(0) = 0, g′(x)=−log⁡(1−x)≥0g'(x) = -\log(1 - x) \ge 0, and g′′(x)=1/(1−x)g''(x) = 1/(1 - x), so 0≤g(x)=∫0x ⁣∫0ydz1−z dy≤x22(1−x)0 \le g(x) = \int_0^x \!\int_0^y \frac{dz}{1 - z}\,dy \le \frac{x^2}{2(1 - x)}. Setting Rc=c g(m/c)R_c = c\,g(m/c) gives 0≤Rc≤m22(c−m)0 \le R_c \le \frac{m^2}{2(c - m)}. Applying the identity to cac_a, cbc_b, and NN and collecting terms, the leading part is mlog⁡m−mlog⁡ca−mlog⁡cb+mlog⁡N−mm\log m - m\log c_a - m\log c_b + m\log N - m, as claimed.

∎

The leading term reads m [PMI(a,b)−1]m\,\bigl[\mathrm{PMI}(a, b) - 1\bigr], where PMI(a,b)=log⁡cabNcacb\mathrm{PMI}(a, b) = \log \frac{c_{ab} N}{c_a c_b} is the pointwise mutual information of the pair and cab=mc_{ab} = m. BPE ranks by mm alone; WordPiece weights mm by how much more often aa and bb 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 (e,r)(e, r), with count 7,6637{,}663; WordPiece takes (an,d)(an, d), with a gain of 7,355.47{,}355.4 nats, because an is followed by d far more often than chance. The harness checks the exact formula against a recount for the first 4040 WordPiece merges and the remainder bound on 2,0002{,}000 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 200200-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 pp on a vocabulary VV. A segmentation has probability P(t1,…,tk)=∏i=1kp(ti)P(t_1, \dots, t_k) = \prod_{i=1}^{k} p(t_i), and a string has marginal probability P(x)=∑t∈SegV(x)P(t)P(x) = \sum_{\mathbf{t} \in \mathrm{Seg}_V(x)} P(\mathbf{t}). Encoding uses the Viterbi segmentation t∗=arg⁡max⁡t∈SegV(x)P(t)\mathbf{t}^\ast = \arg\max_{\mathbf{t} \in \mathrm{Seg}_V(x)} P(\mathbf{t}).

Picture the segmentations of a word as paths. Put a node at each of the n+1n + 1 gaps of an nn-letter word, from before the first letter to after the last, and draw an arc from gap ii to gap jj whenever xi:jx_{i:j} — letters i+1i + 1 through jj — 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 log⁡p(xi:j)\log p(x_{i:j}). 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 LL, set δ(0)=0\delta(0) = 0, and for j=1,…,nj = 1, \dots, n let

δ(j)  =  max⁡j−L≤i<jxi:j∈V[δ(i)+log⁡p(xi:j)],\delta(j) \;=\; \max_{\substack{j - L \le i \lt j \\ x_{i:j} \in V}} \Bigl[\delta(i) + \log p(x_{i:j})\Bigr],

with δ(j)=−∞\delta(j) = -\infty when no ii qualifies. Then δ(n)=max⁡t∈SegV(x)log⁡P(t)\delta(n) = \max_{\mathbf{t} \in \mathrm{Seg}_V(x)} \log P(\mathbf{t}), and it is −∞-\infty exactly when xx has no segmentation. The recursion uses O(nL)O(nL) vocabulary lookups, and recording the maximizing ii at each jj recovers t∗\mathbf{t}^\ast.

Proof.

We show by induction on jj that δ(j)\delta(j) is the largest log-probability of a segmentation of the prefix x0:jx_{0:j}. For j=0j = 0 the empty segmentation has log-probability 00. Every segmentation of x0:jx_{0:j} consists of a segmentation of some prefix x0:ix_{0:i} followed by one last piece xi:jx_{i:j}, and its log-probability is the sum of the two parts. Maximizing over the last piece and then over the segmentations of x0:ix_{0:i} gives max⁡i[δ(i)+log⁡p(xi:j)]\max_i \bigl[\delta(i) + \log p(x_{i:j})\bigr] by the induction hypothesis. If no last piece is in VV, there is no segmentation and the maximum over an empty set is −∞-\infty.

∎

Replacing the maximum by a sum gives the total probability of all paths.

Proposition 6 (Forward–backward and the lattice posteriors).

Let α(0)=0\alpha(0) = 0, α(j)=log⁡∑iexp⁡[α(i)+log⁡p(xi:j)]\alpha(j) = \log \sum_i \exp\bigl[\alpha(i) + \log p(x_{i:j})\bigr], and symmetrically β(n)=0\beta(n) = 0, β(i)=log⁡∑jexp⁡[log⁡p(xi:j)+β(j)]\beta(i) = \log \sum_j \exp\bigl[\log p(x_{i:j}) + \beta(j)\bigr]. Then α(n)=β(0)=log⁡P(x)\alpha(n) = \beta(0) = \log P(x). The posterior probability that the segmentation uses the piece from gap ii to gap jj is

qij  =  exp⁡[α(i)+log⁡p(xi:j)+β(j)−log⁡P(x)],q_{ij} \;=\; \exp\bigl[\alpha(i) + \log p(x_{i:j}) + \beta(j) - \log P(x)\bigr],

and for every letter position kk, the posteriors of the arcs covering it sum to one: ∑i≤k<jqij=1\sum_{i \le k \lt j} q_{ij} = 1.

Proof.

The induction of Theorem 2 with sums in place of maxima, using the distributive law, gives eα(j)e^{\alpha(j)} as the total probability of all segmentations of x0:jx_{0:j}; the same holds for β\beta from the right. The segmentations that use the arc (i,j)(i, j) are exactly a segmentation of x0:ix_{0:i}, then xi:jx_{i:j}, then a segmentation of xj:nx_{j:n}, so their total probability is eα(i) p(xi:j) eβ(j)e^{\alpha(i)}\,p(x_{i:j})\,e^{\beta(j)}; dividing by P(x)P(x) gives qijq_{ij}. Each segmentation has exactly one piece covering position kk, so summing qijq_{ij} over the covering arcs sums P(t)/P(x)P(\mathbf{t})/P(x) over every segmentation, which is 11.

∎

The arc widths in panel B are these posteriors. Try underwriting at ∣V∣=400|V| = 400: 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 pp, compute the expected number of times each piece is used under the posterior of Proposition 6, renormalize those expected counts into a new pp, and repeat.

Theorem 3 (EM never lowers the likelihood).

Fix VV and a Unigram LM pp. For training words xx with counts cxc_x, let q(t∣x)q(\mathbf{t} \mid x) be the posterior over SegV(x)\mathrm{Seg}_V(x) under pp, and let

cˉu=∑xcx Eq[number of times u appears in t]\bar c_u = \sum_x c_x\, \mathbb{E}_{q}\bigl[\text{number of times } u \text{ appears in } \mathbf{t}\bigr]

be the expected count of piece uu. Then the update p′(u)=cˉu/∑vcˉvp'(u) = \bar c_u / \sum_v \bar c_v satisfies ℓ(p′)≥ℓ(p)\ell(p') \ge \ell(p), where ℓ(p)=∑xcxlog⁡Pp(x)\ell(p) = \sum_x c_x \log P_p(x).

Proof.

For any model p′p', Jensen’s inequality applied to the concave logarithm gives

log⁡Pp′(x)  =  log⁡∑tq(t∣x) Pp′(t)q(t∣x)  ≥  ∑tq(t∣x)log⁡Pp′(t)  −  ∑tq(t∣x)log⁡q(t∣x),\log P_{p'}(x) \;=\; \log \sum_{\mathbf{t}} q(\mathbf{t} \mid x)\,\frac{P_{p'}(\mathbf{t})}{q(\mathbf{t} \mid x)} \;\ge\; \sum_{\mathbf{t}} q(\mathbf{t} \mid x) \log P_{p'}(\mathbf{t}) \;-\; \sum_{\mathbf{t}} q(\mathbf{t} \mid x)\log q(\mathbf{t} \mid x),

with equality when p′=pp' = p, because then the ratio inside is the constant Pp(x)P_p(x). Weight by cxc_x, sum over words, and subtract the equality case: ℓ(p′)−ℓ(p)≥Q(p′)−Q(p)\ell(p') - \ell(p) \ge Q(p') - Q(p), where Q(p′)=∑xcx∑tq(t∣x)log⁡Pp′(t)=∑ucˉulog⁡p′(u)Q(p') = \sum_x c_x \sum_{\mathbf{t}} q(\mathbf{t}|x)\log P_{p'}(\mathbf{t}) = \sum_u \bar c_u \log p'(u). Write πu=cˉu/∑vcˉv\pi_u = \bar c_u / \sum_v \bar c_v. Then Q(p′)=(∑vcˉv)[−H(π)−KL(π ∥ p′)]Q(p') = \bigl(\sum_v \bar c_v\bigr)\bigl[-H(\pi) - \mathrm{KL}(\pi \,\|\, p')\bigr], which Gibbs’ inequality, KL≥0\mathrm{KL} \ge 0 (see KL Divergence), maximizes exactly at p′=πp' = \pi. Hence ℓ(p′)−ℓ(p)≥Q(π)−Q(p)≥0\ell(p') - \ell(p) \ge Q(\pi) - Q(p) \ge 0.

∎

EM climbs; it does not promise the top. The vocabulary itself is chosen by a heuristic. Starting from the 2626 letters and the 2,0002{,}000 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 ∣V∣∈{800,400,200,100,50}|V| \in \{800, 400, 200, 100, 50\}. 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 −log⁡2p(t)-\log_2 p(t) bits on piece tt is the Shannon code for the distribution pp (see Shannon Entropy & Mutual Information), so a segmentation t\mathbf{t} costs −log⁡2P(t)-\log_2 P(\mathbf{t}) bits, and the Viterbi segmentation is the cheapest single spelling. A cleverer coder could charge for the word as a whole, −log⁡2P(x)-\log_2 P(x) bits, summed over all spellings. The two are never far apart.

Proposition 7 (The segmentation sandwich).

For every string xx with at least one segmentation,

−log⁡P(x)  ≤  −log⁡P(t∗)  ≤  −log⁡P(x)+log⁡∣SegV(x)∣.-\log P(x) \;\le\; -\log P(\mathbf{t}^\ast) \;\le\; -\log P(x) + \log\bigl|\mathrm{Seg}_V(x)\bigr| .
Proof.

The gap −log⁡P(t∗)+log⁡P(x)-\log P(\mathbf{t}^\ast) + \log P(x) equals −log⁡q(t∗∣x)-\log q(\mathbf{t}^\ast \mid x), the posterior surprisal of the Viterbi segmentation, which is nonnegative. Since t∗\mathbf{t}^\ast has the largest posterior among ∣SegV(x)∣|\mathrm{Seg}_V(x)| possibilities, q(t∗∣x)≥1/∣SegV(x)∣q(\mathbf{t}^\ast \mid x) \ge 1/|\mathrm{Seg}_V(x)|, which bounds the gap by log⁡∣SegV(x)∣\log|\mathrm{Seg}_V(x)|.

∎

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 ∣V∣=400|V| = 400, nonroyaltys costs 21.6621.66 bits under its Viterbi spelling non · royalty · s and 21.6521.65 bits marginally, although log⁡2∣Seg∣=4.32\log_2|\mathrm{Seg}| = 4.32 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 ∣V∣|V|. 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:

L(V)+L(D∣V),L(V)=∑t∈V(∣t∣+1)log⁡227,L(D∣V)=−Lln⁡2,L(V) + L(D \mid V), \qquad L(V) = \sum_{t \in V} \bigl(|t| + 1\bigr)\log_2 27, \qquad L(D \mid V) = -\frac{\mathcal{L}}{\ln 2},

where L(V)L(V) spells each piece letter by letter with an end marker, and L(D∣V)L(D \mid V) codes the training tokens under their own maximum-likelihood unigram model. Along BPE’s merge path on the finance corpus:

vocabularytwo-part code length
letters only1,648,2961{,}648{,}296 bits
BPE after 1,8441{,}844 merges (1,8701{,}870 pieces)636,622636{,}622 bits — the minimum
whole words (3,4253{,}425 types)712,162712{,}162 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 ∣V∣|V|.

The open vocabulary of the previous topic is now closed in the useful sense. Of the training corpus’s word types, 54.8%54.8\% occur once; of the 353353 pieces BPE uses at ∣V∣=400|V| = 400, 0.57%0.57\% 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 2424 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 with sentencepiece (identical Viterbi spellings).
  • The greedy counterexample by exhaustive search, and the 1/31/3 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