Contents Language as Data Code Course home

Chapter 5Subword Tokenisation

After this chapter you will be able to

  • run byte pair encoding by hand, with the tie break rule, and apply the learned merges to an unseen word;

  • compute the fertility of a tokeniser and say what it costs in money, memory and context;

  • work out how many parameters a vocabulary adds to the embedding matrix;

  • explain why attention cost grows faster than fertility;

  • say what a tokeniser decides before the model sees a single word.

This chapter builds on Chapter 3, whose Heaps’ law says the vocabulary never closes.

The vocabulary problem

Chapter 3 left us with an uncomfortable fact. The vocabulary of a natural language never closes. Heaps’ law guarantees it, because however much text a system has seen the next document can hold a word it has not, and for a word-level system every such word is a small crisis. The classical remedy is to map everything unknown to a single <unk> symbol, as in Chapter 10. This is honest bookkeeping and poor modelling. It declares unfathomable, Vaccination and iPhone17 to be the same word, so all identity is lost at the moment identity matters most.

The opposite extreme is available and instructive. Work at the character level and the vocabulary problem vanishes, since a few dozen symbols cover everything anyone will type. The price is that every regularity we care about is smeared across long sequences. The model has to rediscover character by character that t-h-e is a unit before it can start learning what the does. Sequences get roughly five times longer, so a dependency that spanned three words now spans fifteen symbols.

Neither words nor characters will do. The resolution sounds like a compromise and is a synthesis: let the data decide what the units are. Frequent words should survive as single tokens, because statistically they have paid for it. Rare words should break into pieces that are themselves frequent, so that unfathomable becomes something like un + fathom + able and a novel surname becomes pronounceable fragments (Figure 5.1). In the worst case, anything at all becomes single characters. A vocabulary of such subword units can be closed, modest in size, and still able to represent every string. Every large language model you have used is built on this idea.

Figure 5.1. The same word at three granularities. The word-level vocabulary has no entry for it. The character-level one spells it in twelve steps. The subword split, which is illustrative here, keeps the pieces that the data says are frequent.

Byte pair encoding

The dominant algorithm is byte pair encoding, or BPE, and it is almost embarrassingly simple. It belongs to a family of subword methods, and its siblings appear later in this chapter. It was borrowed from a 1994 data compression technique and repurposed for translation by Sennrich, Haddow and Birch in 2016. It learns a vocabulary by merging, greedily and repeatedly:

  1. Split every word in the training corpus into characters. Append an end-of-word marker </w> to each word. The starting vocabulary is the character set.

  2. Count every adjacent pair of current symbols, across the whole corpus. Each occurrence counts with its word’s frequency.

  3. Merge the most frequent pair into one new symbol. Add that symbol to the vocabulary and record the merge as a rule.

  4. Repeat from step 2, for a fixed number of merges. That number is the algorithm’s only real hyperparameter.

One bookkeeping rule matters enough to state precisely, because without it two otherwise correct implementations will disagree. When several pairs tie for the highest count, merge the lexicographically smallest pair. Ties are not rare, and in small corpora they are the norm, so the tie break decides every merge that follows. Once the rule is stated, BPE is exactly reproducible, because two implementations make the same merges.

A worked run, step by step

Take the classic micro corpus. Four words, each with a frequency:

word frequency
low 5
lower 2
newest 6
widest 3

We will run five merges. At every step we do the same three things: count all adjacent pairs, pick the winner while breaking ties lexicographically, then rewrite the corpus with that pair joined. Every count below is weighted by the word’s frequency, so a pair inside newest contributes 6 and not 1. That weighting is the most common mistake in a hand simulation.

Step 0: split into characters.

Every word becomes its characters plus the end-of-word marker.

symbols frequency
l o w </w> 5
l o w e r </w> 2
n e w e s t </w> 6
w i d e s t </w> 3
Step 1: merge e s.

Count every adjacent pair. There are fourteen distinct pairs in all, and the eight highest are these:

