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