Sub topic 4
Byte Pair Encoding: learning merges from a corpus
This chapter covers the training half of Byte Pair Encoding (BPE). Training turns a pile of text into an ordered list of merge rules. The next chapter applies those rules to new text.
You should already know basic Python (dictionaries, tuples, loops), what a token is as the input unit of a language model, and how to count frequencies. Earlier chapters covered why subwords exist and how text is split into words before subword splitting. Here we assume the corpus has already been split into words.
The core idea
BPE starts with the smallest symbols available, which are single characters here. It then repeatedly finds the most frequent pair of adjacent symbols and fuses that pair into one new symbol. Each fusion is a merge. The model is the ordered list of merges.
Frequent character sequences such as est or low become single symbols after a few merges. Rare words stay split into smaller pieces. No word is ever out of vocabulary, because the character symbols are always available as a fallback.
The size of the final vocabulary is:
vocabulary size = number of base symbols + number of mergesSo the number of merges is the setting you tune. Training stops when you reach a target vocabulary size or when no pair is left to merge.
The training loop
- Count how often each distinct word appears in the corpus.
- Write each word as a sequence of symbols: its characters plus an end-of-word marker.
- Count every adjacent symbol pair, weighted by the frequency of the word it appears in.
- Pick the most frequent pair and record it as the next merge.
- Rewrite every word, replacing each occurrence of that pair with the fused symbol.
- Go back to step 3 until the stopping condition holds.
Why the end-of-word marker matters
The code below appends </w> to every word. The marker lets BPE tell a suffix from the same letters in the middle of a word. The symbol est</w> (as in newest) is different from est inside a word like estimate. It also lets the encoder rebuild word boundaries from the pieces.
Pairs are counted inside words only. The marker is the last symbol of each word, so a pair never spans two words. Whitespace splitting happens before BPE, which is the pre-tokenisation step from the previous chapter.
A runnable trainer
This trainer uses a small toy corpus: low five times, lower twice, newest six times and widest three times.
from collections import Counter
def get_pair_counts(words):
pairs = Counter()
for symbols, freq in words.items():
for a, b in zip(symbols, symbols[1:]):
pairs[(a, b)] += freq
return pairs
def merge_pair(words, 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(symbols[i] + symbols[i + 1])
i += 2
else:
out.append(symbols[i])
i += 1
merged[tuple(out)] += freq
return merged
corpus = ("low " * 5 + "lower " * 2 + "newest " * 6 + "widest " * 3).split()
words = Counter(tuple(w) + ("</w>",) for w in corpus)
merges = []
for _ in range(10):
pairs = get_pair_counts(words)
if not pairs:
break
best = max(pairs, key=pairs.get)
words = merge_pair(words, best)
merges.append(best)
print(merges)Each key in words is a tuple of symbols and each value is how often that word occurred. Counting distinct words once and multiplying by frequency is what keeps training affordable. Without it you would rescan every token of the corpus on every merge.
The merge_pair function scans left to right and consumes two symbols whenever it finds the pair. This matters for overlapping cases such as a a a with the pair (a, a). The scan merges the first two and leaves the third alone.
Tracing the first merges by hand
Start with these words. Each is shown with its frequency.
| Word | Symbols | Frequency |
|---|---|---|
| low | l o w </w> | 5 |
| lower | l o w e r </w> | 2 |
| newest | n e w e s t </w> | 6 |
| widest | w i d e s t </w> | 3 |
The pair (e, s) appears in newest (6) and widest (3), so its count is 9. The pairs (s, t) and (t, </w>) also total 9. Three pairs tie, and the next section explains how the code breaks the tie.
Here is the full run of 10 merges. The code prints exactly this list.
| Merge | Pair | New symbol | Count at that step |
|---|---|---|---|
| 1 | e + s | es | 9 |
| 2 | es + t | est | 9 |
| 3 | est + </w> | est</w> | 9 |
| 4 | l + o | lo | 7 |
| 5 | lo + w | low | 7 |
| 6 | n + e | ne | 6 |
| 7 | ne + w | new | 6 |
| 8 | new + est</w> | newest</w> | 6 |
| 9 | low + </w> | low</w> | 5 |
| 10 | w + i | wi | 3 |
Read the table from the top and you can watch the corpus compress. After merge 3, every newest and widest ends in the single symbol est</w>. After merge 8, newest is one symbol. After merge 9, low is one symbol, while lower is low e r </w>. The vocabulary now holds 11 base symbols (10 letters plus </w>) and 10 merges, so 21 entries.
Ties and determinism
When several pairs share the top count, the result depends on the tie-break. In the code, max(pairs, key=pairs.get) returns the first maximal pair in the counter's insertion order. That is why merge 1 is (e, s) and not (t, </w>). Python dictionaries keep insertion order, so the run is repeatable.
Production trainers use an explicit rule, often the lexicographically smallest pair, or the pair that appeared first. If two trainers break ties differently, they produce different merge lists from the same corpus. Both lists are valid, but the encodings differ. Record the tie-break rule with the model.
Edge cases
- Single characters never disappear. Base symbols stay in the vocabulary even if a merge absorbs every occurrence. Keep them so unseen words can still be spelled.
- Rare characters. If the training corpus has no
ßor no emoji, those characters are not base symbols. A character-based BPE then needs an unknown token for them. Byte-level BPE avoids this, and a later chapter covers it. - Running out of pairs. If every word has become a single symbol,
get_pair_countsreturns an empty counter. The code'sif not pairs: breakhandles this, so asking for more merges than the corpus supports does not crash. - Count of 1. Late merges often join pairs seen only once. They memorise the training data and add vocabulary entries that rarely help. Many trainers set a minimum pair frequency.
- Frequency weighting. Counting by word frequency means common words dominate the early merges. A rare word like
wideststill getswionly at the end. - Cost. This version recounts every pair after every merge. For a real corpus this is slow. Practical implementations keep pair counts and an index of where each pair occurs, updating only the words that changed.
What training produces
Training outputs two things. The first is the base symbol set. The second is the ordered merge list. The vocabulary is derived from those two. Nothing else is stored, such as weights or probabilities. This is a difference from the unigram model, which keeps a probability for each piece.
The merge list is also the whole recipe for encoding. To tokenise a new word, split it into base symbols and apply the merges in the order they were learned. The next chapter walks through that process.
Common mistakes
- Forgetting the end-of-word marker. Without it,
lowinsidelowerand the standalone wordlowlook identical. - Counting pairs per distinct word, not per occurrence. Using the word's frequency as a weight (as
get_pair_countsdoes) is essential. Without the weight,widestwould count as much asnewest. - Merging across word boundaries. If you run BPE on a whole sentence as one sequence, pairs like
(t, w)can form across a space. Split words first. - Choosing the number of merges by guess. The merge count sets the vocabulary size, which affects sequence length and model size. A later chapter treats this trade-off.
Exercise
After merges 1 to 3 on the toy corpus, how is the word widest written as symbols? What is the count of the pair (w, i) at that point, and why does it not get merged until step 10?
Show answer
After merges 1 to 3, widest is w i d est</w>. The pair (w, i) has count 3, because widest occurs 3 times and no other word contains wi. Pairs from newest, low and lower have higher counts (9, 7, 6 and 5), so they are merged first. (w, i) wins only when everything with a higher count has been merged. Even then it ties with (i, d) and (d, est</w>) at 3, and the code picks (w, i) because it appears first in insertion order.
Exercise
The vocabulary after 10 merges has 21 entries. If the corpus also contained the word wide (frequency 1), how many base symbols would there be, and would the answer change?
Show answer
The base symbols would stay at 11. wide uses only w, i, d, e and the end-of-word marker, which are all already present. The base symbol set depends only on which characters occur in the corpus. The new word would add an extra w i d e </w> entry, which changes pair counts (it adds 1 to (w, i), (i, d) and (d, e)), but it adds no new base symbols.