pair count where it comes from
e s 9 newest 6 ++ widest 3
s t 9 newest 6 ++ widest 3
t </w> 9 newest 6 ++ widest 3
w e 8 lower 2 ++ newest 6
l o 7 low 5 ++ lower 2
o w 7 low 5 ++ lower 2
e w 6 newest 6
n e 6 newest 6

Six more pairs exist, and none of them scores above 5. Note that w </w> is one of those six, at 5, coming from low alone. Three pairs tie at 9, so the tie break matters at the very first step. Sorted as tuples, (𝚎,𝚜)<(𝚜,𝚝)<(𝚝,</𝚠>)\texttt{(e,s)} < \texttt{(s,t)} < \texttt{(t,</w>)}, so e s wins.

corpus after merge 1 frequency
l o w </w> 5
l o w e r </w> 2
n e w es t </w> 6
w i d es t </w> 3
Step 2: merge es t.

Recount, because the merge changed which pairs exist. The pairs e s and s t are both gone and es t has taken their place. Now only two pairs tie at 9, namely es t and t </w>, and since (𝚎𝚜,𝚝)<(𝚝,</𝚠>)\texttt{(es,t)} < \texttt{(t,</w>)} the winner is es t.

corpus after merge 2 frequency
l o w </w> 5
l o w e r </w> 2
n e w est </w> 6
w i d est </w> 3
Step 3: merge est </w>.

Recount again. This time there is no tie, because est </w> stands alone at 9 while the next best, l o and o w, are back at 7.

corpus after merge 3 frequency
l o w </w> 5
l o w e r </w> 2
n e w est</w> 6
w i d est</w> 3

This is the interesting moment. The suffix est</w> completed in three merges, before the algorithm had touched the stem of low at all. Nothing told it that -est is an English suffix, and it won because it was frequent.

Step 4: merge l o.

With the 9s exhausted the top count drops to 7, and we get a second tie, since both l o and o w score 5+2=75+2=7. Sorted, (𝚕,𝚘)<(𝚘,𝚠)\texttt{(l,o)} < \texttt{(o,w)}, so l o wins.

corpus after merge 4 frequency
lo w </w> 5
lo w e r </w> 2
n e w est</w> 6
w i d est</w> 3
Step 5: merge lo w.

The previous merge has just made lo w available, and it inherits the same count of 7, with no tie this time.

corpus after merge 5 frequency
low </w> 5
low e r </w> 2
n e w est</w> 6
w i d est</w> 3

Five merges, in order, and this ordered list is the tokeniser.

# merged pair new symbol count tie?
1 e s es 9 3 way
2 es t est 9 2 way
3 est </w> est</w> 9 no
4 l o lo 7 2 way
5 lo w low 7 no

Three of the five steps involved a tie, so the tie break rule is not a footnote. Without it three of these five merges are undefined, and every merge after the first bad one is wrong as well. The words now tokenise like this:

word tokens after 5 merges
low low </w>
lower low e r </w>
newest n e w est</w>
widest w i d est</w>

The algorithm found a productive English suffix in est</w> and a whole common word in low. The rarer lower still decomposes into a known stem plus leftovers. Nobody supplied a single linguistic fact, and -est paid for itself in compression. This is the idea of BPE in one sentence.

Using the tokeniser

Applying a trained tokeniser to new text replays the same logic. Split the word into characters, then apply the recorded merge rules in the order they were learned, wherever they match. Try lowest, a word the training corpus never contained, and apply the five rules in order to watch it assemble (Figure 5.2).

apply result
split l o w e s t </w>
rule 1, e s l o w es t </w> matched
rule 2, es t l o w est </w> matched
rule 3, est </w> l o w est</w> matched
rule 4, l o lo w est</w> matched
rule 5, lo w low est</w> matched
Figure 5.2. How lowest is assembled. The four symbols e, s, t and </w> are joined by rules 1 to 3, and l, o, w by rules 4 and 5. An unseen word comes out as a known stem and a known suffix.

An unseen word came out as two meaningful pieces, a stem low and a suffix est</w>, and that is the point of subwords. The rules must be applied in the order they were learned, because rule 2 can only fire once rule 1 has already produced es. Apply them in a different order and you get a different and wrong answer.

