Topic 01 of 62 · Text in, prediction out
BPE vs WordPiece vs Unigram
MediumHow do BPE, WordPiece, and Unigram build a subword vocabulary, and how do they differ when encoding new text?
1 · Start with the intuition
Every subword tokenizer tries to solve the same practical problem: give the model a fixed-size vocabulary (say 32K to 128K tokens) that keeps common words intact as single tokens while splitting rare or unfamiliar words into smaller reusable pieces. BPE and WordPiece build their vocabulary **bottom-up**, starting from individual characters/bytes and repeatedly merging pairs. Unigram works **top-down**, starting with a huge candidate list of substrings and pruning away the ones that hurt corpus likelihood the least.
2 · How the mechanism works
Mechanism step 1 of 3 · no question to answer
Start from a base alphabet
Initialize with raw UTF-8 bytes (byte-level BPE) or characters, after applying a regex pre-tokenizer that prevents merges across word/punctuation boundaries.
Next, we will look at: Grow bottom-up or prune top-down. Move on when this operation makes sense.
Visualizing the behavior
BPE: candidate pairs before the first merge
Derivedadjacent-pair count in the toy corpus
Same word, three conventions for marking word boundaries
Illustrative3 · The governing equation
BPE merge rule: argmax_{(a,b)} count(ab)
WordPiece merge rule: argmax_{(a,b)} count(ab) / (count(a) · count(b))
Unigram objective: argmax_{seg(x)} Π_{u ∈ seg(x)} p(u) (solved via Viterbi)Notation: SentencePiece is an implementation library that runs BPE or Unigram directly on raw Unicode strings by treating whitespace as a regular visible character (▁, U+2581) rather than pre-splitting on spaces.
Why did byte-level BPE become the standard for modern LLMs (GPT-2/3/4, Llama 3, Qwen)? Because starting from all 256 raw byte values guarantees **zero `<unk>` (unknown) tokens**: any Unicode emoji, rare script, or binary string can always fall back to its UTF-8 bytes. Notice how the three algorithms differ at encode time: BPE does not just look for the longest token in the vocabulary—it strictly replays merges in the exact order they were learned during tokenizer training.
4 · Put concrete numbers on it
Worked numbers (from stated assumptions)5 · Common misconception to avoid
Treating the tokenizer as a swappable preprocessing script. The token IDs are hard-wired to row indices of the model’s input embedding matrix and output LM head—changing or re-sorting the tokenizer invalidates the checkpoint’s weights.
In practice · implementation & engineering rule of thumb
Watch out for leading spaces and special tokens when debugging prompts: "cat" and " cat" usually map to completely different token IDs, and serializing special tokens as raw text vs control IDs changes model behavior.
# Always verify how your tokenizer splits domain strings & whitespace:
ids_no_space = tokenizer.encode("cat", add_special_tokens=False)
ids_with_space = tokenizer.encode(" cat", add_special_tokens=False)
# Measure fertility (tokens per word or byte) on your target language slice:
tokens_per_byte = len(tokenizer.encode(sample_text)) / len(sample_text.encode("utf-8"))Go one level deeper
Follow-ups that often come after a correct first answer.
- Pre-tokenization matters as much as the algorithm
- Byte-level BPE tokenizers usually split text with a regex first (for example separating letters, digits and punctuation), so merges never cross those boundaries. Choices such as splitting numbers into single digits or 1–3 digit chunks change how arithmetic appears to the model.
- Subword regularization
- With Unigram (and BPE-dropout), you can sample a segmentation during training instead of always taking the single deterministic split. The model then sees multiple subword spellings of the same word, improving robustness to typos and morphological variants.
6 · Self-check & interview synthesis
Explain it in your own words first
Before revealing the reference answer, try answering the opening question aloud in four beats: what it is → how the math works → what trade-off it makes → a concrete number or failure mode.
Follow-up question interviewers often ask next
MediumWhy do modern tokenizers (like Llama 3 or GPT-4) use a regex to split digits or prevent merges across spaces and punctuation before running BPE?
Show follow-up reasoning
Without a pre-tokenization boundary rule, BPE greedily merges common words with trailing punctuation (creating separate tokens for `"dog"`, `"dog."`, `"dog,"`, `"dog!"`) and merges arbitrary multi-digit chunks like `"199"` + `"8"` vs `"19"` + `"98"`, which wastes vocabulary slots and makes arithmetic inconsistent.