The Story: From Text to Numbers
Neural networks only understand numbers. You read "Hello world". Your brain understands language.
A language model sees: [15234, 18203, 91028]. Numbers.
How do you convert "Hello world" into numbers in a way the model can understand? That's the role of tokenization (i.e., splitting text into elementary units).
This invisible step is critical. Bad tokenization = model goes haywire, high costs, poor performance. Good tokenization = everything works.
Example: if "Hello" becomes 5 tokens instead of 1, your context shrinks by 80%. Catastrophe.
The Bad Solutions (and Why They Fail)

Approach 1: Word-level Tokenization
Split on spaces. "The cat sleeps" = 3 tokens.
Huge problems:
-
Never-ending vocabulary: the list of words is never closed, new ones appear every day. "Antidisestablishmentarianism", "supercalifragilisticexpialidocious", proper nouns, slang, neologisms. Impossible to store them all.
-
Unknown words: any word outside the vocabulary becomes
[UNK], short for unknown. Such a word is said to be out-of-vocabulary, usually abbreviated OOV. The info disappears. The model just sees noise. -
No morphological understanding: "eat", "eating", "eaten" are 3 different tokens. The model doesn't see the common root "eat-".
Concrete example: a model trained on 50k English words encounters "antidisestablishmentarianism" (rare). [UNK]. Information lost.
Approach 2: Character-level Tokenization
Each letter = 1 token. "cat" = 3 tokens (c, a, t).
Advantage: small vocabulary (26 letters + accents + punctuation = ~50-100 tokens).
Problem: "Hello world" = 11 tokens (10 letters plus the space) instead of 2. Sequences explode. The model becomes very slow, because the cost of attention grows with the square of the token count, every token is compared against every other, written . Going from 2 tokens to 11 is therefore not 5.5 times more work, it is roughly 30 times more.
The Compromise: Subwords
Between these two extremes, there's a sweet middle ground:
Intermediate vocabulary (32k-100k tokens). Frequent words = 1 token. Rare words = multiple coherent sub-tokens.
"antidisestablishmentarianism" -> ["anti", "dis", "establish", "ment", "arian", "ism"]
Each piece is understandable. The model generalizes. No unknown words.
Too much vocabulary = a huge, sparse embedding matrix (most of its rows are almost never used), so inefficient. Too little = long sequences, slow attention, unknown words. Subwords = the elegant and universally used compromise.
BPE: Byte Pair Encoding

