Sub topic 4
Byte Pair Encoding: learning merges from a corpus
Prerequisites and the core idea
This chapter assumes Basic Python, dictionaries, tuples, loops, and frequency counting. You should also know that a token is an input unit given to a language model.
Byte Pair Encoding (BPE) is a subword tokenisation method. It starts with small units, usually characters or bytes, and repeatedly joins the most frequent adjacent pair. The ordered list of joins becomes the tokenizer's merge rules.
BPE balances two problems:
- Word tokens create many unknown words and a large vocabulary.
- Character tokens represent every word but produce long sequences.
A frequent word can become one token, while an unfamiliar word can usually be represented by smaller pieces.
Representing words
A simple word-level BPE trainer processes each word separately. It adds an end-of-word marker such as </w> so that low and the beginning of lower do not become indistinguishable.
For the corpus low low lower, the initial representation is:
| Word | Initial symbols | Frequency |
|---|---|---|
| low | `l o w </w>` | 2 |
| lower | `l o w e r </w>` | 1 |
Pair counts include word frequency. For example, (l, o) occurs three times, while (w, </w>) occurs twice. The first merge is therefore (l, o) -> lo.
After merging, the words become:
lo w </w>with frequency 2lo w e r </w>with frequency 1
The pair (lo, w) now occurs three times, so it becomes low. Later merges may create low</w>, lowe, or other pieces, depending on the corpus and tie-breaking rules.
A minimal BPE trainer
The following trainer stores each distinct word as a tuple and stores its frequency in a Counter. Each iteration counts pairs, selects the most frequent one, and applies it without overlapping replacements.
from collections import Counter
def get_pair_counts(words):
pairs = Counter()
for symbols, frequency in words.items():
for left, right in zip(symbols, symbols[1:]):
pairs[(left, right)] += frequency
return pairs
def merge_pair(words, pair):
merged_words = Counter()
for symbols, frequency in words.items():
output = []
index = 0
while index < len(symbols):
if (
index + 1 < len(symbols)
and (symbols[index], symbols[index + 1]) == pair
):
output.append(symbols[index] + symbols[index + 1])
index += 2
else:
output.append(symbols[index])
index += 1
merged_words[tuple(output)] += frequency
return merged_words
corpus = ("low " * 5 + "lower " * 2 + "newest " * 6 + "widest " * 3).split()
words = Counter(tuple(word) + ("</w>",) for word in corpus)
merges = []
for _ in range(10):
pair_counts = get_pair_counts(words)
if not pair_counts:
break
best_pair = max(pair_counts, key=pair_counts.get)
words = merge_pair(words, best_pair)
merges.append(best_pair)
print(merges)The trainer's stopping condition is deliberately simple: it performs ten merges. Production tokenizers usually stop at a target vocabulary size or when no useful merge remains.
Important implementation details
A merge applies to adjacent symbols inside each word. It does not combine symbols across whitespace boundaries. When a pair appears several times in one word, the implementation must choose a non-overlapping order. Most implementations scan from left to right.
Tie-breaking matters. Two pairs can have equal counts, and different tie rules can produce different vocabularies. Therefore, save the exact merge list with the vocabulary. The tokenizer used during inference must reproduce the training decisions.
BPE's vocabulary size is controlled by how many merges are learned. More merges create shorter sequences but require a larger embedding table. Fewer merges preserve smaller reusable pieces but increase sequence length.
Exercise
In the corpus low low lower, which pair is selected first, and why?
Show answer
(l, o) is selected first because it occurs three times: twice in low and once in lower. It has a higher count than (w, </w>), which occurs twice.