Sub topic 8
WordPiece encoding with greedy longest match and ## prefixes
This chapter covers how a trained WordPiece vocabulary is applied to new text. It assumes you know what a token is, can read basic Python (dictionaries, loops, string slicing), and have seen how a subword vocabulary is built. Training is covered in the previous chapter. Here the vocabulary is a fixed set of strings, and the question is how a word gets split into entries from that set.
What the encoder needs
A WordPiece encoder needs only the vocabulary. Training chose pieces with a likelihood-style score, but that score is not stored with the model and plays no part in encoding. The encoder checks whether a string is in the vocabulary. It does not rank candidate pieces.
This differs from BPE. A BPE encoder replays an ordered list of merges. A WordPiece encoder uses a set of strings and a fixed search rule.
Every vocabulary entry follows one naming convention:
- A piece that can start a word is stored as written, for example
play. - A piece that continues a word is stored with a
##prefix, for example##ing.
The ## is part of the token string. It is not a separate token. The vocabulary may contain both ing and ##ing, and they get different ids. ing means a word that starts with "ing". ##ing means "ing" in the middle or at the end of a word.
The greedy longest-match rule
Encoding works on one pre-tokenised word at a time. Normalisation and pre-tokenisation (lowercasing, splitting on whitespace and punctuation) have already happened. The rule for one word is:
- Set
startto 0. - Set
endto the end of the word. - Take
word[start:end]. Ifstart > 0, put##in front of it. - If that string is in the vocabulary, emit it and set
start = end. Otherwise, reduceendby one character and go back to step 3. - If
endreachesstartwithout a match, the word cannot be encoded. Emit[UNK]for the whole word. - Stop when
startreaches the end of the word.
This approach is called MaxMatch. At each position it takes the longest piece that fits, and it never goes back to reconsider an earlier choice.
A runnable implementation
The function below follows the rule exactly. It adds a length cap, which BERT's reference implementation also has, so one very long string cannot cause a lot of slicing work.
def wordpiece_encode(word, vocab, unk="[UNK]", max_chars=100):
if len(word) > max_chars:
return [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
vocab = {"un", "##aff", "##able", "play", "##ing", "##s"}
print(wordpiece_encode("unaffable", vocab)) # ['un', '##aff', '##able']
print(wordpiece_encode("unaffordable", vocab)) # ['[UNK]']
print(wordpiece_encode("playing", vocab)) # ['play', '##ing']
print(wordpiece_encode("plays", vocab)) # ['play', '##s']The inner while shrinks end until a match is found. The ## is added only to the candidate string, never to the slice of word. This keeps the character positions correct.
Tracing a word by hand
Take unaffable with the vocabulary above. Each row shows the longest candidate that matched at that position.
| `start` | Candidates tried (longest first) | Match | New `start` |
|---|---|---|---|
| 0 | `unaffable`, `unaffabl`, ... `una` | `un` | 2 |
| 2 | `##affable`, `##affabl`, `##affab`, `##affa` | `##aff` | 5 |
| 5 | `##able` | `##able` | 9 |
Now trace unaffordable. The first two steps match un and ##aff. At start = 5 the remainder is ordable. The encoder tries ##ordable, ##ordabl, and so on down to ##o. None of them is in the vocabulary, so end reaches start and the function returns [UNK].
The all-or-nothing unknown token
The second result above is the most important behaviour to remember. Two pieces had already matched, but the output is a single [UNK] for the entire word. The encoder discards the partial matches. A rare word is therefore replaced by a token that carries no information about it.
This is rare in practice for one reason. A WordPiece vocabulary normally contains every single character from the training alphabet, in both forms (a and ##a). Any word made of known characters can then fall back to character pieces. The real source of [UNK] is a character the vocabulary has never seen, such as a rare symbol, an emoji, or a script missing from the training data. That one character makes the whole word [UNK].
In the toy vocabulary above, the single characters are missing, so unaffordable fails. A larger vocabulary would not fail on it.
Greedy is not optimal
Longest match at each step does not guarantee the best segmentation. It does not even guarantee that a valid one is found. Consider this vocabulary:
vocab = {"a", "ab", "##bc"}
print(wordpiece_encode("abc", vocab)) # ['[UNK]']Greedy picks ab because it is longer than a. At start = 2 the encoder needs ##c, which is not in the vocabulary. It never goes back to try a followed by ##bc, which would have worked. The result is [UNK].
A second example shows a different cost. With the vocabulary {"a", "ab", "##bcd", "##c", "##d"}, the word abcd becomes ['ab', '##c', '##d'], which is 3 tokens. A segmentation of ['a', '##bcd'] has only 2.
Greedy matching does have advantages. It is simple and fast, and its output depends only on the vocabulary. The same word always gives the same split, so there is no randomness at encoding time. This is a difference from the unigram model in a later chapter, which can search for the best-scoring segmentation or sample from several.
Decoding and what is lost
Decoding reverses the convention. Tokens starting with ## are joined to the previous token. Any other token starts a new word, so a space goes in front of it.
def wordpiece_decode(tokens):
out = ""
for tok in tokens:
if tok.startswith("##"):
out += tok[2:]
else:
out += (" " if out else "") + tok
return out
print(wordpiece_decode(["play", "##ing", "un", "##aff", "##able"]))
# playing unaffableThis does not recover the original text exactly. The pipeline lowercased the input and may have stripped accents. It split punctuation into separate words, so hello, world decodes as hello , world. It also collapsed runs of whitespace. WordPiece with ## is lossy by design. The next chapters show how SentencePiece changes this by marking spaces inside the tokens.
Performance in practice
The loop above slices and hashes strings many times for each word. For a word of length n, one position can try up to n candidates, so a word costs O(n²) lookups in the worst case. This is fine for short words and for teaching. Production tokenisers store the vocabulary in a trie. They can then follow characters forward from start and remember the longest complete entry seen on the way. This gives the same output as the slicing loop, only faster. Some libraries use a linear-time variant of the same algorithm. If you replace the lookup structure, check that the new version gives identical output on a large word list before trusting it.
Common errors
- Forgetting the prefix on later pieces. Looking up
affinstead of##affatstart = 2fails, or worse, matches a different, word-initial entry. - Applying the prefix to the first piece. The first piece of a word never carries
##. Checkstart > 0before adding it. - Splitting on whitespace only. Encoding expects punctuation to have been separated already.
playing.as a single word will probably become[UNK]or split in odd places. - Casing mismatch. An uncased vocabulary contains only lowercase pieces. If you skip lowercasing,
Playingfails at the first character. - Treating
##as a token. Models see ids, not strings.##ingandingare different ids with different learned embeddings.
Exercise
Using the vocabulary {"un", "##a", "##ff", "##able", "##aff", "##ord", "##er", "##s"}, what does wordpiece_encode return for "unaffs" and for "unorder"? Explain each result.
Show answer
"unaffs" gives ['un', '##aff', '##s']. At start 0, "un" is the longest match. At start 2, the longest match is "##aff". At start 5, "##s" matches. "unorder" gives ['[UNK]']. After "un" matches, the encoder needs a piece for "order" at start 2. It tries "##order", "##orde", "##ord"; "##ord" is in the vocabulary, so it matches. Then at start 5 the remainder is "er", and "##er" is in the vocabulary. So the correct result is ['un', '##ord', '##er'], not [UNK]. Check the trace before answering: every candidate is tried longest first, and the first one found in the vocabulary is taken.
Exercise
Why does the vocabulary {"a", "ab", "##bc"} make wordpiece_encode return ['[UNK]'] for "abc", even though "a" followed by "##bc" would be a valid split?
Show answer
The encoder prefers the longest match at each position. At start 0 it takes "ab" because that is longer than "a". At start 2 it needs "##c", which is not in the vocabulary, and it has no way to go back to the earlier choice. The whole word then becomes [UNK]. Greedy longest match never backtracks.