How to Implement One BPE Merge Step
How to write one step of byte pair encoding: count the pairs, pick the top one, merge it, and avoid the bugs that trip candidates, for your AI interview.
In short
One BPE merge step counts every pair of side-by-side symbols, weighting each count by how often its word appears, picks the top pair with a fixed tie rule, and joins it everywhere, scanning left to right.
10 min readAdvancedOccasional ยท estimateFacts checked 27 November 2026
Say it out loud
Read it once, then say it without looking. Start with the short one; use the long one when they ask you to go deeper.
I'd split it into four moves. First I count every pair of neighbouring symbols, weighted by how often each word appears. Then I pick the top pair, with a fixed tie rule so every run agrees. Next I rewrite each word, joining that pair and skipping past both symbols. Last I save the rule. The traps are overlaps like 00000, pairs that cross word boundaries, and replacing inside a joined string.
A tokenizer learns its pieces from a big pile of text, and byte pair encoding is one way to do it. It starts with single characters, then finds the two symbols that sit side by side most often and glues them into one new symbol. That gluing is one merge step. Repeat it thousands of times and you have the vocabulary.
Writing one step is a small job with four parts. First, count every neighbouring pair, and weight each count by how often its word appears. Second, pick the top pair, with a fixed tie rule so every run agrees. Third, rewrite each word, joining that pair and moving past both symbols. Fourth, save the rule, because the tokenizer replays saved rules in order on new text.
Candidates usually trip on three things. Overlapping pairs in a run like 00000 need a scan from left to right that skips both symbols after a join. Pairs must not cross word boundaries, which is why text is split into words first. And joining symbols into one string and calling replace can match across symbol edges, so I keep the symbols as a list.
The idea is older than most chat models. Sennrich and colleagues brought it into neural machine translation, in a paper published at ACL 2016. Hugging Face's Transformers docs say that byte pair encoding is the most popular tokenization algorithm in Transformers, used by models like Llama and Gemma.
What is one BPE merge step, in plain words?
A tokenizer learns its pieces from a large pile of text. Byte pair encoding, called BPE for short, starts with single characters and then glues together the two symbols that sit side by side most often. One round of gluing is one merge step. Repeat it thousands of times and you have the tokenizer's vocabulary.
Picture a clerk sorting post. She sees the same two letters on half the envelopes and puts them in one tray. The next round she checks again, because the new tray may pair with another. A hospital's clinical-note search does the same work on drug names. Metformin and amlodipine turn up hundreds of times in the notes, so their common pieces should become single tokens, not odd fragments.
Key words
- Symbol
- One unit in the working text: a character at first, later a joined piece.
- Pair
- Two symbols that sit side by side inside a word.
- Word count
- How often a word appears in the training text. It multiplies the pairs inside it.
- Merge rule
- The saved note: join this pair into this new symbol. The tokenizer replays these notes in order.
- Tie rule
- The fixed rule that picks one pair when two pairs have the same count.
How does one merge step work?
One step has four moves. Each one is a small function, and together they fit on one screen.
- 1
Count the pairs
Walk each word's symbols and add the word's count to every neighbouring pair. A word seen 900 times adds 900 to each pair inside it.
- 2
Pick the winner
Take the pair with the highest total. Break ties with a fixed rule, such as the smaller pair, so every run picks the same one.
- 3
Merge in every word
Rewrite each word from left to right. Where the winning pair sits, join the two symbols into one and skip past both.
- 4
Save the rule
Store the pair and its new symbol. Later the tokenizer replays the saved rules in the same order on new text.
On a made-up hospital word table, the pair i and n wins with a total of 2,600. It sits inside four drug names: 900 for metformin, 620 for amlodipine, 700 for lisinopril and 380 for atorvastatin. Metoprolol and omeprazole have no i next to an n, so they add nothing.
One merge step, in order
Word table
each word and how often it appears
Count pairs
side-by-side symbols, weighted by count
Pick the top pair
highest count; smaller pair on a tie
Merge every word
scan left to right, skip both joined
New merge rule
saved, applied in the same order later
- 1The table hands each word and its count to the counting step.
- 2Each neighbouring pair gets the word's count added to its total.
- 3The pair with the highest total wins. Ties go to the smaller pair.
- 4The rewritten words and the winning pair go on to the saved rule.
โWe iteratively count all symbol pairs and replace each occurrence of the most frequent pairโ
Sennrich and colleagues, ACL 2016
โBPE starts with individual characters and iteratively merges the most frequent adjacent pair.โ
Hugging Face, Transformers docs (Tokenization algorithms)
Where do candidates go wrong?
Overlapping pairs
In a run like 00000 with the pair (0, 0), the scan joins the first two zeros, then the next two, and leaves the last zero alone. That gives 00, 00, 0. Scanning right to left gives 0, 00, 00, a different tokenizer, so pick one direction and keep it.
Ties
If two pairs share the top count, the winner must not depend on the order that a Python dictionary (a table of keys and values) or a set (a bag of unique items) happens to hold them. Pick the smaller pair, as the code does, and say so out loud.
Weights
Count pairs per word and multiply by the word's count. Skip the weight and a pair from a rare word counts as much as one that appears in thousands of notes.
Word boundaries
Split the text into words first, then count pairs inside each word. A pair that spans two words is not part of any real word. Hugging Face's guide describes the first step in its own words, shown below.
Joined strings
Joining the symbols into one string and calling replace (a function that swaps one piece of text for another) can match across symbol edges. Symbols 'ai' and 'n' make 'ain', and replace('in') finds an 'in' that is not a pair at all. Keep the symbols as a list.
โA pre-tokenizer splits text on whitespace or other rules, producing a set of unique words and their frequencies.โ
Hugging Face, Transformers docs (Tokenization algorithms)
How would you write it in Python?
The script below uses made-up counts from the hospital notes. It runs one step, prints the winning pair, and checks the overlap case from the list above.
# One BPE merge step on made-up drug-name counts from a hospital's clinical notes.
from collections import Counter
words = Counter({"metformin": 900, "metoprolol": 450, "amlodipine": 620,
"atorvastatin": 380, "lisinopril": 700, "omeprazole": 310})
splits = {w: list(w) for w in words} # every word starts as single characters
def count_pairs(splits):
counts = Counter()
for w, parts in splits.items():
for pair in zip(parts, parts[1:]):
counts[pair] += words[w] # weight by how often the word appears
return counts
def merge(parts, pair):
out, i = [], 0
while i < len(parts):
if i + 1 < len(parts) and (parts[i], parts[i + 1]) == pair:
out.append(parts[i] + parts[i + 1])
i += 2 # skip both symbols so overlapping pairs stay left to right
else:
out.append(parts[i])
i += 1
return out
counts = count_pairs(splits)
# Highest count wins; on a tie the smaller pair wins, so every run agrees.
best = min(counts, key=lambda p: (-counts[p], p))
print("Best pair:", best, "seen", counts[best], "times")
splits = {w: merge(parts, best) for w, parts in splits.items()}
for w in ["metformin", "amlodipine", "lisinopril"]:
print(w, splits[w])
print("Overlap check:", merge(list("aaa"), ("a", "a")))Output
Best pair: ('i', 'n') seen 2600 times
metformin ['m', 'e', 't', 'f', 'o', 'r', 'm', 'in']
amlodipine ['a', 'm', 'l', 'o', 'd', 'i', 'p', 'in', 'e']
lisinopril ['l', 'i', 's', 'in', 'o', 'p', 'r', 'i', 'l']
Overlap check: ['aa', 'a']Tip
In the interview, say what the code leaves out. Many trainers keep a table of pair counts and update only the words that changed, and they repeat this step until the vocabulary reaches its target size.
What does the interviewer want to hear?
A strong answer covers
- The four moves: count, pick, merge, save.
- Pair counts weighted by word frequency, not raw pair counts.
- A fixed tie rule, so the same corpus always gives the same merge.
- A left-to-right scan that skips both symbols, with the overlap case named.
- Pairs never cross word boundaries.
- Saved rules replayed in order on new text.
Common traps
Trap"Just call replace."
BetterReplace works on strings and can match across symbol edges. Keep the symbols as a list and merge by position.
Trap"Pick the first pair."
BetterFirst in dictionary order is not a rule. Use the count, then a fixed tie rule such as the smaller pair.
Trap"Count the whole text."
BetterCount pairs inside each word and multiply by the word's count, or rare words skew the choice.
Can you spot the bug?
Spot the bug
Which counting loop is right when each word has a count?
Quick check
A hospital's lab-result log has a run of five zeros, 00000, and the best pair is (0, 0). What does one merge step give, scanning left to right?
Can you answer these from memory?
Flash cards ยท tap a card to flip it
What will they ask next?
Learn it in depth
Last updated on 27 November 2026
Building a tokenizer or a search tool on your own text?
Venkat designs and builds AI products and agents (the UI and the system behind it), so book a short call and say what you need. No promises, no numbers.