Do one merge step of a BPE tokenizer

Byte Pair Encoding (BPE) builds a tokenizer by repeatedly finding the most common pair of neighbouring symbols and gluing it into one new symbol. Run enough merges and frequent chunks like "ing" or "the" become single tokens.

Write bpe_merge_step(words) where words is a list of lists of symbols, for example [["l","o","w"], ["l","o","w","e","r"]].

1. Count every adjacent pair across all words.
2. Pick the most frequent pair. On a tie, pick the pair that comes first in alphabetical order of (left, right).
3. Return (pair, new_words), where new_words has every occurrence of that pair merged into one symbol (left + right), scanning each word left to right without overlap.

If no pair exists, return (None, words).

Signaturedef bpe_merge_step(words)

Understand the idea

Byte Pair Encoding learns a vocabulary by noticing which two neighbouring symbols appear together most often and fusing them into one new symbol. It is like noticing you always write 't' then 'h' and inventing a single key for 'th'. One merge step has two parts: count every adjacent pair across all words, then rewrite the words with the winning pair joined. Worked example: words [a, b, c] and [a, b, d]. Pairs: (a, b) appears 2 times, (b, c) once, (b, d) once. The winner is (a, b), so the new words are [ab, c] and [ab, d]. If two pairs tie on count, the alphabetically smaller (left, right) pair wins. While rewriting, scan left to right and, after a merge, jump past both symbols, so [a, a, a] with pair (a, a) becomes [aa, a], not two overlapping merges. Rule: best pair = highest count, then smallest pair; merge without overlap. GPT style tokenizers are trained by repeating this step thousands of times.

solution.pyPython idle
Ctrl/Cmd + Enter runs sample tests

Run checks the first 2 tests. Submit checks all 4.

  • Sample 1: low / lowerbpe_merge_step([["l","o","w"],["l","o","w","e","r"]])
  • Sample 2: tie breaks alphabeticallybpe_merge_step([["b","c"],["a","b"]])
  • Test 3: no overlap in aaabpe_merge_step([["a","a","a"]])
  • Test 4: nothing to mergebpe_merge_step([["x"],["y"]])