Sub topic 7
WordPiece: choosing merges by a likelihood-style score
This chapter assumes you have read the BPE training chapter. You should be comfortable with the merge loop, with counting adjacent pairs in a Counter, and with the idea that a vocabulary is built from an initial alphabet plus learned merges. Basic Python is enough for the code.
What changes compared with BPE
WordPiece builds its vocabulary with the same outer loop as BPE. It starts from single characters and repeatedly merges two adjacent units into one new unit. The difference is how it picks the pair to merge.
- BPE picks the pair with the highest raw count.
- WordPiece picks the pair with the highest score. The score is the pair count divided by the product of the counts of its two parts.
The intuition: a pair deserves a merge when its parts tend to occur together, not merely when the pair is common. If a and b are both very frequent, they will meet often by chance, and a high pair count says little. If a and b are rare on their own but almost always appear together, merging them is informative.
The score
For a candidate pair (a, b):
score(a, b) = count(a b) / (count(a) * count(b))Here count(a b) is how often the two units are adjacent in the training words, weighted by word frequency. count(a) and count(b) are how often each unit occurs anywhere.
Why this is "likelihood-style"
Suppose the corpus is modelled as independent draws of units. The probability of a unit is its count divided by the total number of units, N. Merging a and b into ab replaces count(ab) occurrences of two draws with one draw. The change in corpus log-likelihood is roughly:
count(ab) * [ log p(ab) - log p(a) - log p(b) ]The bracketed term is the pointwise mutual information (PMI) of the pair. It equals log(score) + log N. Since N is the same for every candidate, ranking by score is the same as ranking by PMI. The full likelihood gain also multiplies by count(ab). The simplified score leaves that factor out. This has a practical effect, covered under edge cases below.
The word "likelihood" therefore describes the motivation. The code below does not compute a likelihood. It computes a ratio of counts.
The training loop
Two details differ from the BPE chapter:
- WordPiece has no end-of-word marker. Instead, every character after the first in a word gets the
##prefix.hugstarts ash,##u,##g. Souat the start of a word and##uinside a word are different units. - When two units merge, the
##of the right-hand unit is dropped.##gand##smerge into##gs.pand##umerge intopu.
A worked first step
Use this word-frequency table: hug 10, pug 5, pun 12, bun 4, hugs 5.
Unit counts after splitting:
| Unit | Count |
|---|---|
| h | 15 |
| ##u | 36 |
| ##g | 20 |
| ##s | 5 |
| p | 17 |
| ##n | 16 |
| b | 4 |
Pair counts and scores:
| Pair | Pair count | Score |
|---|---|---|
| h ##u | 15 | 15 / (15 × 36) = 0.0278 |
| ##u ##g | 20 | 20 / (36 × 20) = 0.0278 |
| ##g ##s | 5 | 5 / (20 × 5) = 0.0500 |
| p ##u | 17 | 17 / (17 × 36) = 0.0278 |
| ##u ##n | 16 | 16 / (36 × 16) = 0.0278 |
| b ##u | 4 | 4 / (4 × 36) = 0.0278 |
BPE would merge ##u ##g first, because 20 is the highest count. WordPiece merges ##g ##s first. The letter s only ever appears after g, so the pair has the highest association even though its count is the smallest among the pairs that include ##g.
After that merge, every remaining pair scores exactly 1/36. The next choice is a tie. The implementation below breaks ties by higher pair count, then by the pair itself, so that results are reproducible. That picks p ##u (count 17) and creates pu.
A minimal trainer
The code uses Fraction so that ties are exact. With floats, 1/36 computed from different integers could differ in the last bit and make the tie-break arbitrary.
from collections import Counter
from fractions import Fraction
def split_word(word):
return tuple([word[0]] + ["##" + ch for ch in word[1:]])
def join_tokens(left, right):
return left + right[2:] if right.startswith("##") else left + right
def count_units_and_pairs(words):
units = Counter()
pairs = Counter()
for symbols, freq in words.items():
for s in symbols:
units[s] += freq
for a, b in zip(symbols, symbols[1:]):
pairs[(a, b)] += freq
return units, pairs
def best_pair(words):
units, pairs = count_units_and_pairs(words)
if not pairs:
return None
def key(pair):
a, b = pair
score = Fraction(pairs[pair], units[a] * units[b])
return (score, pairs[pair], pair)
return max(pairs, key=key)
def apply_merge(words, pair):
new_token = join_tokens(*pair)
merged = Counter()
for symbols, freq in words.items():
out = []
i = 0
while i < len(symbols):
if i < len(symbols) - 1 and (symbols[i], symbols[i + 1]) == pair:
out.append(new_token)
i += 2
else:
out.append(symbols[i])
i += 1
merged[tuple(out)] += freq
return merged
def train_wordpiece(word_freqs, num_merges):
words = Counter({split_word(w): f for w, f in word_freqs.items()})
vocab = {s for symbols in words for s in symbols}
merges = []
for _ in range(num_merges):
pair = best_pair(words)
if pair is None:
break
words = apply_merge(words, pair)
vocab.add(join_tokens(*pair))
merges.append(pair)
return vocab, merges
word_freqs = {"hug": 10, "pug": 5, "pun": 12, "bun": 4, "hugs": 5}
vocab, merges = train_wordpiece(word_freqs, 2)
print([join_tokens(a, b) for a, b in merges]) # ['##gs', 'pu']
print(sorted(vocab))
# ['##g', '##gs', '##n', '##s', '##u', 'b', 'h', 'p', 'pu']Notice that ##s stays in the vocabulary even though no training word uses it on its own after the first merge. Merged units are added, never removed. Keeping the single characters is also what lets the encoder fall back to them for unseen words.
From vocabulary to tokenisation
BPE records an ordered merge list and replays it on new text. WordPiece training produces a vocabulary, and the encoder uses only the vocabulary. At encoding time it takes the longest vocabulary entry that matches at each position. Merge order is not used. That is the topic of the next chapter, but the consequence matters now: the training score decides which units exist, and the greedy matcher decides how they are used. The two stages are only loosely coupled, so a word may be split differently from the way training combined its pieces.
Edge cases and failure modes
- Rare-unit pairs score high. If
aandbeach occur once and appear together, the score is 1/(1×1) = 1, far above any frequent pair. Without a safeguard, early merges would be dominated by noise. Real implementations apply a minimum frequency or work from an alphabet that already contains the common characters. A count-weighted likelihood gain would penalise this, which is one reason the simplified ratio is only an approximation. - Frequent units are suppressed. A pair of two very common units, such as
##eand##rin English, gets a low score even when it is very common. Such pairs tend to enter the vocabulary late or not at all, unless they reach a mid-sized vocabulary through other merges. - Scores change after every merge. Merging
##g ##slowers the count of##gand##s, so every pair that involves them must be rescored. A naive implementation like the one above recounts everything each iteration, which is fine for demonstrations. Production trainers update counts incrementally. - Ties. Exact ties are common on small corpora, as the example shows. Different tie-breaking rules give different vocabularies from the same data, which is a reason to treat a published vocabulary as an artefact, not as something you can regenerate exactly.
- Library differences. Training with the Hugging Face
tokenizerslibrary'sWordPieceTrainermay not use this score. To my knowledge it is built on its BPE trainer and chooses by count, while the resulting model still encodes in WordPiece style. If matching the score matters to you, check the source of the version you use.
BPE and WordPiece side by side
| Aspect | BPE | WordPiece |
|---|---|---|
| Merge criterion | Highest pair count | Highest pair count / (count a × count b) |
| Word-internal marker | End-of-word marker, or none with byte-level BPE | `##` on non-initial units |
| Output of training | Ordered merge list | Vocabulary set |
| Encoding | Replay merges in order | Greedy longest match against the vocabulary |
| Favours | Common sequences | Sequences whose parts rarely appear apart |
Exercise
Using the word counts hug 10, pug 5, pun 12, bun 4, hugs 5, compute the WordPiece score of the pair (##u, ##g) before any merge, and explain why BPE and WordPiece disagree about which pair to merge first.
Show answer
Before any merge, count(##u ##g) = 20 (hug 10, pug 5, hugs 5), count(##u) = 36 and count(##g) = 20. The score is 20 / (36 × 20) = 1/36 ≈ 0.0278. BPE ranks by raw count, and 20 is the highest pair count, so it merges (##u, ##g) first. WordPiece divides by the counts of the parts. The pair (##g, ##s) scores 5 / (20 × 5) = 0.05, which beats 1/36, so WordPiece merges it first.
Exercise
Why does the trainer in this chapter use Fraction instead of float division, and what would go wrong with floats on the second merge of the example corpus?
Show answer
After the first merge, all six candidate pairs have a score of exactly 1/36. With floats, the same mathematical value computed from different integers can differ in the last bit, so the maximum would be chosen by rounding error and not by the intended tie-break (higher pair count, then the pair itself). Fraction keeps the scores exact, so the tie is real and the tie-break picks (p, ##u) with count 17.