Run it. The script behind every table in this run is code/worked_examples/bpe.py. Running it with --no-tiebreak takes the lexicographically last tied pair instead of the first. All five merges come out different, yet on this corpus the final tokenisations come out the same, because the tied merges only change the order in which the pieces of est are built, so the corpus alone does not show the damage. A smaller corpus does, and Problem 5.4 asks you to build one.

Run it

Five byte pair encoding merges applied to the words low, lower, newest and widest
Byte pair encoding builds a vocabulary by repetition. The commonest adjacent pair of symbols becomes a new symbol, and five rounds turn single letters into word pieces.

Fertility: measuring a tokeniser

How do we judge a tokeniser? The workhorse diagnostic is fertility, the average number of tokens produced per word:

fertility=#tokens#words.(5.1)\begin{equation} \text{fertility} \;=\; \frac{\#\text{tokens}}{\#\text{words}}. \label{eq:fertility} \quad\text{(5.1)} \end{equation}

A fertility of 1.01.0 means every word survived whole, and a fertility of 2.02.0 means words are being cut in half on average. Character-level tokenisation of English runs near 55. Fertility is a compression gauge, and like all compression it reflects the fit between training data and use. A BPE vocabulary learned on news text has low fertility on news. On medical abstracts, legal boilerplate or another language its fertility climbs, because the merges it learned are the wrong merges for that text. Rising fertility is therefore often the first measurable symptom of domain shift, and it is cheaper to compute than any accuracy number.

Fertility is also, bluntly, money. Modern language model APIs price by the token and context windows are budgeted in tokens. Text that tokenises at fertility 1.81.8 costs 50%50\% more than the same content at 1.21.2, and fits 33%33\% less into the window. Multilingual users often notice that their language costs more per sentence than English on the same model. What they are measuring is the fertility of a tokeniser whose training data under-represented their language. Tokenisation looks like invisible plumbing, and it has an equity dimension.

Three practical notes round out the picture.

First, modern systems usually run BPE over bytes and not Unicode characters. This is byte-level BPE, as used in GPT-2 and its descendants, the language models that Chapter 19 describes. All 256 bytes sit in the base vocabulary, so no string in any script can be out of vocabulary and <unk> disappears from the system.

Second, BPE has siblings. WordPiece uses likelihood-driven merges and is the tokeniser behind BERT. The unigram language model tokeniser prunes a large vocabulary instead of growing a small one, and it reaches you through SentencePiece. They differ in the selection criterion and share the subword philosophy.

Third, tokenisation is where some of a model’s oddest behaviour is born. A model may be unable to reverse a word, count its letters, or do digit arithmetic, and the cause is often the tokeniser having welded those characters into opaque units before the model saw them. When a language model’s behaviour on a string puzzles you, inspect the string as the model sees it, in tokens.

What the tokeniser decides about the model

Fertility is a property of text, whereas the merge count is a property of the model, and it is a larger one than it looks. The number of merges is not a tuning knob that can be turned freely, because it sets the size of the largest single matrix the model carries.

The merge count is the vocabulary

Run BPE over bytes and the base vocabulary is all 256 byte values. After that every merge adds one new symbol. GPT-2 makes the arithmetic visible.

256 base byte values 256
merges learned 50,000
one end of text special token 1
GPT-2 vocabulary size 50,257

This is the published figure, and it is the merge loop of Section 5.2.1 run fifty thousand times on web text.

Every merge is a row in the embedding matrix

A model stores one vector per vocabulary item, so the embedding matrix is V×dV \times d where dd is the model width. GPT-2 small is 768 wide, so a single merge costs 768 parameters.

embedding matrix, V×dV \times d 50,257×768=38,597,37650{,}257 \times 768 = 38{,}597{,}376
share of GPT-2 small’s 124M parameters 31.1 percent
cost of one more merge 768 parameters
cost of ten thousand more merges 7,680,000 parameters

