Tokenization
Human language exists as discrete, variable-length text strings governed by syntax, grammar, and morphology. Deep neural networks, conversely, are differentiable mathematical functions that operate strictly on continuous numerical vectors. The bridge between these two representations is tokenization.
The design of every tokenizer is governed by a fundamental tradeoff in sequence modeling:
- Character-Level Representation: Guarantees zero out-of-vocabulary (OOV) errors because every text decomposes into individual Unicode characters. However, it inflates sequence length by an order of magnitude. Because self-attention compute and memory scale quadratically () with sequence length , processing text character-by-character imposes a massive computational tax on every attention layer.
- Word-Level Representation: Keeps sequence lengths short and preserves obvious semantic units. However, human vocabulary is practically open-ended: proper names, technical jargon, slang, and typos are infinite. A fixed word vocabulary requires enormous embedding matrices () and inevitably fails when encountering unseen words at inference time.
Subword tokenization resolves this dilemma. By treating words as compositional sequences of high-frequency subword chunks, common words remain single tokens, rare words break down into familiar morphemes, and sequence length remains computationally efficient.
How Tokenization Works
Modern tokenizers transform raw text into integer tensors through three distinct phases:
Text-to-Tensor Tokenization Geometry ("understanding" → X ∈ R3 × d)
The BPE Algorithm Walkthrough
To see how Byte-Pair Encoding (BPE) constructs its vocabulary, consider building a tokenizer from scratch on a miniature training corpus consisting of four words and their frequencies:
1. Initial Character Vocabulary
We append a special end-of-word suffix </w> to each word to preserve word boundary information across merges. Each word starts split into individual character symbols:
l o w </w>(frequency: 5)l o w e r </w>(frequency: 2)n e w e s t </w>(frequency: 6)w i d e s t </w>(frequency: 3)
The base vocabulary contains all 11 unique symbols:
2. Counting Symbol Pairs
We scan the corpus and count all adjacent pairs of symbols:
| Adjacent Symbol Pair | Occurrences Across Corpus | Total Frequency |
|---|---|---|
e + s | 9 | |
s + t | 9 | |
l + o | 7 | |
o + w | 7 | |
w + e | 6 | |
n + e | 6 | |
w + </w> | 5 |
Both e + s and s + t share the top frequency of 9. Breaking ties deterministically, we merge e + s first:
- Merge Rule 1:
e + ses - Updated Corpus:
l o w </w>(5)l o w e r </w>(2)n e w es t </w>(6)w i d es t </w>(3)
3. Merging Most Frequent Pairs
Re-evaluating adjacent pair frequencies in the updated corpus:
es + tappears times.est + </w>then appears times.l + oandlo + weach appear times.
Applying these greedy merges in sequence produces five learned rules:
- Rule 1:
e + ses(freq 9) - Rule 2:
es + test(freq 9) - Rule 3:
est + </w>est</w>(freq 9) - Rule 4:
l + olo(freq 7) - Rule 5:
lo + wlow(freq 7)
4. Tokenizing Unseen Words
When the model encounters the previously unseen word lowest, it splits the word into base characters (l o w e s t </w>) and applies the learned merge rules in order, decomposing lowest into two root morphemes (low and est</w>) without throwing an unknown token error:
Byte-Pair Encoding (BPE) Subword Merge Simulator
Step through each merge rule to see how frequent adjacent pairs fuse into subwords and segment the unseen word lowest.
Practical Edge Cases & Realities
Byte-Level BPE & Zero Out-of-Vocabulary Tokens
Early BPE models operated on Unicode characters. If an input contained an unencountered emoji, rare mathematical symbol, or character from an unsupported script, the tokenizer emitted the destructive unknown token [UNK].
Modern frontier tokenizers (Tiktoken for GPT-4, LLaMA 3, Gemma) eliminate [UNK] completely using Byte-Level BPE:
- The base vocabulary is initialized with all 256 raw bytes ( through ) of the UTF-8 specification.
- Because every Unicode symbol decomposes into 1 to 4 UTF-8 bytes (for example, the emoji ✨ maps to UTF-8 bytes
0xE2,0x9C,0xA8), any input text is representable without fallback errors.
Numbers & Digit Splitting
Standard BPE trained on raw text merges numbers inconsistently:
1234might tokenize as12+3412345might tokenize as123+45123456might tokenize as1+234+56
This unpredictable chunking forces attention layers to waste capacity inferring decimal alignment before performing arithmetic. Modern models enforce regex pre-tokenization rules that split every individual digit into its own token, stabilizing mathematical reasoning.
Multilingual Fertility & Compute Cost
Tokenizer vocabularies trained predominantly on English corpora dedicate most entries to English morphemes.
- In English, fertility (tokens per character) is roughly 0.25 to 0.30 (~4 characters per token).
- In non-Latin scripts (Hindi, Arabic, Japanese, Telugu), text frequently splits into individual bytes, causing fertility to surge to 0.80 to 1.20 tokens per character.
This means non-English prompts consume to more tokens for the exact same semantic content, driving up API costs, inference latency, and memory consumption.
Comparing Modern Tokenizers
| Algorithm | Used By | Optimization Objective | Boundary Handling |
|---|---|---|---|
| Byte-Pair Encoding (BPE) | GPT-4, LLaMA 3 | Co-occurrence frequency () | Regex pre-tokenization with byte fallback |
| WordPiece | BERT | Likelihood of unigram language model | Explicit prefix marking (e.g. ##ing) |
| SentencePiece / Unigram | T5, Mistral | Prunes seed vocabulary via unigram loss | Treats whitespace as a standard symbol (▁) |