Lesson 2.5 · 5 of 6 · 7 min read · Reviewed 24 Nov 2026
Tokenizer algorithms: BPE, WordPiece and SentencePiece
By the end, you can
- Describe how BPE builds a vocabulary by merging the most frequent pairs.
- Tell BPE, WordPiece and SentencePiece apart and say why the choice changes token counts.
Lesson 2.1 said tokenizersTokenizer: The component that splits text into tokens and maps each token to an id the model can process. learn their word pieces from data. This lesson shows how. Three families cover almost every model you will meet.
BPE: merge the most frequent pair
Byte pair encoding (BPEByte-pair encoding (BPE): A tokenization method that starts from characters or bytes and repeatedly merges the most frequent pairs into new tokens.) started as a compression trick and was adapted for language models. Training works like this:
- Split every word in the training text into single characters.
- Count every adjacent pair of symbols across the corpus.
- Merge the most frequent pair into one new symbol and add it to the vocabulary.
- Repeat until the vocabulary reaches the size you chose.
A worked example on a tiny corpus, low ×5, lower ×2, newest ×6, widest ×3:
| Step | Most frequent pair | New symbol | Why |
|---|---|---|---|
| 1 | e + s |
es |
In newest and widest: 6 + 3 = 9 |
| 2 | es + t |
est |
Again 9 |
| 3 | l + o |
lo |
In low and lower: 5 + 2 = 7 |
| 4 | lo + w |
low |
Again 7 |
Ties (such as s + t, also 9 at step 1) are broken by a fixed rule, here the pair seen first. After four merges, lowest (never seen in training) becomes low + est: two tokensToken: The unit a model reads and writes: a word, part of a word, a space or a symbol, mapped to an integer id. built from pieces the tokenizer did see. To tokenise new text, the tokenizer replays its merges in the order it learned them.
Many current models use byte-level BPE: the starting units are the 256 possible bytes rather than characters. Any text, emoji or binary-looking string can be encoded, so there is never an “unknown” token.
WordPiece: merge what helps most
WordPiece, used by BERT and related models, builds its vocabulary the same bottom-up way, but chooses merges differently. Instead of the most frequent pair, it picks the pair whose merge most increases the likelihood of the training data. In practice that favours pairs that appear together more than their separate frequencies would predict. WordPiece marks pieces that continue a word with a prefix, so playing might become play + ##ing.
SentencePiece: no pre-splitting on spaces
BPE and WordPiece usually split text on spaces first, which assumes the language uses spaces. SentencePiece treats the whole input as one streamStreaming: Receiving a response as a series of server-sent events while it is generated, instead of waiting for the whole reply. of characters and encodes the space itself as a visible symbol (often ▁). That makes it work the same way for Japanese, Thai or Chinese as for English, and lets you turn tokens back into the exact original text. SentencePiece is a library that can train either BPE or a unigram model, which starts from a large vocabulary and prunes the pieces that matter least.
Side by side
| BPE | WordPiece | SentencePiece | |
|---|---|---|---|
| Builds vocab by | Merging the most frequent pair | Merging the pair that most helps likelihood | BPE or unigram, on raw text |
| Word boundary | Leading space in the token (byte-level) | ## on continuing pieces |
▁ symbol for spaces |
| Unknown text | None with byte-level BPE | Rare characters may become [UNK] |
Can fall back to bytes |
Why an architect cares
- Counts differ by model. The same paragraph can be 10 to 30% more or fewer tokens on another model’s tokenizer, and far more for some languages. Budgets and cost estimates from one model do not carry over.
- Language fairness. A tokenizer trained mostly on English splits other languages into more pieces, so they cost more and fill the window faster.
- Always measure with the target model’s tokenizer or its token countingToken counting: Measuring how many tokens a request will use before sending it, for example with a token-counting endpoint. endpoint. Never assume.
Key points
- Subword tokenizers learn their vocabulary from data. They start from small units and repeatedly merge pieces that often appear together.
- BPE merges the most frequent adjacent pair. WordPiece picks the merge that most improves the likelihood of the training text. Both mark word boundaries in their own way.
- SentencePiece treats the input as a raw character stream, spaces included, so it works for languages that do not separate words with spaces.
- Byte-level BPE starts from bytes, so it can encode any text with no unknown tokens.
Train a BPE tokenizer from scratch
Learn BPE merges from a tiny corpus and use them to tokenise words the tokenizer never saw.
You will have: A train() function that learns merges and a tokenize() function that replays them.
Steps
- Write count_pairs to add each word's frequency to every adjacent pair.
- Write merge to join one pair everywhere it appears.
- In train, pick the most frequent pair, record it and merge it, four times.
- Write tokenize to replay the merges in order and try lowest, newer and wide.
Done when
- The four merges come out as es, est, lo, low.
- lowest, never seen in training, becomes low + est.
- Words with no learned merges stay as single characters.
Open in the Playground No API key needed.
Starter code (Python)
CORPUS = {"low": 5, "lower": 2, "newest": 6, "widest": 3}
def count_pairs(vocab):
pairs = {}
# TODO: for each word (a tuple of symbols) add its frequency to every adjacent pair
return pairs
def merge(vocab, pair):
# TODO: return a new vocab where every occurrence of pair is joined into one symbol
return vocab
def train(corpus, n_merges):
vocab = {tuple(word): freq for word, freq in corpus.items()}
merges = []
for _ in range(n_merges):
pairs = count_pairs(vocab)
if not pairs:
break
# TODO: pick the most frequent pair, record it and merge it
return merges
merges = train(CORPUS, 4)
print("merges:", ", ".join(a + b for a, b in merges))
# TODO: write tokenize(word, merges) that replays the merges in order, and try "lowest"
Show a solution
CORPUS = {"low": 5, "lower": 2, "newest": 6, "widest": 3}
def count_pairs(vocab):
pairs = {}
for symbols, freq in vocab.items():
for a, b in zip(symbols, symbols[1:]):
pairs[(a, b)] = pairs.get((a, b), 0) + freq
return pairs
def merge(vocab, pair):
out = {}
for symbols, freq in vocab.items():
merged, i = [], 0
while i < len(symbols):
if i < len(symbols) - 1 and (symbols[i], symbols[i + 1]) == pair:
merged.append(symbols[i] + symbols[i + 1]); i += 2
else:
merged.append(symbols[i]); i += 1
out[tuple(merged)] = freq
return out
def train(corpus, n_merges):
vocab = {tuple(word): freq for word, freq in corpus.items()}
merges = []
for _ in range(n_merges):
pairs = count_pairs(vocab)
best = max(pairs, key=pairs.get) # ties: the pair seen first wins
merges.append(best)
vocab = merge(vocab, best)
return merges
def tokenize(word, merges):
symbols = tuple(word)
for pair in merges: # replay merges in the order they were learned
symbols = next(iter(merge({symbols: 1}, pair)))
return list(symbols)
merges = train(CORPUS, 4)
print("merges:", ", ".join(a + b for a, b in merges))
for word in ["lowest", "newer", "wide"]:
print(word, "->", " + ".join(tokenize(word, merges)))