Byte-pair-encoding merge learning
Problem
- 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_mergestimes, stopping early if no pairs remain. Return the list of merged pairs.
Signature
def bpe_merges(word_freqs: dict[str, int], num_merges: int) -> list[tuple[str, str]]: ...Examples
The visible tests, as an interactive Python session would show them: each call and the value it should give.
>>> 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')]
TrueHints
Count adjacent symbol pairs across all words, weighted by word frequency.
Pick the most frequent pair (ties -> lexicographically smallest); merge non-overlapping occurrences left to right.
Repeat num_merges times, stop early if no pairs remain, return the list of merged pairs.
Reference solution
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 mergesWhat 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.