Almost a third of that model is the tokeniser’s vocabulary, and where the output layer keeps its own matrix instead of reusing the embedding matrix, it costs the same again. There is a genuine trade-off here, with two sides. More merges give longer subwords and lower fertility, so sequences get shorter. More merges also give a larger embedding matrix and a wider softmax (Appendix A recalls the softmax). Parameters are being traded against sequence length, and the best point depends on the text the model will meet, which is the argument fertility makes.

Fertility becomes compute, and not linearly

Self-attention (Chapter 17) compares every token with every other token, so its cost grows with the square of the sequence length. A tokeniser that is somewhat worse per word is therefore considerably worse per document. Take a document of 1000 words. The last column is the KV cache, explained below, in 16-bit numbers of two bytes each.

tokens attention pairs n2n^2 KV cache (fp16)
fertility 1.2 1200 1,440,000 42.2 MB
fertility 1.9 1900 3,610,000 66.8 MB
ratio 1.58 2.51 1.58
Figure 5.3. Attention pairs for a 1000-word document at two fertilities. Fertility rises by a factor of 1.581.58 and the bar rises by 2.512.51, because cost follows the square of the length.

A tokeniser 58 per cent worse per word costs 151 per cent more attention work. That gap is the strongest practical argument for measuring fertility at all.

Memory during generation

A model generating text keeps a key and a value vector per token per layer. That store is the KV cache, and it usually limits how many requests one server can hold at once.

per token, GPT-2 small at fp16 2×12×768×2=36,8642 \times 12 \times 768 \times 2 = 36{,}864 bytes
36 KB per token
a full 1024 token window 36.0 MB

Every token the tokeniser fails to merge costs another 36 KB of cache. This is for one request on one small model, and the figure is far higher on a large one. The context window is measured in tokens and never in words, so fertility also decides how much of a document fits inside it.

fertility words that fit in a 1024 token window
1.2 853
1.9 539

Two readers send the same document to the same model. One is truncated and the other is not, and the only difference is how well the tokeniser fits their language. Section 5.3 called that an equity dimension, and these are the numbers underneath it.

Where this leaves us

Subword tokenisation closes the vocabulary problem that Chapter 3 opened. We get a fixed and modest vocabulary that can still spell anything, with frequent units kept whole so that downstream statistics have something solid to bind to. From here on every model in this book operates on tokens, whether the n-gram models of Chapter 10, the embeddings of Part II or the transformers of Part IV. Every perplexity, similarity and attention weight we compute is a statement about token sequences. Remember that when you compare numbers across systems, because two models with different tokenisers are answering subtly different questions about the same text.

Summary

A word-level vocabulary never closes, and a character-level one makes sequences too long. Byte pair encoding starts from characters and repeatedly merges the most frequent adjacent pair, breaking ties by taking the lexicographically smallest, and the ordered merge list is the tokeniser. On the micro corpus the suffix est is found in three merges with no linguistic knowledge, and the unseen word lowest splits into a stem and a suffix. Fertility, the tokens per word, measures the fit between a tokeniser and a text, and it sets cost, context use and KV cache size. The merge count sets the vocabulary and hence the embedding matrix, which holds almost a third of GPT-2 small. Attention cost grows with the square of the sequence length, so a modest rise in fertility is a large rise in compute.

Key terms

subword. a unit between a character and a word, chosen so that frequent words stay whole and rare ones split.

byte pair encoding. a tokeniser learned by repeatedly merging the most frequent adjacent pair of symbols.

merge rule. one recorded pair merge, applied in the order it was learned.

fertility. the average number of tokens produced per word.

byte-level BPE. BPE whose base vocabulary is the 256 byte values, so no string is out of vocabulary.

KV cache. the stored key and value vectors of every token generated so far, kept per layer.

Further reading.

Sennrich et al. (2016) is the paper that made BPE standard for neural machine translation. Kudo and Richardson (2018) present SentencePiece and the unigram alternative. Jurafsky and Martin (2025) situate tokenisation in the broader text normalisation pipeline, in Chapter 2 of the third edition draft. The trainer you are asked to write in Problem 7 exists as tokenizers, the library behind most current models, and sentencepiece is the reference implementation of the unigram alternative.

