SystemYou are an expert NLP engineer. You explain tokenization clearly and give correct, minimal code examples.
You are an expert NLP engineer. You explain tokenization clearly and give correct, minimal code examples.
User
What is the difference between BPE, Unigram and WordPiece tokenization? When is each used?
Assistant
All three are subword algorithms, but they learn the vocabulary differently and segment differently.
BPE (byte-pair encoding): bottom-up. Start from characters/bytes, greedily merge the most frequent pair. Segmentation applies merges in learned order. Deterministic, simple, the default for GPT-2/3/4, Llama, Mistral.
WordPiece: also bottom-up, but merges the pair that most improves likelihood (count divided by product of individual counts), not raw frequency. Segmentation is greedy longest-match-first with ## continuation markers. Used by BERT and derivatives.
Unigram: top-down. Start from a large vocabulary and prune tokens whose removal hurts total likelihood least (EM training). Segmentation picks the most probable split (Viterbi), and can sample alternative segmentations (subword regularization). Used by T5, mT5, ALBERT via SentencePiece.
BPE
WordPiece
Unigram
direction
bottom-up
bottom-up
top-down
merge score
frequency
likelihood gain
likelihood loss on removal
segment
merge rules
longest match
best-probability split
sampling
no
no
yes
WordPiece-style segmentation in a few lines:
python
defwordpiece_segment(word, vocab):
"""Greedy longest-match-first, ## marks continuations."""
tokens, i = [], 0while i < len(word):
end, cur = len(word), Nonewhile end > i:
piece = word[i:end] if i == 0else"##" + word[i:end]
if piece in vocab:
cur = piece
break
end -= 1if cur isNone:
return ["[UNK]"]
tokens.append(cur)
i = end
return tokens
vocab = {"un", "##aff", "##able", "low", "##er", "##est", "[UNK]"}
print(wordpiece_segment("unaffable", vocab)) # ['un', '##aff', '##able']print(wordpiece_segment("lowest", vocab)) # ['low', '##est']print(wordpiece_segment("zzz", vocab)) # ['[UNK]']
Rule of thumb: BPE for decoder LLMs, WordPiece if you continue a BERT-style stack, Unigram when you need segmentation sampling or strong multilingual coverage.