Foundations to Frontier
Tests

Byte-Pair Encoding: Algorithm and Implementation from Scratch

Byte-pair encoding (BPE) builds a subword vocabulary by repeatedly merging the most frequent adjacent pair of symbols in a training corpus. It starts from characters (or bytes); each merge adds one new token; the ordered list of merges is the tokenizer. To encode new text, the merges are applied in the order they were learned. BPE began as a data-compression method (Gage, 1994) and became the standard tokenizer for GPT-style models after Sennrich and colleagues used it for translation in 2016. This page covers the training loop, efficient pair counting, encoding and decoding, end-of-word markers, vocabulary size, and how training data shapes the result. In the exercises you implement BPE training and encoding, then study a tokenizer on held-out text. 1000 merges cut test text from 7.0 to 1.22 tokens per word. A tokenizer trained on general text needed 4.58 tokens per word on technical text, against 1.57 for one trained on technical text; a mixed tokenizer needed 1.77. Common suffixes (s, ed, ing, er, ly) appeared among the first 30 merges.

Level 0: Foundation

★☆☆☆☆ Introductory⏱ 5 minGeneral audience. No mathematics required.

Gluing together the pairs that appear most

Start with every word spelled out letter by letter. Find the pair of neighbouring symbols that appears most often in the whole collection, say “e” followed by “s”, and glue it into one new symbol “es”. Repeat thousands of times. Common endings like “ing” and whole common words soon become single tokens, while rare words stay split into smaller pieces. The demo shows the merges a toy corpus learns, one step at a time.

Language lab
Merges learned: we, lo, ne, r</w>. Corpus now: lo·we·r</w> lo·we·s·t·</w> ne·we·r</w> ne·we·s·t·</w> … Frequent pairs fuse into subwords such as "est" and "er".
Why engineers care

Every GPT-style model, and most code and multilingual models, use a BPE tokenizer. Knowing how it was trained explains why some words, numbers or identifiers are cheap and others are expensive.

📝 Quick check (Level 0)
0/3 answered
  1. 1. BPE repeatedly merges…
  2. 2. Each merge adds…
  3. 3. Common endings like 'ing' become…

Level 1: Beginner

★★☆☆☆ Basic⏱ 20 minSecondary-school mathematics: arithmetic and elementary algebra.

By hand

  • Training:
    1. Split every training word into characters plus an end-of-word marker </w> (or use bytes and a leading-space marker, as GPT-2 does).
    2. Count all adjacent symbol pairs, weighted by word frequency.
    3. Merge the most frequent pair everywhere, record the merge rule, and repeat until the target vocabulary size is reached. Vocabulary = base symbols + number of merges (256 bytes + 31,744 merges = 32,000).
  • Encoding: split a new word into characters and apply the merge rules in learned order (or, equivalently, repeatedly merge the adjacent pair with the lowest rule rank).
  • Decoding: concatenate tokens and turn </w> back into spaces; encoding is lossless.
  • Efficiency: work on word types with counts, not on running text, and update pair counts only for words containing the merged pair.
  • Compression: English text with GPT tokenizers averages about 4 characters per token.
📝 Quick check (Level 1)
0/3 answered
  1. 1. Merges needed for a 32,000-token byte-level vocabulary:
  2. 2. New text is encoded by applying merges…
  3. 3. BPE encoding is…

Level 2: Intermediate

★★★☆☆ Intermediate⏱ 25 minUndergraduate students and practising engineers.

BPE in code

Exercise 1.

  • Count pairs, merge the best pair, and repeat to learn rules.
  • Encode a word by applying the rules in order; decoding gives back the original word.

Practice.

  • Hugging Face tokenizers trains byte-level BPE on gigabytes in minutes; tiktoken provides OpenAI’s encoders; SentencePiece offers BPE and Unigram.
  • Choose training text that matches what the model will see (languages, code, domain).
  • Pre-tokenise with a regex (splitting digits, punctuation and spaces) so that merges do not cross word or number boundaries.
  • Save the merges and vocabulary with the model; the tokenizer is part of the model.
