Sub topic 2
Encoding new text with learned BPE merges
This chapter assumes you know Python basics, what a token is, and how BPE merges are learned from a corpus. Here, you apply a learned merge list to new text, then compare how byte-level BPE, WordPiece, and the unigram model build and apply their vocabularies.
Applying BPE merges to new words
A BPE tokeniser stores an ordered list of merges. To encode a word, split it into characters, append an end-of-word marker, then apply each merge in the order it was learned.
def bpe_encode(word, merges):
symbols = list(word) + ["</w>"]
for a, b in merges:
out = []
i = 0
while i < len(symbols):
if i < len(symbols) - 1 and symbols[i] == a and symbols[i + 1] == b:
out.append(a + b)
i += 2
else:
out.append(symbols[i])
i += 1
symbols = out
return symbols
merges = [("l", "o"), ("lo", "w"), ("e", "s")]
print(bpe_encode("lower", merges)) # ['low', 'e', 'r', '</w>']A character that never appeared in training has no merge and no vocabulary entry, so character-level BPE fails on it.
Byte-level BPE
Byte-level BPE starts from the 256 possible byte values instead of characters. Every string is a sequence of bytes, so every input has a valid encoding.
> Byte-level BPE never produces an unknown token. Rare characters split into several byte tokens instead.
WordPiece: choosing merges by likelihood
WordPiece scores a candidate merge of symbols a and b by count(ab) / (count(a) × count(b)). It prefers pairs that occur together more often than their parts occur alone, not simply the most frequent pair.
WordPiece encoding with ## prefixes
WordPiece encodes greedily. At each position it takes the longest vocabulary entry that matches. Pieces after the first carry a ## prefix, so unaffable can become un, ##aff, ##able. If any position has no match, the whole word becomes [UNK].
The unigram language model tokeniser
The unigram model starts with a large candidate vocabulary, each piece with a probability. It picks the segmentation with the highest total probability using Viterbi search. Training removes the pieces whose loss hurts the likelihood least. Because a word can have several segmentations, the model can sample among them during training.
Exercise
Using merges [("l", "o"), ("lo", "w")], what does bpe_encode("low", merges) return?
Show answer
['low', '</w>']. The first merge joins l and o into lo. The second joins lo and w into low. The end marker stays separate.