Tokenization
After this lesson, you will be able to:
- Understand why neural networks need numbers, not words, and how tokenization bridges the gap
- Walk through the Byte-Pair Encoding (BPE) algorithm step by step
- Compare three tokenization methods: BPE, WordPiece, and SentencePiece
- See how vocabulary size (small vs. large) changes what the model can learn
- Understand why splitting words into sub-pieces became the standard in modern LLMs
- Spot common tokenization mistakes that quietly hurt model quality
#The First Translation
Why not just split on spaces and assign each word a number? Three reasons:
-
Vocabulary explosion. English has over 170,000 words in common use. Add misspellings, proper nouns, code, URLs, and multilingual text, and you need millions of entries. Each entry is a row in the embedding matrix, so millions of rows means billions of parameters just for embeddings.
-
Unknown words. Any word not in your vocabulary becomes an
<UNK>token, losing all meaning. "Transformerization" would be unknown to a word-level tokenizer. -
Morphology blindness. "run," "runs," "running," and "runner" share a root but are four separate entries. The model must learn their relationship from scratch, with no structural hint that they are related.
Subword tokenization solves all three problems by splitting text into pieces that balance frequency and coverage.
#Byte-Pair Encoding: Step by Step
BPE starts with individual characters and iteratively merges the most frequent adjacent pair into a new token. The algorithm is simple but powerful.
#Step 1: Start with Characters
['l', 'o', 'w', 'e', 'r']. Add a special end-of-word marker (often </w> or _) so the model knows where words end. Your initial vocabulary is just the set of all characters that appear in the corpus — typically 256 bytes for a byte-level BPE.#Step 2: Count All Adjacent Pairs
Scan the entire corpus and count how often each pair of adjacent tokens appears. If "th" appears 1,000 times and "he" appears 900 times, those are the top pairs. This counting happens across all words, weighted by word frequency.
#Step 3: Merge the Most Frequent Pair
['t', 'h', 'e'] to ['th', 'e'].#Step 4: Repeat
Go back to Step 2 and count pairs again (now including the newly merged token). The pair "th" + "e" might now be the most frequent, creating the token "the". Repeat until you reach your desired vocabulary size — typically 32,000 to 128,000 tokens for modern LLMs.
#Step 5: The Final Vocabulary
After thousands of merges, you have a vocabulary that includes single characters (for handling any input), common subwords ("ing", "tion", "pre"), full common words ("the", "and", "for"), and even multi-word fragments. Common words are single tokens; rare words get split into known subword pieces.
#Interactive: Watch BPE in Action
Type any text above and watch BPE split it into tokens. Try these experiments:
- Type a common word like "the" — it should be a single token
- Type an unusual word like "defenestration" — watch it split into subword pieces
- Type code like
console.log("hello")— notice how code tokens differ from English - Type a word in another language — see how the tokenizer handles unfamiliar scripts
#End-to-End BPE: From Raw Text to Token IDs
#Step 1: Raw Text Input
"lowest". This is just a string of characters, and the model cannot process it directly. We need to convert it to a sequence of integer token IDs from our learned vocabulary.#Step 2: Split to Characters
['l', 'o', 'w', 'e', 's', 't']. Add a special end-of-word marker. This is our starting vocabulary — every character that appears in the training corpus. For byte-level BPE, the initial vocabulary is the 256 possible byte values.#Step 3: Find the Most Frequent Pair
('e', 's') appears most frequently across words like "lowest," "newest," "widest." This pair is selected for merging. The count is weighted by how often each word appears.#Step 4: Merge to New Token
'e' + 's' into the new token 'es' everywhere in the corpus. The word now becomes ['l', 'o', 'w', 'es', 't']. The token 'es' is added to the vocabulary with a new ID. The merge rule ('e', 's') -> 'es' is recorded in the merge table.#Step 5: Repeat Merges
'es' + 't' might merge into 'est'. Then 'l' + 'o' into 'lo', and 'lo' + 'w' into 'low'. Each merge creates a new token and is added to the ordered merge table. Repeat until the vocabulary reaches the target size (32K-128K tokens).#Step 6: Final Vocabulary
'est', 'ing', 'tion', full common words like 'the', 'and', 'low', and the special tokens ([PAD], [UNK], [CLS]). Our word "lowest" is now tokenized as ['low', 'est'] — two meaningful subword tokens.#Step 7: Encode New Text
"lowest" becomes ['low', 'est'] which maps to token IDs [4521, 891]. These integers are what the model actually sees. The merge table is deterministic, so the same text always produces the same tokens.#The Math Behind the Merge
At each step, BPE selects the pair that maximizes frequency:
Why this score? Merging a pair replaces two tokens by one, so the pair's count is exactly the number of tokens the merge removes from the corpus. Picking the highest count is therefore the greedy way to shorten the corpus the most. The derivation shows this step by step.
If your training corpus is entirely English text, what happens when the model encounters Chinese characters at inference time?
<UNK> tokens ever. Rare scripts just require more bytes per character.#Byte-level BPE: a concrete trace
Talking about "bytes" in the abstract is one thing. Watching them on paper is what makes the algorithm click. The next few paragraphs take two simple strings, encode them to UTF-8, and walk through one merge step of a tiny BPE trainer so you can see exactly what a tokenizer sees.
c, a, f each take a single byte: 0x63, 0x61, 0x66. But é is U+00E9, which lives outside the ASCII range, so UTF-8 spends two bytes on it: 0xC3 0xA9. The whole word is the 5-byte sequence [0x63, 0x61, 0x66, 0xC3, 0xA9], one more byte than the four user-visible characters suggest.[0xF0, 0x9F, 0xA6, 0x99]. A byte-level BPE tokenizer therefore starts with four tokens for one emoji before any merges happen, which is exactly why pre-merge sequence lengths are so different across scripts.cat→c a t× 3 = pairs(c,a)× 3,(a,t)× 3café→c a f 0xC3 0xA9× 2 = pairs(c,a)× 2,(a,f)× 2,(f,0xC3)× 2,(0xC3,0xA9)× 2car→c a r× 4 = pairs(c,a)× 4,(a,r)× 4
(c,a) appears 3 + 2 + 4 = 9 times — the most-frequent pair by a wide margin. BPE merges it into a new token ca. After the first merge the words become ca t, ca f 0xC3 0xA9, and ca r. The next round counts pairs again, sees (ca, r) × 4 leading the pack, and merges that to produce car as a single token. Three or four merges in, the most common surface forms of this toy corpus are already single tokens, while the rare bytes of é stay separate. That is the whole BPE algorithm; everything else is scale."Hello, world!" lands in just 4 tokens (Hello, ,, world, !) because each of those substrings was frequent enough during training to win merges. Strings like def , return , and, and </div> are similarly compressed into single tokens, which is why GPT-4 reads Python and HTML almost as densely as prose. By contrast, Swahili text, which barely appeared in the merge-training corpus — averages roughly 3–4× more tokens per word than English, because most subword merges never fired and you end up paying near the byte rate. Hindi and Burmese can be 5–6× worse. The tokenizer is the same; the merge table is what is unbalanced.tiktoken (via Pyodide) on your own strings and see the fertility difference across languages firsthand.A multilingual chat product charges a flat per-message price. Why might a Swahili user effectively get 3× less context than an English user with the same byte-pair tokenizer?
#WordPiece and SentencePiece
BPE is not the only subword algorithm. Two important alternatives shaped the field:
#WordPiece (BERT)
##, so "playing" might become ['play', '##ing'].Where does the ratio come from? It is the part of the likelihood gain of a merge that depends on how common the two pieces are. The derivation below is a motivation for the score, not a proof that the score is the exact best merge.
#SentencePiece (T5, LLaMA)
▁ (a special underscore). This makes it language-agnostic, equally effective for English, Japanese, Thai (which has no spaces), and mixed-language text.#Vocabulary Size: The Goldilocks Problem
A model with vocabulary size 256 (just bytes) vs. one with vocabulary size 100,000, which needs fewer tokens to represent the same text?
Vocabulary size creates a fundamental tradeoff:
| Small Vocabulary (< 10K) | Large Vocabulary (> 100K) |
|---|---|
| More tokens per sentence | Fewer tokens per sentence |
| Smaller embedding matrix | Larger embedding matrix |
| Better on rare/novel words | May waste capacity on rare tokens |
| Slower inference (more steps) | Faster inference (fewer steps) |
| Learns subword patterns well | Each token is more semantically complete |
Modern LLMs have converged on roughly 100K-200K tokens as the sweet spot. GPT-4 uses ~100K (cl100k_base), GPT-4o uses ~200K (o200k_base), Llama 1 and 2 used 32K but Llama 3 and 3.1+ jumped to a 128K tiktoken-style vocabulary, and Mistral models use 32K-128K. Labs that do not publish their tokenizers, Anthropic among them, give no official vocabulary size. The trend is toward larger vocabularies because the embedding matrix cost is small compared to the attention and FFN parameters in a multi-billion-parameter model, and larger vocabs reduce sequence length — directly cutting inference cost.
Two numbers decide the trade-off: how many parameters the vocabulary adds, and how many tokens a given text needs. Open the derivation to put them in one formula and compute the break-even point.
#Try It: Build a Mini BPE Tokenizer
#Why Tokenization Matters for You
Tokenization is not just an implementation detail. It directly affects model behavior:
-
Cost. API pricing is per token. Inefficient tokenization means you pay more for the same content. Code and non-English text often cost 2-3x more in tokens than English prose.
-
Context window. A 128K token limit holds different amounts of text depending on the tokenizer. Dense technical text with rare terms uses more tokens than simple English.
-
Arithmetic failures. LLMs struggle with arithmetic partly because numbers are tokenized unpredictably. "123456" might be one token, two tokens, or three tokens depending on the number and the tokenizer. The model never sees individual digits consistently.
-
Multilingual bias. Tokenizers trained primarily on English text produce more tokens for non-English text, making those languages more expensive and reducing effective context length.
Try the cost side of this yourself: the same sentence, three vocabularies and a live count of tokens.
- Do: Choose the Numbers preset, then the Multilingual preset, and switch between English-only, Multilingual and Character-level each time. Hover over a token.
- Notice: Watch the Tokens and Tokens / word readouts. Rare words such as antidisestablishmentarianism, and text outside the small vocabulary, split into many small pieces, and the ratio card turns amber above 2. In this toy vocabulary every digit is its own token, while real tokenizers group digits differently from model to model.
- Why: Cost and context length are counted in tokens, so more pieces for the same text means a bigger bill and less room. Drawn stand-in, not a trained tokenizer: the vocabulary is a short hand-made list matched longest piece first, ids come from a hash and the merge history is just a split in halves, so the counts show the effect but not any real model's numbers.
#Key Takeaways
- BPE is iterative compression. The algorithm merges the most frequent adjacent byte pair into a new token, repeated until the vocabulary size target is reached. Modern LLMs have converged on roughly 100K–200K token vocabularies.
- Tokenization is unequal across languages. Latin scripts tokenize at roughly 1 token per word, while CJK languages often need 2–3 tokens per character, so prompts can cost 2–4x more for the same meaning.
- Vocabulary size is a Goldilocks problem: too small means poor compression and long sequences, too large means rare tokens have sparse training signal and poor representations.
- Count with the real tokenizer, not approximations.
tiktoken(OpenAI) and Anthropic's tokenizer API give exact counts, and off-by-one estimates cause silent truncation in production. - Prompt caching operates at token boundaries, so understanding tokenization helps you structure system prompts for higher cache hit rates.
#Quick Check
What does BPE merge at each step?