from tokenizers import Tokenizer, models, trainers, pre_tokenizers
tok = Tokenizer(models.BPE(unk_token=None))
tok.pre_tokenizer = pre_tokenizers.ByteLevel(add_prefix_space=False)
tok.train(["corpus.txt"], trainers.BpeTrainer(vocab_size=32000, initial_alphabet=pre_tokenizers.ByteLevel.alphabet()))
print(tok.encode("unlaunchable rockets").tokens)
🐍 Exercise 1: BPE from scratch
Implement pair counting, merging, BPE training and encoding.
📝 Quick check (Level 2)
0/3 answered
  1. 1. A fast library for training BPE:
  2. 2. Pre-tokenisation prevents merges…
  3. 3. The tokenizer should be saved…

Level 3: Advanced

★★★★☆ Advanced⏱ 25 minGraduate level, with full derivations and proofs.

Theory

BPE as greedy compression. Each merge replaces the most frequent pair, so it removes the largest number of symbols from the training corpus at that step. The total corpus length falls with every merge, as in Gage’s original compressor. The greedy choice is not globally optimal; Unigram tokenisation (F2-3) instead optimises a likelihood over segmentations.

What the merges capture. Frequent sub-strings are frequent because they are reused: morphemes, common words and frequent character sequences. So the learned vocabulary approximates the language’s reusable units, as measured on the training data.

Dependence on training data. The merges reflect the training distribution. Text from another domain or language shares fewer frequent pairs, so it falls back to short pieces and needs many more tokens per word. This affects cost, context length and often accuracy, and is one reason models are weaker in under-represented languages.

📝 Quick check (Level 3)
0/3 answered
  1. 1. Each BPE merge greedily…
  2. 2. Learned merges approximate…
  3. 3. Out-of-domain text tends to need…

Level 4: Expert

★★★★★ Expert⏱ 30 minResearchers: original papers and open problems.

How does a BPE tokenizer’s training data shape its efficiency?

History.

  • P. Gage, “A new algorithm for data compression” (C Users Journal, 1994).
  • R. Sennrich, B. Haddow and A. Birch, “Neural machine translation of rare words with subword units” (ACL 2016).
  • A. Radford et al., “Language models are unsupervised multitask learners” (2019), with byte-level BPE.

Exercise 2.

  • General text: words from about 400 stems plus 10 suffixes (as in F2-1); 20,000 training and 5000 test tokens.
  • Technical text: different stems built from other letters, with 20% part-number-like codes (two letters + two digits).
  • Experiments:
    • fertility (tokens per word, counting the end marker) on held-out general text after 0, 100, 300 and 1000 merges;
    • 1000-merge tokenizers trained on general, technical, or mixed (half and half) text, applied to both test sets;
    • which suffixes appear among the first 30 merges.
merges tokens per word (general test)
0 (characters) 7.001
100 2.347
300 1.664
1000 1.219
tokenizer trained on technical test general test
general text 4.581 1.219
technical text 1.569 4.813
mixed 1.767 1.454
  • Compression has diminishing returns: the first 100 merges cut length by two-thirds; the next 900 cut a further 48%.
  • Domain mismatch costs 2.9×: the general tokenizer splits technical words almost into characters, because their frequent pairs never appeared in its training text.
  • Mixing the training data covers both at a moderate cost on each (1.77 and 1.45).
  • Merges recover morphology: the suffixes s, ed, er, ers, ing and ly were all among the first 30 merges.
  • Seeds: seed 1 gave 1.232 tokens per word at 1000 merges, and 4.553 against 1.582 for general against technical tokenizers on technical text.
  • A test I got wrong: I expected the first merge in the exercise-1 example to be “s” + “t”. With end-of-word markers, t + </w> ties at 9 and wins the tie-break, so the ending est</w> is built in three merges.
🐍 Exercise 2 (research): how does a BPE tokenizer's training data shape its efficiency?
Train BPE tokenizers, measure tokens per word on held-out text as merges grow, and transfer tokenizers between a general and a technical domain.

BPE in AI, robotics and aerospace

  • Domain models: retraining or extending a tokenizer for aerospace text with many codes and units reduces cost and improves accuracy.
  • Multilingual systems: balancing training data across languages to keep fertility even.
  • Design lesson: a tokenizer is trained on data like any model; it works best on text like its training set.

References

  1. P. Gage (1994). “A new algorithm for data compression.” C Users Journal 12(2).
  2. R. Sennrich, B. Haddow and A. Birch (2016). “Neural machine translation of rare words with subword units.” Proc. ACL.
  3. A. Radford et al. (2019). “Language models are unsupervised multitask learners.” OpenAI technical report.
  4. A. Petrov et al. (2023). “Language model tokenizers introduce unfairness between languages.” NeurIPS.