esc
  • WorkflowsPages
  • Case studiesPages
  • Machine Learning FoundationsLearn
  • AI EngineeringLearn
  • AI Guardrails & Red TeamingLearn
  • UI/UXLearn
  • Design SystemsLearn
  • Production System DesignLearn
  • AI papersPages
  • Interview KitPages
  • Book a callContact
Letโ€™s talk

Iโ€™ll build the agent for it.

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.

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

  1. 1The table hands each word and its count to the counting step.
  2. 2Each neighbouring pair gets the word's count added to its total.
  3. 3The pair with the highest total wins. Ties go to the smaller pair.
  4. 4The rewritten words and the winning pair go on to the saved rule.
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.
  • โ€œ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

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

1 / 6

What will they ask next?

  1. Q004How do tokenizers like BPE, WordPiece and SentencePiece work?11 min
  2. Q003What is a token, and why not whole words?11 min
  3. Q005Why do token counts differ across languages and models?10 min
  4. Q474Implement temperature, top-k and top-p over logits.11 min
  5. Q476Write a chunker with overlap.11 min

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.