v9.1.1
Menu

BPE Trainer

mediumFREETokenization AlgorithmsLLM 1: Foundations

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

Input
low lower newest
2
Output
e low n r s t w
Reasoning
  • Inputs: text is three words, and num_merges is 22. 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 =2=2, o·w =2=2, w·e =2=2 (once in "lower", once in "newest"), and every other pair =1=1. Three pairs tie at 22. 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 =2=2 and w·e =2=2 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

Learn this in

More from LLM 1: Foundations

solution.py

Test results

Sign in to run your code against the test cases.