---
title: Byte-pair-encoding merge learning
url: https://gurkanozkan.ai/learn/coding/mle-byte-pair-encoding-merge-learning-22/
markdown: https://gurkanozkan.ai/learn/coding/mle-byte-pair-encoding-merge-learning-22.md
kind: coding
difficulty: Hard
topics:
  - NLP
  - Tokenisation
  - Hash map
json: https://gurkanozkan.ai/api/learn/coding/mle-byte-pair-encoding-merge-learning-22.json
robots: noindex
---

# Byte-pair-encoding merge learning

- Words (with frequencies) start as tuples of single characters. - At each step, count adjacent symbol pairs across all words, weighted by word frequency. - Choose the most frequent pair; ties go to the lexicographically smallest pair (compare as tuples of strings). - Merge every non-overlapping occurrence left to right in every word. - Repeat `num_merges` times, stopping early if no pairs remain. Return the list of merged pairs.

## Signature

```python
def bpe_merges(word_freqs: dict[str, int], num_merges: int) -> list[tuple[str, str]]: ...
```

## Examples

Each call and the value it should give.

```python
>>> bpe_merges({'aa': 2, 'ab': 1}, 1) == [('a', 'a')]
True

>>> bpe_merges({'low': 5, 'lower': 2, 'newest': 6, 'widest': 3}, 3) == [('e', 's'), ('es', 't'), ('l', 'o')]
True
```

## Hints

1. Count adjacent symbol pairs across all words, weighted by word frequency.
2. Pick the most frequent pair (ties -> lexicographically smallest); merge non-overlapping occurrences left to right.
3. Repeat num_merges times, stop early if no pairs remain, return the list of merged pairs.

## Reference solution

```python
from collections import Counter

def bpe_merges(word_freqs, num_merges):
    words = {tuple(w): f for w, f in word_freqs.items()}
    merges = []
    for _ in range(num_merges):
        counts = Counter()
        for sym, f in words.items():
            for a, b in zip(sym, sym[1:]):
                counts[(a, b)] += f
        if not counts:
            break
        top = max(counts.values())
        pair = min(p for p, c in counts.items() if c == top)
        merges.append(pair)
        new = {}
        for sym, f in words.items():
            out = []; i = 0
            while i < len(sym):
                if i + 1 < len(sym) and (sym[i], sym[i + 1]) == pair:
                    out.append(sym[i] + sym[i + 1]); i += 2
                else:
                    out.append(sym[i]); i += 1
            new[tuple(out)] = new.get(tuple(out), 0) + f
        words = new
    return merges
```

## What a strong solution covers

- Correct weighted pair counting.
- Deterministic tie-break.
- Left-to-right non-overlapping merge.
- Complexity discussion and incremental pair-count updates.
- Explains how merges are applied at encode time.

## Common mistakes

- merging overlapping occurrences (`aaa`)
- recounting pairs incorrectly after a merge.
---

*Study material compiled with AI: drafted by a local model (Inkling 2 Mini) from public sources, then checked against those sources by independent AI reviewers (Claude) in November 2026. Not reviewed line by line by a person.*
