How AI Language Models Work · Text as Numbers

Byte-Pair Encoding: Learning Word Pieces

Real tokenizers are learned, not written by hand. Start from single letters and keep merging the most common pair, and useful pieces like "low" appear by themselves.

bpe_tokenizer.py

# Real tokenizers learn word pieces. Byte-pair encoding (BPE): start from letters, keep merging the most common pair.
words = ["l o w", "l o w e r", "l o w e s t", "s l o w"]

for merge in range(3):
    pairs = [a + " " + b for w in words for a, b in zip(w.split(" "), w.split(" ")[1:])]
    options = list(dict.fromkeys(pairs))
    counts = [pairs.count(p) for p in options]
    best = options[counts.index(max(counts))]
    words = [(" " + w + " ").replace(" " + best + " ", " " + best.replace(" ", "") + " ").strip() for w in words]
    print("merge", merge, ":", best, "->", words)

Step by step

  1. Four words, each split into single letters with spaces between the pieces. Every letter is a token to begin with.
  2. Do three merges. Real tokenizers do tens of thousands.
  3. Every pair of neighbouring pieces in every word: "l o", "o w", "w e" and so on.
  4. Each different pair once.
  5. How often each appears. "l o" and "o w" both appear 4 times, once in every word.
  6. The most common pair wins. In a tie the first one found wins: "l o".
  7. Merge it everywhere: "l o" becomes the single piece "lo". The spaces around the pair make sure only whole pieces are joined.
  8. It prints merge 0 : l o -> ['lo w', 'lo w e r', 'lo w e s t', 's lo w'].
  9. merge changes from 0 to 1.
  10. pairs now points to a different list: ['lo w', 'lo w', 'w e', 'e r', 'lo w', 'w e', 'e s', 's t', …].
  11. options now points to a different list: ['lo w', 'w e', 'e r', 'e s', 's t', 's lo'].
  12. "lo w" appears 4 times.
  13. best changes from 'l o' to 'lo w'.
  14. Merged: "low" is now a single token, and "low" on its own is one token.
  15. It prints merge 1 : lo w -> ['low', 'low e r', 'low e s t', 's low'].
  16. merge changes from 1 to 2.
  17. pairs now points to a different list: ['low e', 'e r', 'low e', 'e s', 's t', 's low'].
  18. options now points to a different list: ['low e', 'e r', 'e s', 's t', 's low'].
  19. "low e" appears twice (lower, lowest); everything else once.
  20. best changes from 'lo w' to 'low e'.
  21. "lowe" becomes a piece. Pieces do not have to be real words or syllables, just common.
  22. It prints merge 2 : low e -> ['low', 'lowe r', 'lowe s t', 's low'].
  23. After three merges: "low" is one token, "lowest" is three ("lowe", "s", "t"). Common words end up as single tokens and rare words as a few pieces. That is why "tokens" and "words" are different counts.