tokenizers 0.23.3; tiktoken 0.14.0); model probes measured on Apple M1 Pro (CPU). Data as of October 2026. Reading: 46 min, plus 15 in closed details.A tokenizer is a lossless compressor with a frozen dictionary: learned from a corpus before pretraining, it cuts text into pieces from a fixed vocabulary of V entries and hands the model their integer ids, so the vocabulary decides how many tokens every text costs, how large the model's input and output tables are, and what the model can see inside a word.
One sentence of the running story becomes 11 ids; the vocabulary sets three costs
Fig. 1 runs the running example's real tokenizer (4,096 entries, byte-level BPE trained on TinyStories) on a sentence of its running story, step by step in the list under "What a tokenizer does": the real bytes, the real pre-tokenizer, the real merges in the order the trainer learned them, the real ids and the embedding rows they select. Ids are laid out in the order the vocabulary was built: 0 the special token, 1 to 256 the bytes, 257 to 4,095 the merges in the order learned. Each id selects one row of the embedding table, and the tied output layer scores all 4,096 entries for every token.
You need: what an embedding and an output layer (unembedding) are; both are built from zero in The transformer from zero. This page owns the vocabulary that feeds them. The running example is the one of Topic: llm-architecture: the tiny GPT (6 layers, width 256, 5.84M parameters) reads TinyStories through a byte-level BPE of 4,096 tokens trained on TinyStories itself, and the running sequence is the 256-token opening of a held-out story about Roxy the rhinoceros (root src/data/README.md).
A modern tokenizer is four stages, each a separate object in the Hugging Face tokenizers library: a normalizer (optional cleanup such as Unicode NFC; the running example has none), a pre-tokenizer (cuts text into word-like chunks, and for byte-level BPE turns each chunk into bytes), the model (BPE: applies the learned merges inside each chunk) and a post-processor (adds special tokens such as a beginning-of-sequence marker). The decoder runs it backwards and gives back exactly the same text.
Three things to read off Fig. 1. A leading space is part of the next token (Ġloved is " loved"; byte-level BPE writes the space byte as Ġ so that every byte has a printable character). "Roxy" costs four tokens while " climb" costs one, because merges are learned from frequency and the name is rare in TinyStories. And id 0 is <|endoftext|>, a special token that the setup reserved before training to separate stories.
Where the ids go (steps 6 and 7): id i selects row i of the embedding matrix E (V × d = 4,096 × 256 in the tiny GPT), and the output layer multiplies the final hidden state by a V × d matrix to give one score (logit) per entry. The tiny GPT ties the two: the output matrix is the embedding matrix (Press and Wolf 2016).
Encoding with the running example's tokenizer (src/code/snippets.py, Hugging Face tokenizers 0.23.3), with its real output:
Where the tiny GPT ties its output layer to the embedding:
r|hin|o|cer|os. The running text's 874 characters become 255 tokens (3.43 characters per token), but rare words shatter: " rhinoceros" 5, " Roxy" and "Roxy" 4 each, " slippery" 3; every other word of the passage is 1 or 2 tokens. GPT-2's 50,257-entry vocabulary needs 228 tokens for the same text, Llama 3's 128,256 entries 222. A rarely seen word costs the model more positions, and the model must learn to assemble its meaning across them.The unit trades the size of the vocabulary against the length of the sequence. Word-level (historical): the vocabulary explodes for morphologically rich languages (every inflection is a new word), an out-of-vocabulary (OOV) word cannot be represented at all, and it needs word boundaries, which Chinese, Japanese and Thai do not write. Character-level: a tiny vocabulary and no OOV, but long sequences, so every text costs more compute, and each token carries little meaning. Byte-level: 256 ids, one per UTF-8 byte, so no text is ever unknown and no Unicode normalisation is needed, but a non-Latin character costs 2 to 4 bytes (ByT5 runs a model directly on them, see Beyond subwords). Subword-level, the compromise every modern LLM uses: frequent words stay whole and rare words decompose into meaningful pieces, which handles OOV while keeping the vocabulary manageable (32K to 262K entries in current models).
The same sentence costs 7 to 291 units depending on the unit and the language
The same FLORES-200 sentence in each language. Each bar is the sentence's UTF-8 bytes drawn to scale, cut where each method cuts; the number is how many units the model would have to process. Try Burmese: 7 words, but 291 bytes (3.7 times the English sentence's 78) and 285 GPT-2 tokens, nearly one per byte, against 52 for GPT-4o's tokenizer.
Words: split at spaces (Chinese and Japanese have none, so a whole clause counts as one "word"). Characters: Unicode code points. Bytes: UTF-8, which is what ByT5 reads (plus 3 special ids). Tokens: the real GPT-2 (r50k_base, 50,257 entries) and GPT-4o (o200k_base, 200,019) tokenizers run offline with tiktoken; sentence 366 of FLORES-200 dev + devtest (FLORES-200, CC BY-SA 4.0).
Byte-pair encoding (BPE) is a greedy answer borrowed from compression: start with the 256 byte values as the vocabulary, count every pair of adjacent symbols across the corpus, add the most frequent pair as a new symbol, rewrite the corpus with it, and repeat until the vocabulary has V entries. Every merge makes the corpus shorter by exactly the count of the pair it merged, so BPE is "merge whatever saves the most right now". The running example's tokenizer was trained exactly this way (min_frequency=2, the 256-byte alphabet, <|endoftext|> reserved as id 0). Fig. 2 runs the same algorithm, with the page's own trainer, on the running story alone, where every count is small enough to read:
Fig. 2 runs TOKALG.bpeTrain in the page, the library's BpeTrainer rule (most frequent pair, ties to the smaller ids), checked against the library itself (check_algos.mjs, 36 of 36). On all of TinyStories the first merges are the commonest pairs of simple English:
measured read from the committed tokenizer.json (sha256 7f08264c...). ␣ marks a leading space. Merge 7, " the", reuses merge 2 (" t") and merge 1 ("he"): later merges build on earlier ones, which is why the list is ordered.
How it runs in practice. The corpus is first pre-tokenized into words (no merge crosses a word boundary) and counted over distinct words weighted by frequency, so 477 million characters of TinyStories become a small table of word counts. The Hugging Face trainer keeps the candidate pairs in a priority queue ordered by count, breaks ties toward the pair with the smaller ids, refreshes counts that went stale, and stops at the target size or when no pair occurs at least min_frequency times. So the ids are laid out as 0 for the special token, 1 to 256 for the bytes and 257 to 4,095 for the 3,839 merges in the order they were learned.
Replay the merges yourself. The same 874 characters, from raw bytes to the full 4,096-entry vocabulary. Each chip is one token; outlined chips were created by the last merge. Predict how many tokens are left at 1,024 entries (a quarter of the vocabulary), then press a size or drag: the first merges ("he", " t", " a") halve the text fastest, "Roxy" stays four tokens to the end, and the last thousand merges barely move the count.
Replay the 3,839 merges on the running text: the first few hundred do most of the shortening
measured merges from the committed tokenizer.json, applied in the page lowest rank first inside each GPT-2 pre-token, as the library's merge_all does; at 13 checkpoints from 0 to 3,839 merges the page's ids equal the library's (src/check_grow.mjs against src/bpe/grow_check.py). Embedding = (257 + merges) × 256 parameters; share against the tiny GPT's 4,721,920 other parameters.
What the vocabulary size buys, measured. Retraining it on the same 529,875 stories took 30 seconds on 4 CPU threads of the M1 Pro and reproduced the committed file byte for byte (same sha256), so a BPE tokenizer is a deterministic function of its data and settings. Trained at nine sizes, it shows the trade the vocabulary makes:
Characters per token rise fast and then flatten: 256 bytes give 1.0, 4,096 entries 3.95, 16,384 entries 4.14, and the curve stops at 4.15, about the length of an average TinyStories word with its space, because a pre-tokenized word can never become less than one token. At 65,536 the trainer stops early, at 43,702 entries, when no pair occurs twice any more: TinyStories simply does not have 65,536 things worth a token. And the merge lists are nested: every smaller vocabulary's merges are exactly the first merges of the larger one (checked for all nine sizes), so "a 1,024 vocabulary" is just "stop after 767 merges", which is what the replay above uses.
Why the best size grows with the model. For a fixed model, the vocabulary moves compute two ways: fewer tokens per text (fewer passes through the blocks) against a bigger output layer per token (2 × V × d FLOPs). For the tiny GPT the total is lowest around 2,048 to 4,096 entries, the setup's choice; at 65,536 entries the output layer alone would be 3.5 times the blocks' FLOPs. Larger models have more FLOPs per token in their blocks, so the output layer is relatively cheaper and the best vocabulary grows: Tao et al. 2024 fit a scaling law and "predict that the optimal vocabulary size of Llama2-70B should have been at least 216K", seven times its 32K, published.
Embedding share = V × 256 / (V × 256 + 4,721,920 non-embedding parameters of the tiny GPT). FLOPs per validation pass = tokens × 2 × (4,721,920 + 256V): two FLOPs per weight per token, the tied output layer counted once as a V × 256 matmul.
Tao et al. also report ARC-Challenge rising "from 29.1 to 32.0 with the same 2.3e21 FLOPs" when going from a 32K to a 43K vocabulary published.
How to check a tokenizer you are given. Load its tokenizer.json, read model.merges (the first ones tell you what corpus it was trained on), print the pieces of a few strings from your own data, and measure characters per token on held-out text from your target distribution.
Characters per token flatten at about 4; the tiny GPT's compute is lowest at 2,048 to 4,096 entries
Nine tokenizers trained from scratch at 257 to 65,536 entries, measured on the 19.2M-character validation split. Top: characters per token. Bottom: the tiny GPT's FLOPs for one pass over the validation split, split into the blocks and the output layer. The red marker follows the merge slider above.
measured on Apple M1 Pro (CPU) token counts from src/bpe/bpe_sweep.py (tokenizers 0.23.3, 30 seconds per training run), each BPE trained on TinyStories train shard 0 and measured on the official validation split (never seen in training). derived FLOPs = tokens × 2 × 4,721,920 for the blocks and tokens × 2 × 256V for the tied output layer; attention scores omitted (about 0.8M FLOPs per token at the average position 128, the same at every V). Not run here: the tiny GPT's loss at each vocabulary, which needs a GPU training run per size.
BPE is one of three ways to learn a vocabulary from a pre-tokenized corpus (counting over distinct words with their frequencies). They differ in what they merge or remove, and in how they encode a new word:
| Method | Training: how the vocabulary is built | Encoding a new word | Unknown input | Used by |
|---|---|---|---|---|
| BPE | Start from characters; repeatedly merge the most frequent adjacent pair into a new token until the target size (Sennrich et al. 2016) | Apply the learned merges in the order they were learned | Falls back to characters; a character never seen is unknown | LLaMA 1 and 2 (LLaMA section 2.1), Mistral 7B (via SentencePiece) |
| Byte-level BPE | The same, over the 256 possible byte values instead of characters | Same | Impossible: every string is a byte sequence | GPT-2 onward, Llama 3 and 4, Qwen, DeepSeek, Kimi, gpt-oss, GLM, MiniMax, Olmo, Nemotron 3, and the running example |
| WordPiece | Same skeleton as BPE; merge the pair maximising freq(ab) / (freq(a) × freq(b)) | Greedy longest match from the left, ## marks a continuation | The whole word becomes [UNK] | BERT and its descendants |
| Unigram LM | Start from a large candidate set; prune the tokens whose removal hurts corpus likelihood least (Kudo 2018) | Most probable segmentation (Viterbi); can sample others | Characters, or bytes with byte fallback | T5, XLNet, ALBERT, mBART (HF course) |
| SentencePiece | A toolkit, not an algorithm: trains BPE or Unigram on raw text with the space as an ordinary symbol (Kudo and Richardson 2018) | That of the algorithm inside | Optional byte fallback | T5, LLaMA 1 and 2, Gemma 1 to 4 |
WordPiece (BERT) scores a pair by a likelihood ratio (pointwise mutual information up to a constant) rather than raw frequency, so a pair of common parts scores low even if it is frequent. Unigram runs the other way: fit a unigram language model (a word's probability is the product of its tokens'), then prune the tokens whose removal least hurts corpus likelihood, 10% or 20% at a time, never single characters; because it is probabilistic it can also sample other segmentations, which Kudo used as training-time augmentation ("subword regularization"). SentencePiece needs no pre-tokenization: it writes whitespace as the meta symbol ▁ (U+2581), so "Hello▁world." becomes [Hello] [▁wor] [ld] [.] and decodes losslessly by replacing ▁ with a space (SentencePiece section 3.1). Byte-level BPE, as GPT-2 implemented it, maps each byte to a printable character, which is why a space shows up as Ġ in vocabulary files and a Hindi character as two or three odd Latin symbols.
Train all three yourself. Each row is one distinct word of the corpus (×N is how often it occurs), cut into its current tokens; the outlined tokens were created by this step. The table shows the candidates the algorithm weighed. Predict whether WordPiece's first merge is the same as BPE's, then switch modes and step; Unigram starts from 300 candidates and only removes. Edit the text and retrain to use your own corpus.
On the Hugging Face course's four-sentence corpus, the page's WordPiece learns exactly the course's 25 new tokens (ab, ##fu, Fa, Fac, ... ##ut), its Unigram starts at the course's loss of 413.10 and tokenizes "This is the Hugging Face course." exactly as the course prints, and its BPE gives the same merges as the Hugging Face tokenizers library's own BpeTrainer. All three were checked on four corpora (36 of 36 comparisons identical, including accents, emoji, Cyrillic and Japanese; check_algos.mjs). The course's printed BPE list differs from the library's at ties, as the course itself notes: when two pairs are equally frequent the course takes the first one it meets, the library the one whose token ids are smallest. The library has no WordPiece trainer of its own (its WordPieceTrainer runs BPE with ## prefixes), and its Unigram trainer is SentencePiece's EM algorithm, so for those two the course's code is the reference; the page's Unigram is the course's simplified version (probabilities from substring counts, no EM re-estimation, exact removal losses).
WordPiece's original criterion was the language-model likelihood gain of each candidate unit (Schuster and Nakajima 2012); the frequency ratio above is the Hugging Face course's reconstruction, because "Google never open-sourced its implementation of the training algorithm" (course). So a WordPiece vocabulary trained with the library and BERT's original are built by different rules. BPE itself came to translation from compression with Sennrich, Haddow and Birch, to make the model "capable of open-vocabulary translation by encoding rare and unknown words as sequences of subword units".
Same corpus, three algorithms: BPE takes the most frequent pair, WordPiece skips frequent pairs of common parts, Unigram only removes
Defaults reproduce published lists, independently: the Hugging Face course's WordPiece tokens, its Unigram loss of 413.10, and the library's own BPE merges (36 of 36 comparisons identical; details below).
Training builds the vocabulary once; encoding runs on every request, and each method encodes differently. BPE replays its merges in the order learned (the library does it as "apply the lowest-ranked merge present, repeat", which gives the same result). WordPiece stores no merges, only the vocabulary, and takes the longest vocabulary entry that matches from the left; if any part of a word cannot be matched, the whole word becomes [UNK]. Unigram finds the segmentation with the highest product of token probabilities by dynamic programming (Viterbi). So the same vocabulary entry can be reached differently: the course's example vocabulary tokenizes "hugs" as hug ##s by longest match, while BPE replaying the same merges gives hu ##gs (course).
Try your own text. The corpus and sizes above. Words the corpus never contained show the difference best: WordPiece and Unigram cut a word they never saw differently from BPE, from the same corpus.
Encode any text with the three tokenizers you just trained
Before any of this, production tokenizers run a pre-tokenizer, usually a regular expression, and its rules matter as much as the vocabulary. GPT-2's pattern, which the running example's ByteLevel pre-tokenizer uses by default:
Read it left to right: English contractions, then an optional space followed by a run of letters (so " Roxy" is one chunk with its space), an optional space and a run of digits (any length), an optional space and a run of punctuation, then whitespace. Every later tokenizer edits this pattern: GPT-4's cl100k caps digit runs at three, Qwen and Nemotron 3 cut single digits, Kimi gives Chinese characters their own runs. What those edits do to numbers and code is under Numbers and code.
"Apply the lowest-ranked merge present, repeat" with a priority queue over the adjacent pairs of one pre-tokenized word (rank = the merge's position in the learned list):
A larger vocabulary means fewer tokens per text (fewer tokens to run, more text per context window) and makes every token more expensive at the edges of the model: one more embedding row and one more output row per entry, and an output softmax that scores every entry. Nothing in the blocks changes. So the vocabulary matters most where the blocks are small: in small models, and in mixture-of-experts models, where few weights run per token.
src/data/README.md).Fig. 4: length in proportion to parameters, one strip per model, input table on the left, output table on the right (one table when tied). derived for the tiny GPT (V × 256 against its 4,721,920 other parameters); the others are the root's Config calculator results (below).
Any small model. Defaults reproduce Gemma 3 270M's published split, independently: "170 million embedding parameters ... and 100 million for our transformer blocks" (Google; 262,144 × 640 = 167.8M embedding parameters of 268.1M, leaving 100.3M, reproduced from its config). Predict the share at a 32K vocabulary and the same width, then drag.
In a small model the vocabulary is most of the weights
All 45 configs. What the input and output tables cost in the 45 configs of the root's Config calculator, three ways: share of all parameters, share of the parameters active per token, and the output layer's share of decode FLOPs per token. Predict what happens to gpt-oss-20b when you switch from total to active, then switch (it goes from 6% to 28%; the mixture-of-experts models are orange).
In dense models the table's share falls with size, because it grows with width only (Qwen3-0.6B 26%, Llama 3.1 8B 13%, Llama 3.1 405B 1%). Mixture-of-experts models break the pattern: the table is a tiny share of their total weights but a large share of what each token actually uses, because only a few experts run per token while the whole output layer runs every time. In gpt-oss-20b the input and output tables are 28% of the active parameters and the output layer is 16% of the decode FLOPs per token; in DeepSeek-V3 5% and 2.5%. Whoever designs a sparse model with a 200K vocabulary pays for it on every token.
Table = V × d for the input embedding plus V × d for the output layer when untied. Output-layer FLOPs = 2 × V × d, as a share of the calculator's decode FLOPs per token at context 1. A 1B-parameter model with a 256K vocabulary and width 2,048, tied: 256K × 2,048 = 537M, about half of 1B, and an output layer of 2 × 256K × 2,048 = 1.07 GFLOPs per token, about half of the forward pass (2 GFLOPs); Gemma 3 1B is close to this (262,144 × 1,152 = 302M, 30% of 1.0B, from the root's Config calculator).
Dense models: the table's share falls with size. Mixture-of-experts: it is a large share of what each token uses
derived from the Config calculator (on Topic: llm-architecture)'s recorded results (src/calc/out/py_results.json, validated to residual 0 against the Hub's stored-tensor counts; read 2026-10-18), by src/vocab/calc_embed.py: tables = V × d, doubled when untied; vision towers and MTP layers excluded, as in the calculator; decode FLOPs at context 1 (the embedding lookup costs no FLOPs), sorted by total parameters. Share of active: the calculator's "all" accounting, embedding included, routed experts scaled by k/E.
Config vocab_size is not the tokenizer's size. Configs pad the embedding matrix up to a round number so that the matmul tiles well on GPU tensor cores (pad_to_multiple_of in transformers); the extra rows are never produced by the tokenizer, yet still cost parameters and output FLOPs. Qwen3's config says 151,936 rows for 151,669 tokenizer entries (267 rows never used), DeepSeek-V3's 129,280 for 128,815, Llama 4's 202,048 for 201,135 measured (entries counted from each tokenizer.json with added tokens). Count len(tokenizer), not the config.
A second trap: tying is a config flag, not a file layout. Qwen3-0.6B sets tie_word_embeddings true, yet its safetensors also store a separate lm_head (751.6M stored against 596.0M in memory; root FACTS).
Adding tokens to a trained model (new special tokens for a chat format, a domain's frequent words) adds rows that start untrained. resize_token_embeddings in transformers 5.20.1 initialises them to the mean of the old rows by default (mean_resizing=True), which keeps the first forward pass sane; they still need fine-tuning before the model uses them well. Replacing a tokenizer outright throws away what every embedding row learned.
Read from each open model's own tokenizer file (downloaded 2026-10-18, revisions in src/tok2026/fetched.json, read with tokenizers 0.23.3), three patterns hold:
On the same English text (FLORES-200, 259,170 characters) every tokenizer except Llama 2's, from GPT-2's 50K to Gemma 3's 262K, lands between 4.82 and 4.96 characters per token; across all 204 FLORES languages the total falls from 47.4M tokens (GPT-2) to 22.6M (GPT-4o) and 20.6M (Gemma 3).
Llama 3 reports its English compression rising "from 3.17 to 3.94 characters per token" over Llama 2's 32K SentencePiece vocabulary, a 24% gain on Meta's own sample (Llama 3 section 3.2); on FLORES English the same two tokenizers give 4.28 and 4.91, a 15% gain (different text, so the absolute numbers differ). Llama 3's tokenizer is "100K tokens from the tiktoken tokenizer with 28K additional tokens to better support non-English languages" (same section), and its regex (digits in threes) is the one Llama 4, SmolLM3 and others inherited.
The full inheritance list: DeepSeek-V4-Flash and V4-Pro keep V3's 128,000 ordinary tokens (128,815 to 129,280 entries); Gemma 4 keeps 262,125 of Gemma 3's entries; GLM-5.3 equals GLM-5; MiniMax-M3 equals M2 apart from added specials; Olmo 3 equals OLMo 2; SmolLM3 uses Llama 3's tokenizer; Qwen3.5-397B equals Qwen3.5-0.8B. Gemma 1 and 2 already used 256,000 entries, Gemma 3 and 4 use 262,144.
Entries are what the tokenizer can emit (ordinary tokens plus special tokens); config is the padded vocab_size of the model; digits is how the string 12345678 is cut; shared is how many ordinary entries are identical to the predecessor's.
measured from the files (src/tok2026/analyze.py). "BPE, bytes" = byte-level BPE (GPT-2's byte mapping); "BPE, byte fallback" = SentencePiece-style BPE on characters that falls back to 256 byte tokens for anything unseen (Gemma). NFC = the tokenizer normalises Unicode to composed form first, so two encodings of "é" give the same ids. Kimi K3 ships a tiktoken file (163,584 ranked tokens) and reserves 256 special ids in tokenization_kimi.py, 163,840 in all, its config's size exactly. Closed models (GPT-4o, GPT-5: o200k_base, 200,019 entries in tiktoken 0.14.0) and gpt-oss (o200k_harmony, 201,088, gpt-oss model card section 2.3) are in the Vocabulary timeline tab.
Bigger vocabularies barely shorten English; the other 203 languages carry almost all the saving
Tokens for the same text against vocabulary size, for the ten tokenizers of the Same text, ten tokenizers tab, relative to GPT-2. Try switching to one language.
The problem. BPE learns pieces from frequency, so without a rule it cuts numbers wherever the training data happened to make merges: GPT-2 has " 2024" as one token but cuts 12345678 as 123|45|678, so the same digit can sit at different positions inside different tokens, and the model has to learn place value separately for every way a number can be cut. Every tokenizer since has added a digit rule to the pre-tokenizer, and they disagree: groups of up to three from the left (GPT-4's cl100k, GPT-4o's o200k, Llama 3 and 4, DeepSeek-V3 and V4, MiniMax, OLMo 2 and Olmo 3, Kimi K3: 123|456|78) or every digit alone (LLaMA 1 and 2, Gemma 1 to 4, Qwen3, Qwen3.5, Nemotron 3 Super, SmolLM2: 1|2|3|4|5|6|7|8).
| Tokenizer | Digit rule | "12345678" becomes | Source |
|---|---|---|---|
| GPT-2 (r50k_base) | Any run of digits, then BPE merges inside it | 123|45|678 | GPT-2 encoder.py (pattern ?\p{N}+) |
| GPT-4 (cl100k), GPT-4o (o200k), Llama 3 and 4, DeepSeek-V3 and V4, MiniMax, OLMo 2 and Olmo 3, Kimi K3 | Groups of 1 to 3 digits, from the left | 123|456|78 | Pattern \p{N}{1,3} in tiktoken and the models' tokenizer.json |
| LLaMA 1 and 2, Gemma 1 to 4, Qwen3, Qwen3.5, Nemotron 3 Super, SmolLM2 | Every digit on its own | 1|2|3|4|5|6|7|8 | "we split all numbers into individual digits" (LLaMA section 2.1); Gemma "splits digits" (Gemma section 4.1, Gemma 3 section 2.2; Gemma 4 measured here); Qwen pattern \p{N} (tokenizer.json) |
Read from each tokenizer's pattern and checked by encoding 12345678 with the real files (src/tok2026/analyze.py). The running example's TinyStories BPE learned no merges between digits at all (numbers are rare in the stories), so it cuts every digit too, by accident rather than by rule; GLM-5 is the odd one out: its pattern allows three digits but its vocabulary has only 177 of the 1,000 three-digit tokens, so 12345678 becomes 123|45|6|78 (the pattern allows a chunk the vocabulary does not have).
Why left-to-right chunks hurt. Addition works from the right. With chunks of three from the left, 12345 becomes 123|45 and 6789 becomes 678|9: the units digits of the two numbers sit in different positions of different tokens, and the answer's chunks do not line up with either. Writing the number with thousands separators (12,345) forces chunks of three from the right, aligned with place value. Singh and Strouse 2024 showed on GPT-3.5 and GPT-4 that right-to-left tokenization "enforced by comma separating numbers at inference time" "leads to largely improved performance", and that the gap shrinks with model size published.
Chunks of three from the left misalign place value; commas and single digits keep it aligned
The same sum under three digit rules, chunks drawn as boxes under the digits they cover, units column on the right. Try 99999 + 1: plain chunking puts the carry into a token boundary that moves.
Same model, same problems: commas alone raise OLMo 2 1B's exact answers
The same 100 problems, written two ways: the model's real answers, digits compared right-aligned with the truth (green right, red wrong). Try switching between the model whose tokenizer chunks digits in threes and the one that splits every digit.
measured on Apple M1 Pro (CPU) src/probe/arith.py, bf16, greedy, 16 new tokens, the same 8 shots and 100 problems (seed 0) in both formats; OLMo-2-0425-1B at revision a1847dff, Qwen3-1.7B (the post-trained model, prompted as plain text, no chat template) at revision 70d244cc. What transfers: the direction of the effect and that it comes from the tokenizer (the problems and the model are identical between the two columns). What does not: the absolute accuracies, which are those of 1 to 2 billion parameter models on few-shot addition.
So on OLMo 2 1B: 3% exact plain against 19% with commas, digit accuracy 39% against 71%, with nothing changed but how the numbers are written. Single-digit tokenizers (Qwen, Gemma) avoid the misalignment at the price of longer numbers.
Code. Code is mostly whitespace, punctuation and identifiers, and a tokenizer trained on prose wastes tokens on it. The running example's tokenizer is the extreme case: it never saw code, so the 91-character Python function below costs 64 tokens (" total" is to|t|al, an indent is four single spaces) against 45 for GPT-2 and 28 for Llama 3, whose tokenizer has tokens for runs of spaces and for ):\n. Gemma keeps an 8-space indent as one token; byte-level tokenizers of the Llama 3 family attach the last space of an indent to the next word (' ', ' return').
GPT-2 has no tokens for runs of spaces, so each four-space indent costs three single-space tokens before the fourth space joins the next word (45 tokens for the snippet against 28 for GPT-4's cl100k, which added whitespace-run tokens for code); the Same text, ten tokenizers tab runs the snippet through all ten tokenizers.
A tokenizer that never saw code spends 64 tokens on 91 characters of Python
measured src/bpe/inspect_bpe.py: the same snippet through four real tokenizers, pieces alternately shaded, spaces shown as dots.
Fertility is tokens per word, and the related premium is how many tokens a language needs for the same content relative to English: "The ratio |t(sA)| / |t(sB)| is the premium for A relative to B", measured on translations of the same sentences (Petrov et al. 2023 section 3). It varies wildly: GPT-4's tokenizer "uses about 1.6 times more tokens to encode the same text in Italian as it does in English, 2.6 times for Bulgarian and 3 times for Arabic. For Shan ... that difference can be as high as 15 times." A premium is both a cost (APIs bill per token, latency grows with length, less content fits in the context window) and a quality issue (the model sees each word as more, less meaningful pieces). Byte-level is not neutral either: "byte-level representation of the same text is over 4 times longer for Burmese or Tibetan than Chinese."
The tax depends on the tokenizer more than on the language: Tamil falls from 15.6 times English to 2.0
Premium against English for six languages, four generations of tokenizer, over the whole FLORES-200 dev and devtest (2,009 sentences per language). Premium = tokens for the language ÷ tokens for English over the same 2,009 translated sentences (dev and devtest, the construction of Petrov et al.), per tokenizer; 1.00× is parity. The row lengths are the one sentence's real token counts. Defaults reproduce Petrov et al.'s published token counts exactly, independently: 204 of 204 languages for GPT-2's r50k, GPT-4's cl100k, Llama 2, ByT5's bytes and UTF-32 characters, from the FLORES-200 release with the paper's own construction (their code and table). The other columns extend it to newer tokenizers.
Across all 204 languages, the median premium is 2.26 with GPT-4's cl100k and 1.75 with GPT-4o's o200k; 65 languages pay more than 3 times English with cl100k, 15 with o200k and 8 with Gemma 3. So "low-resource languages pay 3 to 5 times more" is true for some tokenizers and some languages, and the size of the tax depends on the tokenizer far more than on the language: Tamil drops from 7.65 with Llama 3 to 1.46 with Gemma 3. OpenAI's GPT-4o launch listed the gain for 20 languages (Gujarati "4.4x fewer tokens (from 145 to 33)"); the Same text, ten tokenizers tab recomputes all 20 sentences (18 reproduce exactly) and lists every one of the 204 languages. So never compare token counts or per-token prices across models as if a token were a fixed amount of text: compare per character or per word of your own text. When choosing a tokenizer for domain adaptation, measure the fertility on your own text: a tokenizer trained on a different distribution can make the same budget of tokens carry much less of your data.
The model never sees characters, only ids, so anything that depends on the characters inside a token, on where a token boundary falls, or on a token it rarely saw in training has to be learned indirectly, and often is not. First the mechanism on ten real tokenizers, then what real models do.
Every failure below starts as a token boundary or a token the model rarely saw
Byte-level tokenizers glue a space to the following word (" Paris" is one token), so a prompt ending in a bare space ends on a lone space token, which in training text is almost never followed by a word token. The model has to recover from a boundary it rarely saw. Before and after, same model, same prompt, one trailing space:
Keep prompts in the form the model was trained on: never end a completion prompt with a bare space, and do not strip or add one without checking the template.
One trailing space changes the next-token distribution and the continuation
measured on Apple M1 Pro (CPU) src/probe/space_letters.py: next-token probabilities after the last prompt token, and 12 greedy tokens. SmolLM2-135M revision 93efa2f0 in fp32; the tiny GPT is the root's ref_baseline_s1500 checkpoint. What transfers: every byte-level tokenizer behaves this way (the space joins the next word); large models recover more often, which is why APIs and chat templates strip or control trailing whitespace. Libraries offer "token healing" (back up one token and constrain the next to start with the removed text) for this exact problem.
" strawberry" is one token in nine of the ten tokenizers of the Same text tab. Counting its r's means knowing the spelling of token 73700 (cl100k), which the model can only have memorised from rare text that spells words out. Writing the word with spaces between letters turns it into one token per letter, so the letters become visible. Whether the model can then count them is a separate question, and the measurement below separates the two.
Qwen3-1.7B is right on 13 of 24 written normally and 14 of 24 spelled out, and "strawberry" is wrong (2) both ways. Tokenization explains why the question is hard for a model that never sees letters, but removing that obstacle does not make a small model a reliable counter; reasoning models get it by spelling the word out and counting step by step in their output.
Spelling the word out makes the letters visible but barely helps a 1.7B model count them
measured on Apple M1 Pro (CPU) src/probe/letters.py: Qwen3-1.7B (revision 70d244cc, bf16, greedy, 4 new tokens), three worked examples then "How many times does the letter "r" appear in "strawberry"?", once with the word as written and once spelled "s t r a w b e r r y". Pieces = how Qwen3's tokenizer cuts the word. A first attempt asked Qwen3-0.6B through its chat template for "a number only"; it answered with explanations ("The letter "r" appears **once**...") that 24 new tokens cut off, a format failure kept in out/space_letters.json and replaced by this few-shot version.
A vocabulary is trained once and a model is trained afterwards, often on different data. Entries that are in the vocabulary but nearly absent from the model's training data get almost no gradient as inputs, and as outputs they are only ever pushed down. Land and Bartolo 2024 call these "tokens present in the tokenizer vocabulary but that are nearly or entirely absent during model training" and found them "across a diverse set of models"; GPT-2's " SolidGoldMagikarp" (id 43453, in the gallery above) is the famous one. The running example has its own, measured:
132 of the 4,096 entries never occur in the 122M training tokens, of two kinds: 122 byte tokens for bytes TinyStories almost never contains (@, ^ and most non-ASCII bytes), and 10 intermediate merges such as " underst", " butterf" and "aghet", tokens the trainer created on the way to " understand", " butterfly" and "aghetti" that every later encoding merges further, so they never survive as final tokens. All of them ended training pointing the same way (their rows have cosine similarity 0.996 with each other, against 0.024 among the 200 commonest tokens) and with norms more than twice the typical row, because the only gradient they ever got was "do not predict me". Fed one of them, the model loses the thread. How to check a real model: count each id in a sample of its training data if you have it; otherwise look for embedding or output rows that cluster together or have unusual norms, then confirm by prompting the model to repeat the token, the indicators Land and Bartolo combine.
The 132 entries never seen in training (red) end with large norms, all pointing the same way
measured on Apple M1 Pro (CPU) src/bpe/freq_glitch.py: how often each of the 4,096 ids occurs in the 122M training tokens (train.bin), and the norm of each row of the trained tiny GPT's tied embedding (ref_baseline_s1500). Continuations are greedy, 25 tokens, after "Once upon a time, there was a little" plus one token.
Inspect any string. Type any text. Try "understand" against " understand", or a word with an accent. Pieces follow the merge slider of the BPE section (all 3,839 merges unless you moved it).
Inspect any string: its pieces, how often each occurred in training, and its row norm
Training counts and norms belong to the full 4,096-entry tokenizer and the ref_baseline_s1500 checkpoint (src/bpe/freq_glitch.py); with fewer merges a piece may not exist in that model. Red: never seen in training.
Special tokens (beginning and end of sequence, chat roles, tool-call markers, padding) are reserved ids added on top of the learned vocabulary, after it is trained, and they never come out of the merge procedure: the tokenizer matches them as whole strings before ordinary encoding. If a template marker is not registered as special, it is just text and costs ordinary tokens: <|user|> is five tokens in eight of the ten tokenizers here and four in Gemma 3 and Llama 4. Tulu 3's template is in exactly that situation, as the Alignment page shows token by token while explaining which tokens carry the SFT loss. Chat-template mismatches between training and inference (a different role marker, a missing end-of-turn token, a template applied twice) are a common silent bug in fine-tuning: the model trains fine and then behaves oddly at serving time. A shared tokenizer is also what makes logit-level distillation possible: a student can only match a teacher's distribution token by token if both have the same vocabulary; with different tokenizers, distil on sampled text or use a method built for mismatched vocabularies (Distillation and Small Language Models).
The first trap: a tokenizer parses special-token strings found inside user text as the special tokens themselves unless told not to. Without split_special_tokens=True, "hi<|im_end|>" becomes 2 ids, the second being Qwen3's real end-of-turn token (151645), so typed text can close a chat turn; serving stacks that template untrusted text must split or escape it. The same run shows Qwen3's len(tok) (151,669, with the 26 added tokens) against vocab_size (151,643, the base vocabulary), and neither is the config's 151,936.
The second trap: a chat template that already writes <bos>, rendered to a string and then tokenized with the default add_special_tokens=True, starts [2, 2, 105], two beginning-of-sequence tokens; letting apply_chat_template tokenize gives [2, 105, ...]. Nothing errors and the model still answers, slightly off distribution. Fix: tokenize with the template, or pass add_special_tokens=False; check by printing the first ids of every training and serving example once and comparing them with the template's own tokenization.
Two silent traps, before and after the fix: the same input, different ids
Predict for each trap what the default call produces, then switch. Ids are the real outputs of src/code/snippets.py (transformers 5.20.1); shaded ids are special tokens, outlined ones are the bug.
Tokenizer-free and byte-level research keeps resurfacing but has not displaced subword BPE in production. Raw bytes remove the tokenizer and its failure modes but make sequences about 4 times longer (ByT5). Patches fix the length: MegaByte groups bytes in fixed patches of 8, and the Byte Latent Transformer (BLT, Meta, December 2024) starts a new patch where a small byte model finds the next byte hard to predict, so predictable stretches become long patches and the large model takes fewer steps: it "matches training flop-controlled performance of Llama 3 while using up to 50% fewer flops at inference". SuperBPE (2025) goes the other way and lets tokens cross spaces ("by the way" as one token), up to 33% fewer tokens than BPE at 200K entries.
Entropy patches give the large model fewer, longer steps than BPE tokens
One sentence, six ways to cut it, drawn to scale in bytes. Three rows (space and the two entropy rules) are transcribed from Figure 3 of the BLT paper, because the small entropy model that draws the boundaries cannot run in this page; the bytes and 4-byte strides are computed, and the BPE row is the real Llama 3 tokenizer, run offline. The step list below walks the six rows; the counter is how many steps the large model takes.
Sentence and patchings from BLT Figure 3; spaces are attached to the following patch, as in the strided row, which only adds up with them. The figure's BPE row reads Da|ener|ys where the real Llama 3 tokenizer gives Da|enery|s; both are 23 tokens.
Use the Hugging Face tokenizers library or SentencePiece on a corpus that matches your target distribution: the vocabulary is frozen with the model, so the languages, scripts, code and number formats you care about must be in the tokenizer's training data. Decide the pre-tokenization rules (digits, whitespace runs, code) before training, reserve special tokens for your chat template, and measure fertility on held-out text in every language you will serve. Where the training corpus comes from and how it is filtered is the subject of Topic: data-curation-and-datasets. A model fine-tuned on a new domain or language with an old tokenizer pays the old tokenizer's rate on every token: the running example's TinyStories BPE needs 64 tokens for a 91-character Python function and 3 tokens per Chinese character (one per byte), where Llama 3's needs 28 and about 1, and its rarely used entries may be glitch tokens. Changing the tokenizer of a trained model means new embedding rows that start untrained, so extending a vocabulary (Llama 3 added 28K entries to tiktoken's 100K before training, not after) is far easier than swapping one.
The running example's tokenizer is a complete, minimal recipe: the closed block below holds the training part of the root's src/data/prepare_data.py, as rerun by src/bpe/bpe_sweep.py, with that run's printed result.
Settings worth knowing: initial_alphabet=ByteLevel.alphabet() puts all 256 bytes in the vocabulary even if the corpus lacks some (without it, a byte never seen in training could not be encoded); min_frequency stops training early on a small corpus (43,702 entries instead of 65,536 here); special tokens are listed up front so they get the first ids and are never split.
Every tokenizer here was run offline on the real vocabulary files: GPT-2's r50k_base, GPT-4's cl100k_base and GPT-4o's o200k_base through tiktoken; Llama 2, Llama 3, Llama 4, Qwen3, Qwen3.5, Gemma 3 and DeepSeek-V3 through the Hugging Face tokenizers library with each model's tokenizer.json (mirrors for the gated Meta and Google repositories), no special tokens added. Text: FLORES-200, the same 2,009 sentences professionally translated into 204 languages (FLORES-200, CC BY-SA 4.0).
Pick a language. Alternating colours mark token boundaries; ␣ is a space, ‹e1 80› is a token that holds only part of a character's bytes. The ratio is against the same sentence in English with the same tokenizer. Try Tamil, then Python code.
The premium of every FLORES-200 language over the whole dev and devtest (the construction of Petrov et al.: all 2,009 sentences joined by spaces). Choose two tokenizers to compare. Try GPT-4 against GPT-4o, then Llama 3 against Gemma 3.
At the GPT-4o launch OpenAI listed 20 languages "chosen as representative of the new tokenizer's compression across different language families", each with one sentence and its token count before (cl100k_base) and after (o200k_base) (Hello GPT-4o, archived 13 May 2024). The sentences below are copied from the page, typos included, and re-tokenized here.
Every model's vocabulary on one axis: what the Reading tab says about sizes (32K in 2023, 128K to 262K now; families keep theirs) seen across 41 models. What each size costs and saves is in the Reading tab's vocabulary-size and current-models sections.
41 models, 2018 to 2026 (eight 2026 models added from the root's map configs on 2026-10-18), vocabulary size on a log axis. Click a point or a table row for its configuration. Try the Qwen family: 152K from Qwen-7B (2023) to Qwen3 (2025), then 248K with Qwen3.5 (2026).
Vocabulary = vocab_size in each model's config.json on Hugging Face (fetched 3 October 2026, the 2026 additions 18 October 2026; padded, see the Reading tab's vocabulary-size section), or the tiktoken encoding size for OpenAI's closed models. Date = the paper or announcement for the 2018 to 2020 models, LLaMA and the closed models; for the others, the day the Hugging Face repository was created, a proxy for the public release of the weights (the official repository where it is not gated, otherwise the named mirror).
Links open in a new tab. Times are estimates: for knowledge base pages, the Reading tab's word count at 230 words a minute.
From zero on the running example: the pipeline, units, BPE as trained on TinyStories with its 3,839 merges replayed and nine sizes costed, WordPiece and Unigram trained live, encoding, vocabulary size against parameters and compute (with a calculator), 2026 tokenizers read from their files, numbers and code, the language tax, failure modes with real outputs and a string inspector, special tokens, beyond subwords.
One sentence in twenty languages and code, token by token; all 204 FLORES-200 languages; OpenAI's GPT-4o table recomputed.
Vocabularies of 41 models from 2018 to 2026 on one axis, each with its configuration and source.
The parent: one token through one block, then every component's alternatives and costs; its Config calculator and Architecture map tabs supply this page's parameter numbers.
The embedding and unembedding this vocabulary feeds, built from an empty file, and the tiny GPT trained.
The other half of how the input is represented: where each token sits.
Why tokens per text matter at 128K: KV cache growth and effective context.
Why a few active experts make the vocabulary's share of active parameters large.
Encoders, encoder-decoders and multi-token prediction heads, each with its own output layer over the vocabulary.
Vocabulary sizes beside every other architectural setting, per config.
Training stages compared; the tokenizer is fixed before pretraining.
Token budgets and data mixtures, all counted in a tokenizer's units.
A chat template token by token and which tokens carry the SFT loss.
What happens to the logits over the vocabulary at every step, including constrained decoding.
Logit distillation needs a shared vocabulary; small models where the table is a large share.
The corpus a tokenizer is trained on, and how it is filtered.
The labs and models whose tokenizers are compared here.
The 128K vocabulary: tiktoken's 100K plus 28K for other languages. (about 31 min)
The WordPiece model at work, with a toy BERT. (about 23 min)
Exact r50k_base token counts for its in-context examples. (about 21 min)
A SentencePiece vocabulary and the sentinel tokens of span corruption. (about 23 min)
Byte-level BPE from scratch; the best single explainer. (2h 15m)
The code from the video, with exercises. (repo, 30m)
BPE, WordPiece and Unigram with worked algorithms; the reference code this page's trainers reproduce. (1h 30m)
Lossless, language-agnostic tokenization. Short and readable. (45m)
The Unigram model and subword regularisation. (45m)
OpenAI's production BPE; the encodings and their regexes. (repo, 20m)
The library behind most open models' tokenizer.json files. (repo, 30m)
The premium, measured on FLORES-200 for 17 tokenizers; reproduced exactly here. (40m)
Entropy patches instead of tokens. (1h)
Tokens that cross spaces. (40m)
Digit grouping direction and arithmetic. (30m)
The glitch-token discovery. (20m)
Larger models deserve larger vocabularies: a compute-optimal vocabulary fit. (45m)
Finding under-trained tokens in any model. (40m)
A T5 on raw bytes. (45m)
The parallel sentences behind every multilingual count here. (5m)
First built on 3 October 2026 from the Notion page of 20 September 2026 (5 min read), rebuilt on 18 October 2026 under Topic: llm-architecture on its running example. Scripts and recorded outputs are in the repository under src/: bpe/ (the running example retrained, inspected, frequencies and glitch tokens), probe/ (arithmetic, trailing space, letters on real models), tok2026/ (2026 tokenizer files), vocab/ (the Config calculator's shares), code/ (quoted source and snippets), tok_data.py and ref_algos.py (ten tokenizers, FLORES-200, Petrov check, the three trainers). Links checked 2026-10-18.