Sub topic 5
Subword tokenisation: BPE and WordPiece
This chapter assumes you can read basic Python and you know what a token and a type are. You should also know why word-level tokenisers struggle with rare words, and you should have met the idea of a fixed vocabulary. Earlier chapters covered rule-based tokenisers, stemming and lemmatisation. Here we look at the approach that most modern language models use instead.
The problem subwords solve
A word-level tokeniser needs a fixed vocabulary. Anything outside it becomes an unknown token, usually written [UNK]. English text keeps producing new strings: names, typos, compounds, product codes, and inflected forms such as "tokenisable". Language with rich morphology makes this worse, because one stem can yield dozens of surface forms.
There are two extreme fixes, and both have costs:
- Huge word vocabulary. The embedding table grows, most rows are rarely trained, and unknown words still appear.
- Characters only. There are no unknown words, but sequences become very long. The model must relearn spelling patterns that a vocabulary could store directly.
Subword tokenisation sits between these. Frequent words stay whole, and rare words are broken into smaller pieces that occur often. The word "unhappiness" might become un, happi, ness. In the worst case a word falls back to single characters or bytes, so nothing is truly out of vocabulary.
Unlike stemming, subword splitting is learned from data, not written by hand. It does not try to find linguistically correct morphemes. A piece such as happi is useful because it is frequent, not because it is a real morpheme.
Byte-pair encoding (BPE)
BPE was introduced as a data compression method and adapted for neural machine translation by Sennrich and colleagues. Training works like this:
- Split every word in the training corpus into characters and add an end-of-word marker such as
</w>. Record each word's frequency. - Count how often each adjacent pair of symbols occurs, weighted by word frequency.
- Merge the most frequent pair into one new symbol. Add that symbol to the vocabulary and record the merge.
- Repeat steps 2 and 3 until the vocabulary reaches a target size, or until a set number of merges is done.
The vocabulary size is therefore a hyperparameter you choose. The ordered list of merges is the whole trained model.
A working BPE trainer
The corpus below is the classic toy example. The word frequencies say that "low" occurs 5 times, "lower" 2 times, "newest" 6 times and "widest" 3 times.
from collections import Counter
END = "</w>"
def pair_counts(vocab):
counts = Counter()
for symbols, freq in vocab.items():
for a, b in zip(symbols, symbols[1:]):
counts[(a, b)] += freq
return counts
def merge_word(symbols, pair):
out = []
i = 0
while i < len(symbols):
if i < len(symbols) - 1 and (symbols[i], symbols[i + 1]) == pair:
out.append(symbols[i] + symbols[i + 1])
i += 2
else:
out.append(symbols[i])
i += 1
return tuple(out)
def learn_bpe(word_freqs, num_merges):
vocab = {tuple(word) + (END,): freq for word, freq in word_freqs.items()}
merges = []
for _ in range(num_merges):
counts = pair_counts(vocab)
if not counts:
break
best = max(counts, key=counts.get) # first pair with the top count wins ties
merges.append(best)
new_vocab = {}
for symbols, freq in vocab.items():
merged = merge_word(symbols, best)
new_vocab[merged] = new_vocab.get(merged, 0) + freq
vocab = new_vocab
return merges
def segment(word, merges):
symbols = tuple(word) + (END,)
for pair in merges: # apply merges in the order they were learned
symbols = merge_word(symbols, pair)
return list(symbols)
corpus = {"low": 5, "lower": 2, "newest": 6, "widest": 3}
merges = learn_bpe(corpus, 5)
print(merges)
print(segment("lowest", merges))
print(segment("newer", merges))Running it prints:
[('e', 's'), ('es', 't'), ('est', '</w>'), ('l', 'o'), ('lo', 'w')]
['low', 'est</w>']
['n', 'e', 'w', 'e', 'r', '</w>']Some points to notice:
- The first three merges build
est</w>. This is the most frequent ending in the corpus (9 occurrences, from "newest" and "widest"). - "lowest" never appeared in training, yet it segments into two known pieces:
lowandest</w>. - "newer" falls back to single characters because none of the learned merges apply to it. This is the safety net. It also shows that five merges is far too few for a real vocabulary.
- Tie-breaking matters. Several pairs had the same count at step 1. Different implementations break ties differently and can produce different vocabularies from the same data.
At inference time, you apply the stored merges in the order they were learned. You do not recount anything.
WordPiece
WordPiece was developed at Google and is used by BERT and related models. It is similar to BPE in outline: start from characters and grow a vocabulary by merging. It differs in two ways.
Merge criterion. BPE merges the most frequent pair. WordPiece merges the pair that most increases the likelihood of the training data under a language model. In the commonly cited simplification, it picks the pair with the highest score:
score(a, b) = count(ab) / (count(a) × count(b))
A pair made of two rare pieces that nearly always appear together can beat a pair of two very common pieces. BPE would prefer the common pair, because raw frequency favours it.
Marking and inference. WordPiece marks word-internal pieces with a prefix, usually ##, instead of an end-of-word marker. At inference it does not replay a merge list. It uses greedy longest-match-first: from the start of the word, take the longest piece in the vocabulary, then continue from where it ended. If at any point no piece matches, the whole word becomes [UNK].
def wordpiece(word, vocab, unk="[UNK]"):
pieces = []
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]
pieces.append(piece)
start = end
return pieces
vocab = {"un", "##aff", "##able", "##a", "##ble", "play", "##ing"}
print(wordpiece("unaffable", vocab))
print(wordpiece("playing", vocab))
print(wordpiece("xyz", vocab))The output is:
['un', '##aff', '##able']
['play', '##ing']
['[UNK]']For "unaffable", the matcher takes un. From position 2 it tries ##affable, then shorter strings, until ##aff matches. It then matches ##able. The string "xyz" has no matching piece, so the whole word is unknown. This differs from BPE's character fallback. A WordPiece vocabulary normally includes every single character, in both plain and ## forms, so real vocabularies rarely hit this case on ordinary text.
BPE and WordPiece compared
| Aspect | BPE | WordPiece |
|---|---|---|
| Merge choice | Most frequent adjacent pair | Pair with the best likelihood-based score |
| Stored artefact | Ordered merge list | Vocabulary list |
| Inference | Replay merges in learned order | Greedy longest-match-first |
| Word-internal marker | Often an end-of-word marker, or a space marker in byte-level variants | `##` prefix on continuation pieces |
| Unknown words | Fall back to characters, or bytes in byte-level BPE | Whole word becomes `[UNK]` if no piece matches |
| Typical use | GPT-style models | BERT-style models |
A related method, the unigram language model tokeniser, works in the opposite direction. It starts with a large candidate vocabulary and prunes it. It is often packaged with SentencePiece, which also treats whitespace as an ordinary symbol so no pre-tokenisation is needed. This chapter covers only BPE and WordPiece.
Practical considerations
Pre-tokenisation
Most implementations first split text into rough words, usually on whitespace and punctuation, and learn subwords inside those units. Without this step, a merge could join the end of one word to the start of the next. The choice of pre-tokeniser affects the result. Tokenisers trained with different pre-tokenisation rules are not interchangeable, even at the same vocabulary size.
Byte-level BPE
Character-level BPE still needs a base alphabet, and Unicode contains well over a hundred thousand characters. Byte-level BPE starts from the 256 possible byte values instead. Any string in any script can be encoded, so unknown tokens cannot occur. The cost is that rare characters may take several tokens, because one character can be up to four bytes in UTF-8.
Normalisation still applies
Subword tokenisers do not remove the need for normalisation. Case folding and Unicode normalisation change which strings reach the tokeniser. Many BERT tokenisers lower-case text and strip accents, while GPT-style tokenisers usually keep case. A decomposed "é" and a composed "é" can tokenise differently if you skip Unicode normalisation.
Trained tokenisers are tied to their models
A model's embeddings are indexed by the tokeniser's vocabulary. You must use the same tokeniser the model was trained with. Retraining a tokeniser on new data changes the token IDs and breaks the pretrained embeddings.
Common errors and gotchas
- Treating subword pieces as morphemes.
happiandnesslook meaningful, but a split likewalk,ed,ingis a statistical result. Splits can look odd, such as cutting a word mid-syllable. - Forgetting the continuation marker. When you rebuild text from WordPiece output, you must join
##pieces to the previous piece without a space. Dropping the prefix by mistake merges separate words or splits whole ones. - Comparing sequence lengths across tokenisers. The same sentence can be 12 tokens under one tokeniser and 20 under another. Context limits, cost and speed all depend on that count.
- Training on unrepresentative data. A vocabulary learned from English news text splits medical terms, code or other languages into many short pieces. The model still works, but sequences get long and efficiency drops.
- Choosing the vocabulary size without testing. Small vocabularies give long sequences. Large ones leave many embedding rows undertrained. Typical values range from about 30,000 to over 100,000, depending on languages and model size.
- Assuming no information loss. Segmentation is reversible for byte-level BPE. For tokenisers that lower-case or strip accents, the original text cannot be fully recovered from the tokens.
Exercises
Exercise
In the BPE example, the corpus is {"low": 5, "lower": 2, "newest": 6, "widest": 3}. Why is the first merge ('e', 's') and not ('l', 'o')?
Show answer
The pair ('e', 's') occurs in "newest" (6) and "widest" (3), so its weighted count is 9. The pair ('l', 'o') occurs in "low" (5) and "lower" (2), so its count is 7. BPE merges the highest-count pair first. Several pairs tie at 9, and the implementation breaks the tie by taking the first one it saw.
Exercise
Using the vocabulary {"un", "##aff", "##able", "##a", "##ble", "play", "##ing"}, what does the greedy longest-match-first WordPiece function return for "unable"? Explain the steps.
Show answer
It returns ['un', '##able']. Starting at position 0, the longest matching piece is "un" ("unable" and the shorter prefixes up to "unab" are not in the vocabulary). From position 2 it tries "##able" first, and that is in the vocabulary, so it takes the piece and reaches the end of the word.
Exercise
A team trains a BPE tokeniser on English text only, then uses it on a Finnish corpus. What problem will they most likely see, and does it cause unknown tokens if the tokeniser is byte-level?
Show answer
Finnish words will split into many short pieces, since the learned merges reflect English. Sequences become long and the model sees less meaningful units. With byte-level BPE there are no unknown tokens, because every string can be encoded as bytes. The cost is length and weaker efficiency, not failure.