How BPE works
- Start with characters. Every word is split into single characters. The vocabulary is the distinct characters in the text.
- Count neighbouring pairs. For every pair of characters that sit next to each other, count how many times it occurs in the whole text.
- Merge the most frequent pair. The pair becomes a new piece, which is added to the vocabulary and replaced everywhere in the text.
- Repeat until the vocabulary reaches the size you want.
The result is an ordered list of merges. That list is the tokenizer: to split new text, you start again from characters and apply the merges in exactly the order they were learned. That is why a word that never appeared in the training text can still be split into known pieces, for example “lowest” into “low” and “est”.
A worked example
The demo’s English text is the example from Sennrich, Haddow and Birch: “low” 5 times, “lower” 2, “newest” 6 and “widest” 3. Split into characters, that is 79 tokens and a vocabulary of 10 characters.
- “e” + “s” occurs 9 times (6 in “newest”, 3 in “widest”) and is merged first, into “es”.
- “es” + “t” also occurs 9 times and becomes “est”.
- “l” + “o” and then “lo” + “w” occur 7 times and give “low”.
- “n” + “e”, “ne” + “w” and “new” + “est” turn all six “newest” into a single token.
After 12 merges no pair occurs twice, and training stops: the text is down to 16 tokens with a vocabulary of 22 pieces. The word “lowest” is not in the text, but the merges split it into “low” + “est”.
BPE in Python
The whole algorithm fits in about 40 lines of Python. It does the same as the demo: it counts pairs only inside words, breaks ties by the pair seen first, and stops when no pair occurs at least twice. Run it, and it prints the first four merges from the example above.
from collections import Counter
def merge(symbols, pair):
# Replace the pair everywhere, left to right.
out, i = [], 0
while i < len(symbols):
if symbols[i:i + 2] == pair:
out.append(pair[0] + pair[1])
i += 2
else:
out.append(symbols[i])
i += 1
return tuple(out)
def train(text, max_merges=50):
# Each distinct word as characters, with its count.
counts = Counter(text.split())
words = {tuple(w): n for w, n in counts.items()}
merges = []
for _ in range(max_merges):
pairs = Counter()
for symbols, n in words.items():
for pair in zip(symbols, symbols[1:]):
pairs[pair] += n
if not pairs:
break
# Most frequent pair (ties: the one seen first).
best = max(pairs, key=pairs.get)
if pairs[best] < 2:
break
merges.append(best)
words = {merge(s, best): n
for s, n in words.items()}
return merges
def encode(word, merges):
# Start from characters, apply merges in order.
symbols = tuple(word)
for pair in merges:
symbols = merge(symbols, pair)
return list(symbols)
text = ("low " * 5 + "lower " * 2
+ "newest " * 6 + "widest " * 3)
merges = train(text)
print(merges[:4])
# [('e', 's'), ('es', 't'), ('l', 'o'), ('lo', 'w')]
print(encode("lowest", merges))
# ['low', 'est']
Counting every pair again after each merge is fine for a small text but slow for a large one. Real implementations keep track of where each pair occurs and update only the counts a merge changes. Byte-level versions start from bytes instead of characters (see below).
Why do language models use BPE?
A model needs a fixed vocabulary. Whole words give a huge vocabulary with no room for new words. Single characters give very long sequences. BPE sits in between: common words become one token, rare words are split into recognisable pieces, and no word is unknown, because you can always fall back on the smallest pieces.
The method comes from data compression and was used to split words for machine translation by Sennrich, Haddow and Birch in 2016. The English example in the demo is the one from their paper. GPT-2 and many later language models use a variant that works on bytes instead of characters.
How real tokenizers differ
- Bytes instead of characters. Byte-level BPE starts from the 256 possible bytes, so any text can be represented, including emoji and rare characters.
- Spaces are part of the token. Real tokenizers usually split text at spaces and punctuation first and attach the space to the following word. The demo here only splits at spaces and never merges across two words.
- Much larger vocabularies. GPT-2’s tokenizer has 50,257 tokens. The demo stops when no pair occurs at least twice.
- Other methods. WordPiece (BERT) and Unigram (often via SentencePiece) also build vocabularies of word pieces, but choose the pieces in different ways.
What it means for other languages
A tokenizer learns its merges from its training text. If that text is mostly English, English words often become a single token while words in other languages are split into more pieces. The same meaning can then cost more tokens, and so more of the model’s context. In the Tokenization lab you can compare how different tokenizers split the same text.
Try it on real tokenizers
In the free Tokenization lab you see how real language models’ tokenizers split your text, follow BPE merges on your own text, and train a small model on tokens.
More explainers
- How self-attention works
- Backpropagation, step by step
- Temperature and top-p in language models
- What is overfitting?
- What is a tokenizer?
- What is activation patching?
- What are logits?
- What are embeddings?
- What is prompt injection?
- How does tool calling work?
- What are steering vectors?
- What is LoRA?
- What is quantization?
- What are scaling laws?