BPE, short for Byte Pair Encoding, is the dominant algorithm. It began life as a file-compression trick (Gage, 1994); Sennrich, Haddow and Birch repurposed it in 2015 to split words for machine translation, and that is where today's usage comes from. It is used by the GPT models (Generative Pre-trained Transformer), GPT-2, GPT-3, GPT-4 --, and virtually all popular large language models (LLMs).
Neural Machine Translation of Rare Words with Subword UnitsThe Core Idea: Merge Frequent Pairs
The algorithm is elegantly simple:
- Start with all characters in the corpus as tokens
- Count adjacent pairs (a,b), (b,c), etc.
- The most frequent pair becomes a new token
- Replace all occurrences
- Repeat until reaching the desired vocabulary size
Concrete example:
Initial corpus: "bas bas bas hug hug pug bug", Vocabulary: {b, a, s, h, u, g, p}
Iteration 1, count every pair of adjacent letters:
- (b, a): 3 times (the three "bas"). (a, s): 3 times. (h, u): 2 times. (u, g): 4 times (two "hug", one "pug", one "bug")
- -> the winning pair is (u, g): create the token "ug". The corpus becomes
b a sx3,h ugx2,p ug,b ug
Iteration 2, recount, now treating "ug" as a token in its own right:
- (b, a): 3 times. (a, s): 3 times. (h, ug): 2 times. (p, ug) and (b, ug): once each
- -> tied at the top, take (b, a): create "ba". The next iteration merges (ba, s) into "bas", which also appears 3 times
... continue until 50,000 or 100,000 tokens
The Detailed Algorithm
Phase 1: Initialization
You start with a text corpus. Represent each word as a sequence of characters with a special end-of-word symbol:
| Word | Character sequence |
|---|---|
| "the" | [t, h, e, </w>] |
| "cat" | [c, a, t, </w>] |
| "sleeps" | [s, l, e, e, p, s, </w>] |
Phase 2: Training (once)
Count all adjacent pairs and merge the most frequent ones:
Round 1: Pair (c, a) in "cat" = frequent -> create token "ca", corpus becomes: [t, h, e], [ca, t], [s, l, e, e, p, s]
Round 2: Pair (ca, t) = frequent -> create token "cat", corpus becomes: [t, h, e], [cat], [s, l, e, e, p, s]
... continue until 50k merges
Result: an ordered list of 50k merges (a merge strategy).
Phase 3: Inference (used afterwards)
When you have new text "cat":
- Decompose into characters: [c, a, t]
- Apply merges in the trained order
- [c, a] -> [ca], [ca, t] -> [cat], etc.
- Final result: [cat]
A common word = 1-2 tokens. An unknown word = several tokens. Perfect.
Training: analyze a corpus to find common merges (done once, offline, before any use). Inference: apply the merge list to new text (done on every request, online). Same algorithm, two different roles.
Real Example: "unconstitutionally"
Take this long and rare English word.
English training corpus: BPE discovers that "un-" (prefix), "-tion" (suffix), "-ally" (suffix) are frequent. The word decomposes intelligently:
"unconstitutionally" -> ["un", "constitu", "tion", "ally"]
Each piece is meaningful. The model learns:
- "un-" = negation prefix (unknown, unable, ...)
- "-tion" = nominal suffix (action, nation, ...)
- "-ally" = adverbial suffix (finally, radically, ...)
Result: the model generalizes. Understanding "un-" in "unconstitutional" helps it understand "unable", even if it has never seen that word.
This is the magic of BPE: automatic morphological decomposition, without supervision.
Vocabulary Size: The Big Trade-off
The single parameter of BPE is the final vocabulary size (50k? 100k?).
| Vocabulary | Example | Sequence length | Memory | Generalization |
|---|---|---|---|---|
| 8k | Very small | Long | Small | Excellent |
| 32k-50k | Standard | Medium | Medium | Good |
| 100k+ | Large | Short | Huge | Medium |
Why does large vocabulary = short sequence? It's counter-intuitive at first. The analogy: count in base 2 vs base 10. In base 2 (2 symbols), 42 is written 101010, 6 digits. In base 10 (10 symbols), 42, 2 digits. The larger the "symbol vocabulary", the fewer you need to represent the same information.
Same logic for tokens: with an 8k vocabulary, "tokenize" breaks down into ["to", "ken", "ize"] = 3 tokens. With a 100k vocabulary, "tokenize" is probably a single token = 1 token. Large vocab -> each token encodes more text -> fewer tokens per sentence -> shorter sequences.
Sizes published by these models' own authors:
- GPT-2: 50,257 tokens
- GPT-4, via OpenAI's tiktoken library: about 100,000 tokens
- LLaMA 1 and 2: 32,000 tokens
The choice depends on the corpus, the languages, and the compute budget.
Vocab 2x bigger = embedding table 2x bigger = more memory and more compute. BUT shorter sequences = fewer tokens to process, and since attention cost grows with the square of the token count, the saving is more than proportional. The benefit can offset the cost in the right conditions.
Byte-level BPE: The Trick for Universality
Important variant: BPE can start from Unicode characters (language-sensitive), or from bytes (256 universal values).
Byte-level BPE starts from the 256 bytes of the UTF-8 representation, the universal character encoding of the web.
Result: any human text, in any language, any encoding, can be tokenized. Zero out-of-vocabulary tokens, zero [UNK]: as a last resort everything falls back to bytes, and all 256 bytes are in the vocabulary by construction.
Chinese "你好"? Tokenize.
Arabic "السلام عليكم"? Tokenize.
Emojis "🚀"? Tokenize.
Python code def foo():? Tokenize.
Used by GPT-2, GPT-3, GPT-4, LLaMA. The universal solution.
Limits of BPE (Honestly)
BPE is excellent, but not perfect:
1. Deterministic but suboptimal A single tokenization strategy per word. But maybe a different split would be better? BPE never explores it. It's just the greedy choice: at each step, merge the most frequent pair without ever going back.
2. Dependent on the training corpus A tokenizer trained on 99% English and 1% French tokenizes French poorly. The French word can become 2 to 3 times more tokens. Your context shrinks.
3. Not probabilistic BPE gives one and only one split. No alternatives. No uncertainty. The Unigram algorithm assigns probabilities to competing splits instead: see the other tokenizers, which also covers WordPiece (BERT's) and SentencePiece.
When your model goes haywire in weird ways, check the tokenization first. The OpenAI and Hugging Face online playgrounds show you the actual split of a piece of text. That's often where the invisible bugs hide: a rare word tokenizes badly, blows up your token count, and the model gets confused.
Why This Matters
Tokenization is invisible but omnipresent. It affects:
- Your context length (a rare word = multiple tokens = reduced context)
- The model's arithmetic (numbers are tokenized inconsistently)
- Performance in non-English languages (2 to 3 times more tokens)
- Mysterious bugs (a poorly tokenized word = the model collapses)
Understanding BPE helps you understand why your model behaves strangely. It's often the tokenization.
Key Takeaways
- The problem: how to encode text as numbers?
- The naive approaches: by words (infinite vocab) or characters (long sequences)
- The solution: subwords via BPE
- The algorithm: iteratively merge the most frequent pairs
- Byte-level BPE: zero unknown tokens, works for all languages
- Vocabulary size: 32k-100k, critical parameter
- The limits: deterministic, corpus-dependent, not probabilistic
- The reality: tokenization is the #1 source of invisible errors
1. What is the core principle of the BPE algorithm?
2. Why does a larger vocabulary produce shorter sequences?
3. How does byte-level BPE guarantee that no text ever produces an unknown token?
4. A tokenizer trained on a 99 percent English corpus processes French text. What is the concrete consequence?