The first cut shapes every model after it
A transformer never reads characters or words. It reads integers drawn from a fixed table, and the tokenizer is the program that maps a string onto that table. Everything downstream inherits the decision: how much of a context window a sentence consumes, how many embedding parameters the model carries, and how badly a rare surname degrades once it cannot be found in the vocabulary. Swap the tokenizer underneath a trained model and you have silently permuted the rows of the embedding matrix, so accuracy does not slip a little — it falls to chance.
Three properties decide whether a scheme is usable. Coverage asks whether every input string can be encoded at all, with no unknown symbol. Fertility asks how many tokens one average word costs, because a 8,192 token window holds 6,160 English words at 1.33 tokens per word but only 2,731 words at 3.0. Stability asks whether the same string always maps to the same ids, including after you retrain or expand the vocabulary.
This lesson walks through the three families — word-level, subword, and byte-level — implements a merge-loop BPE trainer you can run yourself, and finishes with the arithmetic that links vocabulary size to sequence length.
Whitespace splitting looks fine until it does not
The cheapest tokenizer is text.split(), and for a prototype on clean English it genuinely works. It fails on the first contraction, the first hyphenated compound, and the first sentence that ends a line without a space before the period. Punctuation-aware regular expressions fix the obvious cases by splitting on word boundaries, but they still treat unbelievable as one indivisible unit.
import re
from collections import Counter
def regex_tokens(text):
pattern = r"[A-Za-z]+(?:'[A-Za-z]+)?|\d+(?:\.\d+)?|[^\s]"
return re.findall(pattern, text)
text = "Don't stop — NLP's future is bright, version 3.5!"
print(regex_tokens(text))
# ['Don't', 'stop', '—', "NLP's", 'future', 'is', 'bright', ',', 'version', '3.5', '!']
def fertility(tokens, words):
return round(len(tokens) / max(words, 1), 3)
print(fertility(regex_tokens(text), len(text.split())))
The real problem appears at scale. A hundred-million-word corpus contains roughly 400,000 distinct types, and the long tail is where almost every type occurs once. You can either grow the embedding matrix to hold them — paying for rows that are never trained — or map them all to a single unknown symbol and lose the information that made the sentence specific. Subword tokenization is the compromise that resolves both failures at once.
The BPE merge loop
Byte-Pair Encoding arrived in NLP from data compression. Start with an alphabet of characters, count every adjacent pair across the corpus, merge the single most frequent pair into a new symbol, and repeat. After m merges the vocabulary holds exactly V0 + m entries, which is why vocabulary size is a hyperparameter you choose rather than an accident you discover.
def train_bpe(corpus, num_merges, vocab_size=256):
words = [list(w) + ["</w>"] for w in corpus.split()]
alphabet = sorted({c for w in words for c in w})
symbols = {c: i for i, c in enumerate(alphabet)}
merges = []
for _ in range(num_merges):
pairs = Counter()
for w in words:
for a, b in zip(w, w[1:]):
pairs[(a, b)] += 1
if not pairs:
break
best = pairs.most_common(1)[0][0]
merges.append(best)
a, b = best
merged = a + b
symbols.setdefault(merged, len(symbols))
words = [[merged if x == a and y == b else x + y
for x, y in zip(w, w[1:])] for w in words]
words = [list(w) for w in words]
return symbols, merges
syms, merges = train_bpe("low lower lowest low low", 3)
print(merges[:3])
# [('l', 'o'), ('lo', 'w'), ('low', 'e')]
print("vocab grows to:", len(syms))
Encoding at inference time is a greedy replay of that merge list: apply merge 0, then merge 1, and so on, until no rule matches. That is why training is expensive and serving is cheap.
WordPiece, Unigram, and SentencePiece
BERT uses WordPiece, which keeps the loop but changes the scoring rule. BPE merges the pair with the highest raw count; WordPiece merges the pair whose concatenation is most predictable, freq(xy) divided by freq(x) times freq(y). The practical effect is that WordPiece refuses merges which only combine two already-common symbols, so it produces slightly more conservative, more morphologically meaningful pieces.
Unigram inverts the strategy. It begins with a large candidate vocabulary and repeatedly prunes the symbols whose removal raises corpus negative log likelihood the least, which makes vocabulary reduction a search problem rather than a greedy accumulation. SentencePiece adds a crucial engineering guarantee: it treats the input as a raw stream of bytes, so no pre-tokenization step is required and the same model file works for English, Thai, or Japanese without a language-specific word segmenter.
| Algorithm | Selection rule | Typical models | Vocab size |
|---|---|---|---|
| BPE | Highest pair frequency | GPT-2, RoBERTa | 50,257 |
| WordPiece | Highest likelihood ratio | BERT, DistilBERT | 30,522 |
| Unigram | Lowest pruning loss | T5, ALBERT | 32,128 |
| Byte-level BPE | Frequency over UTF-8 bytes | GPT-4, CodeLlama | 100,256 |
| SentencePiece BPE | Frequency, no pre-split | Llama, T5 | 32,000 |
from transformers import AutoTokenizer
gpt2 = AutoTokenizer.from_pretrained("gpt2")
bert = AutoTokenizer.from_pretrained("bert-base-uncased")
text = "Tokenizers decide the shape of every sequence."
gpt_ids = gpt2(text)["input_ids"]
print("gpt2:", gpt_ids[:8], "fertility:", round(len(gpt_ids) / len(text.split()), 3))
print("bert on 'unaffable':", bert.tokenize("unaffable"))
# ['un', '##aff', '##able']
assert gpt2.decode(gpt2(text)["input_ids"]) == text
The ## marker in the BERT output is a continuation flag: it tells the model that this piece attaches to the previous one. Drop it and un becomes a standalone word, which quietly changes the meaning of every compound.
Bytes close the coverage hole
Byte-level tokenization starts from the 256 values of a single byte rather than from a Unicode alphabet. Because UTF-8 text is already a byte stream, every possible string is encodable — there is no unknown token, and decode(encode(x)) always returns x. The cost is fertility: a non-Latin character often needs two to four byte tokens instead of one, so Chinese and emoji-heavy text burns context much faster than English prose.
This is the trade you are actually choosing between when you compare a 30,000 entry vocabulary with a 100,000 entry one. More entries means shorter sequences and a bigger embedding matrix; fewer entries means cheaper embeddings and longer sequences. At hidden size 768, each extra 100,000 tokens adds 76,800,000 parameters before a single attention layer runs.
💡Measure fertility before you ship
Debugging a tokenizer in practice
When text comes back garbled, the fault is almost always in normalization rather than in the model. Case folding, accent stripping, and whitespace collapsing all change ids, so a mismatch between training-time and serving-time normalization produces embeddings that are technically valid and semantically wrong. The checks below catch the common cases in a few lines.
def audit_tokenizer(tokenizer, samples):
for text in samples:
ids = tokenizer(text)["input_ids"]
back = tokenizer.decode(ids)
unk = sum(1 for i in ids if i == tokenizer.unk_token_id)
print(f"{len(ids):>3} ids unk={unk} roundtrip={back == text} {text[:40]}")
samples = [
"The café reopened after three years.",
"naïve résumé — naïve résumé",
"emoji check: rocket and star",
]
audit_tokenizer(gpt2, samples)
Round-trip equality is the single most useful assertion. If decode(encode(text)) differs from the input, no amount of fine-tuning will recover the lost characters.
Choosing a scheme for a real project
For English-only classification on short inputs, a 30,000 entry WordPiece vocabulary is plenty, because documents rarely contain the long tail that forces exotic splits and the sequences are short enough that a little extra fertility costs nothing. For a code model or a multilingual assistant the calculus changes: identifiers like parseConfigFile fragment badly under a small vocabulary, and non-Latin scripts multiply token counts unless you pay for byte-level coverage. A practical selection procedure is to take a thousand held-out examples from production, encode them under two or three candidate tokenizers, and compare fertility, unknown-token rate, and the resulting sequence length distribution against your context budget. Only after that measurement is it worth training anything custom, because a tokenizer trained on the wrong slice of text will encode perfectly and still waste context on every request.
Common Mistakes
Assuming one word equals one token when budgeting context
Fix: Compute fertility on your own corpus; English sits near 1.33 tokens per word and code often near 3.0.
Swapping the tokenizer under a fine-tuned checkpoint
Fix: Token ids index embedding rows, so a new tokenizer forces a full retrain or at minimum an embedding remap.
Choosing vocabulary size by copying another model
Fix: Budget it: embedding cost is V times d, sequence savings come from the fertility the merges actually buy.
Lowercasing at serving time but not at training time
Fix: Keep normalization identical on both paths and assert round-trip equality in your test suite.
Best Practices
- Train the tokenizer on the distribution the model will see, including domain jargon and code identifiers
- Reserve pad, bos, eos, and task marker ids before training so ids never shift later
- Report fertility alongside perplexity, since a slower tokenizer quietly shortens every example
- Prefer byte-level coverage for multilingual products so no input can produce an unknown token
Interview Questions
Q1: Why does BPE grow the vocabulary by exactly one per iteration?
Each iteration picks a single most frequent adjacent pair and merges it into one new symbol, so starting from a 256 byte alphabet and running 49,999 merges yields 50,255 entries; GPT-2 stops at 50,257 including special tokens.
Q2: How does WordPiece differ from BPE?
BPE merges the pair with the highest raw corpus count, while WordPiece merges the pair maximizing freq(xy) over freq(x) times freq(y), rejecting predictable-but-uninformative merges.
Q3: What is fertility and why does it matter for deployment?
Fertility is tokens per word. Moving from 1.33 to 1.60 on an 8,192 token window drops usable prose from 6,160 words to 5,120, which changes retrieval recall and truncation rates without any error being raised.
Key Takeaways
- Tokenization fixes the integer interface every later stage learns over, so changing it invalidates a trained model
- Word-level schemes either blow up the embedding matrix or emit unknown tokens; subword schemes avoid both
- BPE adds one symbol per merge so V = V0 + m, WordPiece scores by likelihood ratio, Unigram prunes by loss
- Fertility and vocabulary size trade directly against each other and against embedding parameter count
- Round-trip decode equality is the cheapest correctness test you can run on a tokenizer