Sub topic 5
Encoding New Text with Learned BPE Merges
Training a Byte Pair Encoding (BPE) tokeniser produces an ordered list of merges. Encoding is the second half of the job: it applies that list to text the tokeniser has never seen. This chapter assumes you have read the previous chapter on learning merges, and that you are comfortable with Python tuples, dictionaries, and loops. It also assumes you know that text is pre-split into words before subword splitting, as covered in the pre-tokenisation chapter.
What training leaves behind
Training produces two artefacts: a base alphabet (the characters seen in the corpus) and an ordered merge list. Each merge is a pair of symbols that was fused into a new symbol. For the toy corpus in the previous chapter ("low", "lower", "newest", "widest" with counts 5, 2, 6, 3), ten rounds of the trainer produce this list, in this order:
("e", "s")("es", "t")("est", "</w>")("l", "o")("lo", "w")("n", "e")("ne", "w")("new", "est</w>")("low", "</w>")("w", "i")
The position in the list is the merge's rank. Rank 0 was the most frequent pair in the training data at the time it was chosen. The list is the tokeniser, so you must store it in order. A bare set of vocabulary strings loses the information encoding needs.
The encoding rule
To encode a word, replay the training process on that single word:
- Split the word into characters and append the end-of-word marker
</w>. - List every adjacent pair of symbols.
- Find the pairs that appear in the merge list. If there are none, stop.
- Merge the pair with the lowest rank. If that pair occurs more than once, merge the leftmost occurrence.
- Go back to step 2.
The frequencies from the corpus are not used at encoding time. Only the ranks matter.
A working encoder
The code below implements the rule directly. It uses the ten merges listed above, so you can check the output by hand.
MERGES = [
("e", "s"), ("es", "t"), ("est", "</w>"),
("l", "o"), ("lo", "w"),
("n", "e"), ("ne", "w"),
("new", "est</w>"), ("low", "</w>"),
("w", "i"),
]
def bpe_encode_word(word, merges):
ranks = {pair: i for i, pair in enumerate(merges)}
symbols = list(word) + ["</w>"]
while len(symbols) > 1:
candidates = [
(ranks[pair], i)
for i, pair in enumerate(zip(symbols, symbols[1:]))
if pair in ranks
]
if not candidates:
break
_, i = min(candidates) # lowest rank, then leftmost position
symbols[i:i + 2] = [symbols[i] + symbols[i + 1]]
return symbols
def bpe_encode(text, merges):
tokens = []
for word in text.split():
tokens.extend(bpe_encode_word(word, merges))
return tokens
def bpe_decode(tokens):
return "".join(tokens).replace("</w>", " ").strip()
for w in ["lowest", "newer", "wider", "zest", "quiz"]:
print(w, bpe_encode_word(w, MERGES))
tokens = bpe_encode("lowest newer", MERGES)
print(tokens)
print(bpe_decode(tokens))The output is:
lowest ['low', 'est</w>']
newer ['new', 'e', 'r', '</w>']
wider ['wi', 'd', 'e', 'r', '</w>']
zest ['z', 'est</w>']
quiz ['q', 'u', 'i', 'z', '</w>']
['low', 'est</w>', 'new', 'e', 'r', '</w>']
lowest newerTwo of these words never appeared in training. "lowest" is assembled from low, which came from "low" and "lower", and est</w>, which came from "newest" and "widest". Neither word was in the corpus, yet the tokeniser represents each with two tokens. This is how BPE handles unseen words: it falls back to pieces that were common elsewhere.
Tracing "lowest" step by step
Each row shows the symbols before the merge and the pair chosen.
| Step | Symbols | Pairs in merge list (rank) | Merge applied |
|---|---|---|---|
| 0 | l o w e s t `</w>` | (l,o) 3; (e,s) 0 | (e,s) |
| 1 | l o w es t `</w>` | (l,o) 3; (es,t) 1 | (es,t) |
| 2 | l o w est `</w>` | (l,o) 3; (est,`</w>`) 2 | (est,`</w>`) |
| 3 | l o w est`</w>` | (l,o) 3 | (l,o) |
| 4 | lo w est`</w>` | (lo,w) 4 | (lo,w) |
| 5 | low est`</w>` | none | stop |
The merges at ranks 0 to 2 fire before the merges at ranks 3 and 4, even though the "l o" pair sits further left. Rank decides the order, not position. Position only breaks ties between occurrences of the same pair.
Why rank order matters
A tempting shortcut is to treat the vocabulary as a set of strings and split each word with greedy longest match, as WordPiece does. That gives different answers from BPE. Suppose the merges are [("b","c"), ("a","b")], so the vocabulary contains a, b, c, ab, bc. Encoding "abc" with BPE merges b c first (rank 0), which gives a, bc. A left-to-right longest match would take ab first and give ab, c.
The BPE result is the one consistent with training. During training, "b c" was more frequent than "a b", so the tokeniser was built to prefer bc. If you reimplement a tokeniser and ignore the ranks, your token ids will differ from the reference implementation, and a model trained with the original tokeniser will see inputs it was not trained on.
Edge cases
Characters never seen in training
My encoder emits whatever characters it is given. A character that was not in the training corpus, such as an emoji or a rare letter, has no entry in the vocabulary. A real character-level BPE tokeniser must map it to an unknown token, which brings back the out-of-vocabulary problem. Byte-level BPE, covered in the next chapter, avoids this by starting from the 256 possible byte values instead of from characters.
Repeated pairs
If a word contains the same pair several times, such as a a a a, each pass merges only the leftmost one. After the first merge the word is aa a a. The pair (a, a) is still the lowest-rank pair, so the loop merges it again and reaches aa aa. The result matches what the trainer's left-to-right, non-overlapping merge produces.
The trainer and the encoder must treat overlapping pairs in the same way. For a a a, both give aa a, because the leftmost pair merges first.
The end-of-word marker
The </w> marker lets the tokeniser tell "est" inside a word from "est" at the end of a word. Without it, the tokens for "lowest" and "estate" could share a token with different meanings in different positions. Other implementations use a different convention. GPT-2 style tokenisers attach the preceding space to the start of the next word as a prefix, written Ġ, and have no end marker. Decoding then needs only concatenation. Whichever convention you use, the encoder must follow the one used in training.
Cost
The loop above rescans the whole word after every merge, so a word of length n costs roughly O(n²) pair checks. This is fine for words, which are short, but it would be slow if applied to whole sentences. Real tokenisers handle this in two ways:
- Pre-tokenisation splits text into words first, so n stays small.
- A cache maps each distinct word to its token list. Natural text repeats words constantly, so most lookups skip the loop entirely.
Production code may also use a priority queue keyed on rank. Encoding is deterministic. The same text always gives the same tokens, which makes caching safe.
Pre-tokenisation changes the result
Because bpe_encode calls text.split(), merges can never cross a space. A pair like ("t", "h") can only fuse within a word. If you change the pre-tokeniser at inference time, for example by splitting on punctuation when training did not, the same text will encode differently. This is a train/inference mismatch of the kind a later chapter covers.
Checking your encoder
Two checks catch most mistakes:
- Round trip.
bpe_decode(bpe_encode(text, MERGES))should equal the whitespace-normalised input. Characters outside the base alphabet are the usual cause of failures. - Training words. Encode the training words and compare with the final symbols from the trainer. "newest" must give
['newest</w>']and "low" must give['low</w>']. If not, your pair order or tie-breaking differs from training.
Exercise
Using the ten merges in this chapter, encode the word "lower" by hand. List the symbols after each merge and give the final tokens.
Show answer
Start: l o w e r </w>. Applicable pairs: (l,o) rank 3. Others such as (w,e), (e,r), (r,</w>) are not in the list. Merge (l,o): lo w e r </w>. Next (lo,w) rank 4: low e r </w>. Now (low,e), (e,r), (r,</w>) are not in the merge list, so stop. Final tokens: ['low', 'e', 'r', '</w>']. The rank-8 merge (low,</w>) never applies because "low" is followed by "e", not by the end marker.
Exercise
Why does encoding "abc" give ['a', 'bc'] when the merges are [("b","c"), ("a","b")], and what would a left-to-right longest-match splitter produce with the same vocabulary?
Show answer
BPE always merges the lowest-rank pair present. ("b","c") has rank 0, so it merges first and gives a, bc. The pair ("a","b") no longer exists, so it is never merged. A longest-match splitter scans from the left, finds "ab" in the vocabulary, and produces ['ab', 'c']. The two methods disagree because BPE follows the order learned in training, while longest match follows position.
Exercise
Why does a production BPE tokeniser keep a cache from words to token lists?
Show answer
Encoding a word runs the merge loop, which costs roughly quadratic time in the word's length. Natural text repeats the same words often, and encoding is deterministic, so storing the result for each distinct word lets later occurrences skip the loop.