Sub topic 8
WordPiece Encoding with Greedy Longest Match and `##` Prefixes
WordPiece encoding converts a pre-tokenised word into vocabulary pieces. It assumes you know basic Python, dictionaries, loops, and token frequency counts. It also assumes that normalisation and pre-tokenisation have already happened. For example, a tokenizer may lowercase text and split punctuation before WordPiece encoding begins.
The WordPiece vocabulary
A WordPiece vocabulary contains complete words and subword pieces. A piece beginning with ## can only appear after another piece in the same word.
For example:
| Vocabulary entry | Meaning |
|---|---|
| `un` | Beginning of a word |
| `##aff` | Continuation of a word |
| `##able` | Continuation of a word |
| `play` | Complete word or word beginning |
| `##ing` | Continuation of a word |
The word unaffable can therefore become:
un ##aff ##ableThe ## text is a continuation marker. It is part of the tokenizer's vocabulary representation, not usually part of the decoded output.
Greedy longest-match encoding
WordPiece encoding scans from left to right. At each position, it chooses the longest vocabulary entry that matches the remaining characters.
Consider the vocabulary:
un, ##aff, ##able, ##a, ##bleFor unaffable, the encoder works as follows:
- At position 0, it tries the longest substring,
unaffable. - It shortens the candidate until it finds
un. - At position 2, it tries continuation candidates such as
##affable,##aff, and##a. - It selects
##aff, because it is the longest matching continuation. - At position 5, it selects
##able.
The algorithm is greedy because it selects the longest valid piece immediately. It does not search all possible segmentations for the best overall result.
If no vocabulary entry matches at a position, the usual WordPiece behavior returns one unknown token, such as [UNK], for the entire word. It does not keep the pieces that were found before the failure.
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
vocab = {"un", "##aff", "##able"}
print(wordpiece_encode("unaffable", vocab))
print(wordpiece_encode("unaffordable", vocab))The output is:
['un', '##aff', '##able']
['[UNK]']The inner loop starts with the longest possible candidate and decreases its length one character at a time. The prefix is added only when start > 0, so the first piece must match an entry without ##.
Common errors
A frequent error is allowing a continuation piece at the beginning of a word. ##ing should not encode ing as the first piece unless the vocabulary also contains ing.
Another error is choosing the shortest matching piece. With ##a, ##aff, and ##affable available, the encoder should choose ##affable when it matches the remaining text.
The vocabulary and encoder must use the same normalisation rules. If training lowercased words but inference preserves uppercase letters, words such as Unaffable may become [UNK] even when their lowercase form is fully supported.
Exercise
Given the vocabulary {"play", "##ful", "##ly", "##f", "##ully"}, what does WordPiece encoding produce for "playfully"?
Show answer
It produces ["play", "##fully"] if "##fully" is in the vocabulary; otherwise it selects ["play", "##ful", "##ly"].