Tokenization Theory: BPE, WordPiece, and Unigram
What You'll Learn
- 1Explain why subword tokenization beats word level and character level schemes
- 2Trace the BPE merge loop and compute the vocabulary it produces
- 3Score WordPiece merges by likelihood and prune Unigram vocabularies by loss
- 4Measure fertility on your own corpus and pick a vocabulary size
A tokenizer fixes the alphabet every later stage learns over, and a bad choice shows up as lost context: at 1.33 tokens per word an 8,192 token window holds 6,160 words of prose, while text tokenized at 3.0 tokens per word fills that window after 2,731 words. Subword algorithms split rare words into frequent pieces while keeping frequent words whole. This lesson derives BPE, WordPiece, and Unigram with their scoring rules and the arithmetic linking vocabulary size to sequence length.
The Vocabulary Trade-off
Word level tokenization maps word to id directly, but a 100 million word corpus holds about 400,000 distinct types, so the embedding matrix explodes while rare words hit an unknown token. Character level tokenization shrinks the alphabet to a few hundred symbols yet stretches sequences five to seven times, multiplying quadratic attention cost. Fertility says where a subword scheme sits.
where is the context window in tokens and is how many whole words fit. Vocabulary size also sets the cost of the embedding layer:
with the hidden size, so each 100,000 extra tokens in a 4,096 dimensional model costs 409,600,000 parameters.
| Scheme | Rule for adding symbols | Example models | Vocab size |
|---|---|---|---|
| BPE | Merge most frequent adjacent pair | GPT-2, RoBERTa | 50,257 (GPT-2) |
| WordPiece | Merge best likelihood ratio | BERT-base, DistilBERT | 30,522 (BERT-base) |
| Unigram | Prune cheapest symbols | T5, ALBERT, XLNet | 32,128 (T5) |
| Byte level BPE | BPE over UTF-8 bytes | GPT-2, CodeLlama | 50,257 |
Byte-Pair Encoding
BPE came from data compression (Gage, 1994) and entered NMT through Sennrich, Haddow, and Birch (2016). The loop starts from an alphabet of size , which is 256 for byte level variants, and performs one merge per iteration, so after merges:
Each iteration picks the pair with the highest corpus weighted count:
Training costs for corpus symbols, since every merge rescans the word list once, and encoding is a greedy replay of that merge list.
WordPiece Merge Scoring
WordPiece (Schuster and Nakajima, 2012, used in BERT) keeps the merge loop but merges and only when the concatenation is more probable than the parts:
Unigram Language Model Pruning
Unigram (Kudo, 2018) inverts the process: it starts from roughly one million candidate symbols and drops those that hurt sentence likelihood the least. A tokenization scores as a product of unigram probabilities:
Each pruning round estimates the loss increase for dropping a symbol, removes the cheapest 20 percent, and re-estimates the survivors in per sentence. Several segmentations survive each round, so Unigram handles ambiguity that greedy BPE cannot.
Worked Examples
Worked Code
from collections import Counter
def word_symbols(word):
return list(word) + ["</w>"]
def train_bpe(freqs, num_merges):
words = []
for w, c in freqs.items():
words.extend([tuple(word_symbols(w))] * c)
merges = []
for _ in range(num_merges):
pairs = Counter()
for w in words:
for i in range(len(w) - 1):
pairs[(w[i], w[i + 1])] += 1
if not pairs:
break
best = max(pairs.items(), key=lambda kv: (kv[1], kv[0]))[0]
merged = best[0] + best[1]
rebuilt = []
for w in words:
out, i = [], 0
while i < len(w):
if i < len(w) - 1 and (w[i], w[i + 1]) == best:
out.append(merged)
i += 2
else:
out.append(w[i])
i += 1
rebuilt.append(tuple(out))
words, merges = rebuilt, merges + [best]
return merges
def encode(word, merges):
syms = word_symbols(word)
for a, b in merges:
out, i = [], 0
while i < len(syms):
if i < len(syms) - 1 and (syms[i], syms[i + 1]) == (a, b):
out.append(a + b)
i += 2
else:
out.append(syms[i])
i += 1
syms = out
return syms
merges = train_bpe({"log": 3, "dog": 2, "dig": 1}, num_merges=3)
print("merges:", merges)
print("unseen word:", encode("fog", merges))
from transformers import AutoTokenizer
gpt2 = AutoTokenizer.from_pretrained("gpt2")
bert = AutoTokenizer.from_pretrained("bert-base-uncased")
t5 = AutoTokenizer.from_pretrained("t5-small")
text = "The tokenizer you pick decides how many tokens a document costs."
ids = gpt2(text)["input_ids"]
print("gpt2 vocab:", gpt2.vocab_size, "fertility:", round(len(ids) / len(text.split()), 3))
print("bert vocab:", bert.vocab_size, bert.tokenize("unaffable"))
print("t5 vocab:", t5.vocab_size)
assert gpt2.decode(gpt2(text)["input_ids"]) == text
Real-World Applications
- GPT-2 (Radford et al., 2019) ships 50,257 byte level entries, so no unknown token exists and any byte string round trips.
- BERT-base (Devlin et al., 2019) uses WordPiece with 30,522 entries and the
##marker, giving a 23,440,896 parameter embedding table that is 21 percent of the 110M model. - T5 (Raffel et al., 2020) and Llama 2 (Touvron et al., 2023) use SentencePiece (Kudo and Richardson, 2018) with 32,128 and 32,000 entries, so Korean and Thai text needs no separate segmenter.
đĄVocabulary size is a three-way trade
Common Mistakes
Assuming one word equals one token
Fix: Measure fertility: English prose sits near 1.33 tokens per word and code near 3.0.
Swapping the tokenizer under a trained model
Fix: Token ids are rows of the embedding matrix, so a new tokenizer forces retraining.
Choosing vocabulary size by tradition
Fix: Budget it with P_embed = V x d, then check the sequence savings.
Best Practices
- Train the tokenizer on the distribution the model will see, domain jargon included
- Reserve pad, bos, eos, and task marker ids before training so ids never shift
- Track fertility in CI, since a 10 percent regression silently shrinks context
Key Takeaways
- BPE grows the vocabulary by exactly one per merge: V = V0 + m, and GPT-2 stops at 50,257 entries
- WordPiece merges only when freq(xy) over freq(x) times freq(y) is large
- Unigram prunes the symbols whose removal raises negative log likelihood the least
- Fertility sets context: 8,192 tokens is 6,160 words at f = 1.33 but 2,731 at f = 3.0
Frequently Asked Questions
Why not tokenize on spaces with a whole word dictionary?
A whole word scheme needs one embedding row per word type, and most rows are trained once or twice, so the matrix grows while staying untrained. Subword keeps near 30,000 to 131,000.
Why does byte level BPE start from 256 symbols?
UTF-8 text is a byte stream with 1 to 4 bytes per code point, and the byte alphabet has exactly 256 members, so for any language. The cost is a few tokens per non Latin character.
Does a larger vocabulary always improve a model?
No. Raising from 50,000 to 250,000 adds 200,000 x 4,096 = 819,200,000 embedding parameters, while sequences shrink only by the fertility gain the merges buy.
Interview Questions
Q1: How does BPE decide which pair to merge?
It counts adjacent pairs weighted by word frequency and merges the unique maximum, so the vocabulary grows by exactly one per iteration; GPT-2 reaches 50,257 entries from a 256 byte alphabet.
Q2: What is fertility and why do you measure it?
Fertility is tokens divided by words. At f = 1.6 an 8,192 token window holds 5,120 words, at f = 1.33 it holds 6,160, so a tokenizer regression quietly costs 1,040 words of context.