BPE Trainer
Implement BPE training for a given number of merges.
Starting with a character-level tokenization of the input text (each character is a token, words separated by spaces are kept separate), repeatedly find the most frequent adjacent token pair and merge them.
Input:
- text: the text
- num_merges: number of merges to perform
Output: Return the final vocabulary as a set of the unique tokens after all merges. The tests sort it alphabetically and print it space-separated.
Rules:
- Split text into words by spaces; each word is tokenized into characters
- At each step, count adjacent pairs across all words, find the most frequent
- If there's a tie, pick the pair that comes first alphabetically (by concatenation)
- Merge that pair in all words
- Repeat for the given number of merges
Example
low lower newest 2
e low n r s t w
- Inputs:
textis three words, andnum_mergesis . Each word starts as its own character sequence: l·o·w, l·o·w·e·r, n·e·w·e·s·t. Pairs never cross a space, so the last letter of one word is never paired with the first letter of the next. - Merge 1: counting adjacent pairs over all three words gives l·o , o·w , w·e (once in "lower", once in "newest"), and every other pair . Three pairs tie at . Comparing their concatenations, "lo" < "ow" < "we", so l and o fuse into lo: lo·w, lo·w·e·r, n·e·w·e·s·t.
- Merge 2: now lo·w and w·e tie. "low" < "we", so low is formed: low, low·e·r, n·e·w·e·s·t.
- Output: the distinct tokens still present are low, e, r, n, w, s, t. Sorted alphabetically they read
e low n r s t w. - Notice that lo, l and o are missing. The vocabulary holds only the tokens that are still present after the last merge, not every token that ever existed.
Constraints
- 1 <= number of merges <= 20
- Text contains lowercase letters and spaces
- Words are separated by single spaces
- Output sorted unique tokens after all merges