# 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.

AI and LLM interview question Q477, Coding and practical. Advanced, occasional (our estimate). From Venkat R. Murty's free Interview Kit: https://designervenkat.online/interview/ai/implement-one-bpe-merge-step

## Say it in 30 seconds

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.

## Say it in 2 minutes

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.

- **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.

*Diagram, One merge step, in order: The word table feeds four moves: count, pick, merge, save. The pick and the saved rule decide what the tokenizer learns, so the tie rule and the saved order have to be exact.*
1. The table hands each word and its count to the counting step.
2. Each neighbouring pair gets the word's count added to its total.
3. The pair with the highest total wins. Ties go to the smaller pair.
4. The 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.

```python
# 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:

```text
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." Better: Replace works on strings and can match across symbol edges. Keep the symbols as a list and merge by position.
- Trap: "Pick the first pair." Better: First 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." Better: Count 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?

A. for pair in zip(parts, parts[1:]): counts[pair] += 1
B. for pair in zip(parts, parts[1:]): counts[pair] += words[w]
C. for pair in zip(all_symbols, all_symbols[1:]): counts[pair] += 1
D. for pair in zip(parts, parts[1:]): counts[pair] = words[w]

**Answer:** B. Option 0 ignores how often each word appears. Option 2 joins symbols from different words, so it counts pairs across a word boundary. Option 3 overwrites the count instead of adding to it, so only the last word counts. Option 1 adds the word's count to each pair inside that word.

**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?

A. 0, 00, 00
B. 00, 00, 0
C. 00000
D. 00, 000

**Answer:** B. The scan joins the first two zeros, then the next two, and the last zero stands alone. Scanning right to left would give 0, 00, 00, a different tokenizer.

## Can you answer these from memory?

**Flash cards**

- **What are the four moves of one merge step?** Count the pairs, pick the top pair, merge it in every word, save the rule.
- **Why weight pair counts by word count?** A pair inside a word seen 900 times matters 900 times more than one seen once.
- **What breaks a tie?** A fixed rule, such as the smaller pair, so every run picks the same one.
- **Why scan with a skip?** So overlapping pairs in a run like 00000 merge into 00, 00, 0 without double joins.
- **Can a pair cross a word boundary?** No. Split the text into words first, then count pairs inside each word.
- **Why keep symbols as a list, not a string?** Replace on a joined string can match across symbol edges and join the wrong pieces.

## Likely follow-up questions

- Q004 How do tokenizers like BPE, WordPiece and SentencePiece work? https://designervenkat.online/interview/ai/how-do-tokenizers-work-bpe-wordpiece-sentencepiece
- Q003 What is a token, and why not whole words? https://designervenkat.online/interview/ai/what-is-a-token
- Q005 Why do token counts differ across languages and models? https://designervenkat.online/interview/ai/why-do-token-counts-differ-across-languages-and-models
- Q474 Implement temperature, top-k and top-p over logits. https://designervenkat.online/interview/ai/implement-temperature-top-k-and-top-p-over-logits
- Q476 Write a chunker with overlap. https://designervenkat.online/interview/ai/write-a-chunker-with-overlap

## Learn it in depth

- [Tokenization](https://designervenkat.online/learn/machine-learning/tokenization)
