Sub topic 14
Comparing the Three Approaches and Choosing One
This chapter assumes you have read the earlier chapters on BPE merge learning, WordPiece greedy longest-match encoding, the unigram model, and SentencePiece. It also assumes basic Python. The goal is to put the approaches side by side and give you criteria for choosing one for a real project.
Separate the Two Questions
"BPE vs. WordPiece vs. SentencePiece" mixes categories. Two separate questions are involved:
- Which algorithm builds and applies the vocabulary? The options are BPE, WordPiece, and unigram.
- Which software and input convention wraps it? The options are a pre-tokenising library such as Hugging Face
tokenizers, or SentencePiece, which works on raw text.
SentencePiece is a toolkit. It implements BPE and unigram, and it sets rules for whitespace and reversibility. WordPiece is an algorithm with no widely used standalone toolkit. You mostly meet it through BERT-family models. Keeping the two questions apart prevents most confusion when you compare options.
How the Algorithms Differ
| Property | BPE | WordPiece | Unigram LM |
|---|---|---|---|
| Training direction | Bottom-up: start with characters (or bytes) and merge | Bottom-up: start with characters and merge | Top-down: start with a large candidate set and prune |
| Training criterion | Most frequent adjacent pair | Pair that most improves corpus likelihood (often approximated as pair count divided by the product of the two part counts) | Remove pieces whose loss increases the corpus likelihood least |
| Encoding | Replay merges in learned order | Greedy longest match from the left | Pick the highest-probability segmentation (Viterbi) |
| Output per word | One deterministic split | One deterministic split | Can sample alternatives |
| Continuation marker | None by default, or an end-of-word `</w>` | `##` on non-initial pieces | Whitespace marker `▁` on word-initial pieces (in SentencePiece) |
| Unknown handling | None at byte level, otherwise `<unk>` | Whole word becomes `[UNK]` if any position fails | `<unk>`, or byte fallback if enabled |
Three consequences matter in practice.
- Frequency vs. likelihood. BPE merges whatever is common, so very frequent pairs such as
eandsmerge early even when they carry little meaning. WordPiece's score divides by the parts' counts, which favours pairs whose parts rarely appear apart. The effect on downstream accuracy is usually small and hard to isolate. - Encoding is not the reverse of training. BPE encoding replays merges in order. WordPiece encoding ignores the merge order and uses only the final vocabulary. Two vocabularies with identical entries therefore encode identically in WordPiece, but not necessarily in BPE.
- Unigram is probabilistic. It can output several segmentations with probabilities. Sampling them during training ("subword regularisation") exposes the model to varied splits of the same word. This helps in low-resource settings and noisy text.
A Decision Flow
Criteria That Decide the Choice
Reuse Beats Preference
If you fine-tune or run a pretrained model, you must use the tokeniser it was trained with. The embedding matrix rows are tied to specific token ids, and a different vocabulary silently maps ids to the wrong embeddings. Choose a new tokeniser only when you train a model from scratch, or when you build a vocabulary for a domain and accept pretraining or continued training.
Language Coverage and Whitespace
WordPiece and classic BPE rely on a pre-tokeniser that splits on whitespace and punctuation. That works well for English and poorly for Chinese, Japanese, and Thai, where words are not separated by spaces. SentencePiece treats whitespace as an ordinary symbol, ▁, so it needs no language-specific pre-tokenisation. For a multilingual model, this is the strongest argument for SentencePiece.
Lossless Round Trips
A pipeline that must return the exact input text needs reversible tokenisation. SentencePiece guarantees it by design: decode(encode(text)) returns the normalised text, and whitespace is recoverable because it is encoded as ▁. A BERT-style pipeline lowercases and strips accents in some models, and it splits on punctuation before WordPiece runs. It cannot recover the original spacing or case. This matters for generation, code, and anything where whitespace is meaningful.
Unknown Tokens
WordPiece's rule that one unmatched position turns the whole word into [UNK] is a real weakness. The word unaffordable in the earlier example loses all information, including the matching prefix un. Byte-level BPE avoids this because every string is a sequence of the 256 byte values. SentencePiece can approximate it with byte_fallback=True. If your data includes emoji, rare scripts, or user-typed noise, prefer a byte-level or byte-fallback design.
Sequence Length and Cost
Fewer tokens per word means shorter sequences, lower attention cost, and more text per context window. Vocabulary size and training data language mix set this. A tokeniser trained mostly on English splits other languages into many more pieces. The same sentence can cost several times more tokens in some languages than in English. Measure it for your own data instead of trusting a general claim.
Measure Instead of Guess
A useful metric is fertility: the average number of tokens per word. Pair it with the unknown rate: the share of words that come out as the unknown token. Both are cheap to compute on held-out text. The function below works with any encoder that takes a word and returns a list of tokens. This example uses the WordPiece encoder from the earlier chapter.
def wordpiece_encode(word, vocab, unk="[UNK]"):
tokens = []
start = 0
while start < len(word):
end = len(word)
piece = None
while start < end:
candidate = word[start:end]
if start > 0:
candidate = "##" + candidate
if candidate in vocab:
piece = candidate
break
end -= 1
if piece is None:
return [unk]
tokens.append(piece)
start = end
return tokens
def fertility(encode, words):
return sum(len(encode(w)) for w in words) / len(words)
def unk_rate(encode, words, unk="[UNK]"):
return sum(1 for w in words if unk in encode(w)) / len(words)
vocab = {"un", "##aff", "##able", "play", "##ing"}
words = ["unaffable", "playing", "unaffordable"]
encode = lambda w: wordpiece_encode(w, vocab)
print(f"fertility: {fertility(encode, words):.2f}")
print(f"unk rate: {unk_rate(encode, words):.2f}")This prints a fertility of 2.00 and an unknown rate of 0.33. Note that the unknown word lowers fertility, because [UNK] counts as one token. A low fertility therefore means something only alongside a low unknown rate. For a SentencePiece model, replace encode with lambda w: sp.encode(w, out_type=str). Compute both metrics on text from the same distribution you will deploy on, not on the training corpus.
Common Failure Modes
- Train/inference mismatch. Normalisation, casing, and special-token handling must be identical at training and inference time. A model trained with lowercased input sees garbage if you pass mixed-case text.
- Numbers. Frequency-driven merges split numbers inconsistently.
1234may become one token and1235two, which makes arithmetic harder. Some designs split digits individually to avoid this. - Special tokens in user text. If a user types
[SEP]or<s>and your tokeniser parses it as the special token, you have an injection path. Decide explicitly whether special-token strings in raw input are parsed or escaped. - Vocabulary mismatch after edits. Adding tokens to a vocabulary requires resizing the model's embedding matrix and training the new rows.
- Treating
▁and##as equivalent. They mark opposite things.▁marks a word start, and##marks a continuation. Code that detokenises by stripping one convention will corrupt output from the other.
A Practical Default
For a new project with no pretrained constraint, a reasonable default is a SentencePiece model with byte_fallback=True, trained on text that matches your deployment languages. Choose BPE if you want simple, deterministic segmentation and the same behaviour that most large generative models use. Choose unigram if you want subword regularisation or tend to work with small or noisy corpora. Use WordPiece when you must match a BERT-family checkpoint, since the benefit of choosing it freshly is small.
Then verify the choice with the fertility and unknown-rate checks above, a round-trip test on messy real inputs, and a look at how numbers and your most important rare words are split.
Exercise
You are building a chat model for English, Japanese, and Arabic from scratch. Users paste code and emoji. Which tokeniser setup would you choose, and which two measurements would you run before committing?
Show answer
Use SentencePiece (BPE or unigram) with byte_fallback=True, trained on a corpus that balances the three languages. SentencePiece needs no whitespace pre-tokeniser, which Japanese requires. It preserves whitespace for code, and byte fallback covers emoji and rare characters without unknown tokens. Before committing, measure fertility per language on held-out text, to confirm no language is split far more finely than the others, and the unknown rate plus a decode(encode(text)) round-trip test on pasted code and emoji.
Exercise
Why can two WordPiece vocabularies with identical entries produce identical encodings, while two BPE merge lists that produce the same final vocabulary may not?
Show answer
WordPiece encoding uses only greedy longest match against the vocabulary set, so the training history is irrelevant. BPE encoding replays the merges in their learned order. A different order can apply merges in a different sequence and yield a different split of the same word.