Practice problems

5.1 BPE by hand. Take a small corpus of a dozen words. Run five byte pair encoding merges by hand, writing out the merge rules in order. Apply the deterministic tie break rule of this chapter at every step. This is where hand simulations go wrong, so whenever two pairs are equally frequent, state which pair you merged and why.

5.2 Apply the rules. Use the five merge rules learned in Section 5.2.1. Tokenise lowers and nest, which the training corpus never contained. Write each intermediate string, say which rule fired at each step, and say what you would conclude about a word, such as wider, to which no rule applies.

5.3 The vocabulary budget. You are given a model width of 768 and a budget of 40 million parameters for the embedding matrix alone. How many merges can you afford, once the 256 byte values and one special token are accounted for? Now halve the width and repeat. Say in one sentence what the width is buying.

5.4 Tie break sensitivity. Re-run Problem 1 with a different tie break rule, for example preferring the lexicographically later pair, and show that the merge list changes. On the corpus of this chapter the tokenisations stay the same, so then find a corpus of two short words, over the letters aa and bb, on which two merges give a different tokenisation of at least one word under the two rules. What does this tell you about reproducibility claims that omit the tie break convention?

5.5 Fertility in money. A document of 20002000 words tokenises into 26002600 tokens with one tokeniser and 34003400 with another. Compute both fertilities. An API charges per token. By what percentage does the second cost more? Then compute how many words of this document fit into a 40964096 token window under each.

Build and measure

5.6 Where the curve flattens. Train BPE on a corpus at several merge counts, from zero upwards, and measure fertility on held-out text each time. Plot it. The curve falls steeply and then flattens, and doubling the merge count eventually buys very little. Say where you would stop, and defend the choice using both sides of the trade-off in Section 5.4.

5.7 Implement the trainer and encoder. Write train(corpus, num_merges), which returns an ordered list of merge rules. Write encode(word), which applies them. Run your encoder on the corpus of Problem 1 and check that it reproduces the merges you did by hand. A mismatch almost always means the tie break rule differs.

5.8 Measure fertility. Use your trained tokeniser to compute fertility, as defined in Equation (5.1), on two samples. One in domain, one out of domain, say a technical or foreign language passage. Report both numbers. Explain in one paragraph why the out of domain number is higher.

5.9 Predict the sixth merge. For the micro corpus of Section 5.2.1, write down the sixth merge before you run anything, together with the pairs you think tie for it. Then extend your trainer to six merges and compare. If your prediction was wrong, say which count you got wrong.

5.10 Where a real trainer differs. Train tokenizers.models.BPE on the low, lower, newest, widest corpus of this chapter, passing end_of_word_suffix="</w>", and list the merges it produces in order. Its first merge is e s, as yours is, and its second is not. Work out what the library does with the end-of-word marker that this chapter does not, and then answer the harder question: is either merge list wrong, and what would you have to know before you could say?

In practice

5.11 A language that costs more. Users of one language report that the same sentence costs twice as many tokens as in English on the same model. State the number you would compute to confirm it, say what in the training of the tokeniser caused it, and name two things you could change, one in the tokeniser and one outside it.

5.12 The model that cannot count letters. A model answers incorrectly when asked how many times the letter r occurs in a long word. Explain how tokenisation could cause this, describe a test that would show whether it does, and say what the test result would have to look like for you to blame something else.

5.13 A new domain. A team trained its tokeniser on news and now applies it to clinical notes. Fertility rises from 1.31.3 to 2.12.1. Estimate the change in attention cost for a note of fixed word length, say what else changes, and decide whether you would retrain the tokeniser, the model, or both, and why.

Code for this chapter

Each one reproduces the tables above. Run it in the page, change an input and watch which numbers move.

  • bpe.pyBPE, five merges

    The whole training run with pair counts and ties, then the learned rules applied to words the corpus never held.

    runs in your browser Run it

From Natural Language Processing: From Corpus Statistics to Grounded LLMs, by Ramaseshan Ramachandran.