Lesson 2 of 5 · Tokens
Byte-Pair Encoding
How byte-pair encoding builds a tokenizer: count pairs, merge the most frequent, repeat. Train a BPE tokenizer in Python and see why it starts from bytes.
- 6 min read
- Intermediate
- Reviewed
- How byte-pair encoding learns a vocabulary from text
- How a trained tokenizer encodes words it has never seen
- Why modern tokenizers start from bytes rather than letters
- How vocabulary size affects a model
The idea
Frequent combinations get merged early and become single tokens. Rare combinations never get merged, so rare words stay split into smaller, familiar pieces. Nobody decides by hand what the tokens are: they come from the statistics of the text.
Training and encoding in Python
Training produces an ordered list of merges. Encoding a new word means starting from its characters and applying those merges in the same order.
# Training text: each word with how often it appears
word_counts = {"low": 5, "lower": 2, "newest": 6, "widest": 3, "slow": 2}
def count_pairs(splits):
pairs = {}
for word in word_counts:
parts = splits[word]
for i in range(len(parts) - 1):
pair = (parts[i], parts[i + 1])
pairs[pair] = pairs.get(pair, 0) + word_counts[word]
return pairs
def merge_pair(parts, pair):
merged = []
i = 0
while i < len(parts):
if i < len(parts) - 1 and parts[i] == pair[0] and parts[i + 1] == pair[1]:
merged.append(parts[i] + parts[i + 1])
i += 2
else:
merged.append(parts[i])
i += 1
return merged
# ---- Training: learn a list of merges ----
splits = {}
for word in word_counts:
splits[word] = list(word)
merges = []
for step in range(6):
pairs = count_pairs(splits)
best = max(pairs, key=pairs.get)
merges.append(best)
for word in splits:
splits[word] = merge_pair(splits[word], best)
print("Learned merges, in order:")
for a, b in merges:
print(f" {a} + {b} -> {a + b}")
# ---- Encoding: apply the merges, in the same order, to any word ----
def encode(word):
parts = list(word)
for pair in merges:
parts = merge_pair(parts, pair)
return parts
for word in ["lowest", "newer", "slowest", "wow"]:
print(f"{word:8} -> {encode(word)}")Look at the results:
lowestwas never in the training text, yet it encodes neatly aslow+est, two pieces the tokenizer learned from other words.slowestbecomess+low+est.wowgets no merges at all and stays as three single characters: the fallback for anything unfamiliar.
Starting from bytes
If the starting units were letters, the tokenizer would need an entry for every character in every writing system, and would fail on anything it had never seen. Modern tokenizers start from bytes instead.
Computers store text as bytes using UTF-8, where one character takes between 1 and 4 bytes:
for text in ["a", "é", "你", "🍕"]:
data = list(text.encode("utf-8"))
print(f"{text!r}: {len(data)} byte(s) {data}")With byte-level BPE, there is never an "unknown" token. Text the tokenizer has seen a lot is compressed into long tokens; text it rarely saw falls back to short tokens, in the worst case single bytes.
Vocabulary size
The number of merges decides the vocabulary size, and it is a trade-off:
| Smaller vocabulary | Larger vocabulary |
|---|---|
| Texts become more tokens (slower, more expensive, less fits in context) | Texts become fewer tokens |
| Smaller embedding and output layers | Bigger embedding and output layers, more parameters |
| Each token is seen often in training | Rare tokens are seen less often, so learned less well |
Vocabularies have grown over time, from about 50,000 tokens in GPT-2 (2019) to around 100,000 to 200,000 in recent models, largely to handle more languages and code efficiently.
Common mistakes
Encode a word with a trained BPE tokenizer: apply its merges, in order.
def merge_pair(parts, pair):
merged = []
i = 0
while i < len(parts):
if i < len(parts) - 1 and parts[i] == pair[0] and parts[i + 1] == pair[1]:
merged.append(parts[i] + parts[i + 1])
i += 2
else:
merged.append(parts[i])
i += 1
return merged
merges = [("l", "o"), ("lo", "w"), ("e", "r")]
word = "lower"
# Start from the single characters of word, apply every merge in order,
# and print the final list of tokens.
In byte-pair encoding, which pair is merged at each training step?
Summary
- BPE starts from small units and repeatedly merges the most frequent neighbouring pair.
- Training produces an ordered list of merges; encoding replays them on new text.
- Unseen words are built from learned pieces; unfamiliar text falls back to small units.
- Byte-level BPE starts from the 256 byte values, so it can encode any text, with no unknown tokens.
- Vocabulary size trades sequence length against model size.
Next: special tokens, the hidden structure markers.
Finished reading? Tick it off to track your progress.