Skip to content
BytePatterns

Learn Byte Pair Merges

HardAI & ML#byte-pair-encoding#pair-counting~35m

Problem

Byte pair encoding builds a tokenizer's vocabulary from a corpus. Start with every word split into single characters. Then, merges times, count every pair of adjacent symbols across the corpus, weighting each word by how often it occurs, pick the most frequent pair, breaking ties by the alphabetically smallest pair, record it, and join that pair into one symbol everywhere, left to right. Given the word counts and the number of merges, return the learned merge rules in order. Then write encode(word, rules), which splits a new word into tokens by replaying the rules in the order they were learned.

Examples

Input:  words = {"low": 5, "lower": 2, "newest": 6, "widest": 3}, merges = 4
Output: [('e', 's'), ('es', 't'), ('l', 'o'), ('lo', 'w')]
Why:    e s and s t both occur 9 times, and e s wins the tie alphabetically
Input:  encode("lowest", the rules above)
Output: ['low', 'est']
Why:    a word never seen in training is still built from learned pieces
Input:  encode("xyz", the rules above)
Output: ['x', 'y', 'z']
Why:    edge case, no rule applies, so the word falls back to single characters

Hints

0 / 3

Stuck on the idea rather than the code? BPE vs WordPiece covers it.