Tokenizers

How text becomes the integer ids a transformer reads, and what the vocabulary costs, on the running example of Topic: llm-architecture (its own 4,096-token byte-level BPE) beside ten real tokenizers. Token counts computed offline with the real tokenizers (Hugging Face 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.

The idea in one screen

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).

Token, vocabulary, id
a piece of text; the fixed list of all pieces (V entries); a piece's position in that list.
Merge (BPE)
one learned rule "these two adjacent tokens become one new token"; a BPE vocabulary is 256 bytes plus its merges in order.
Pre-tokenizer
a fixed rule (usually a regular expression) that cuts text into chunks no token may cross.
Byte-level
the base alphabet is the 256 byte values, so no text is ever unknown.
Special token
a reserved id (end of text, chat roles, tool calls) matched as a whole string, never learned by merging.
Chat template
the rule that writes a conversation as one string of special tokens and text.
Premium
how many tokens a language needs for the same content relative to English.
Glitch token
a vocabulary entry the model almost never saw in training, so its row stayed untrained.

What a tokenizer does

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.

  1. The text. "Roxy loved to climb the icy hill.": 33 characters. The model cannot read characters; everything that follows turns them into a short list of integers and back.
  2. UTF-8 bytes. Byte-level BPE starts from bytes, so no input is ever unknown: 33 bytes, each one of the 256 base tokens (ids 1 to 256). A non-Latin character would be 2 to 4 bytes.
  3. Pre-tokenize. GPT-2's regex (quoted under Encoding) cuts the bytes into 8 chunks; a space travels with the word after it, and no merge may cross a chunk boundary.
  4. Merge inside each chunk. The learned merges apply lowest rank first: " loved" takes five merges, " the" three (merges 1, 2 and 7). Predict what happens to "Roxy" before it plays: the trainer never learned a merge for it, so it stays four byte tokens (orange); the full stop is a single byte too. 11 tokens.
  5. Ids. 11 integers, [50, 79, 88, 89, 505, 266, 1014, 263, 3183, 1443, 14]: 33 bytes compressed 3.0 times. These integers are all the model receives.
  6. Embedding rows. Each id selects one row of the 4,096 × 256 embedding matrix, so the model's input is an 11 × 256 array. "Roxy"'s four rows sit in the byte region at the front; " icy" (3183) was learned late.
  7. Output layer, tied. After the six blocks, the same matrix scores all 4,096 entries for the next token: 2Vd = 2.10M FLOPs per token. Decoding runs the other way, ids to bytes to text, exactly: decode(encode(text)) == text, which the library guarantees for byte-level BPE.

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).

The code that ran, and the tying in the tiny GPT (provenance)

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:

Predict: the running story mentions Roxy the rhinoceros eleven times. How many tokens is " rhinoceros" (with its leading space) in the running example's 4,096-entry vocabulary?

Words, characters, bytes, subwords

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).

A trick from the huge-vocabulary era: negative sampling (history)
word2vec avoided the cost of a softmax over the whole vocabulary by turning prediction into a binary classifier: tell the real (word, context) pair apart from a few sampled noise words, "k in the range 5 to 20 ... for small training datasets, while for large datasets the k can be as small as 2 to 5" (Mikolov et al. 2013 section 2.2). It existed purely to avoid the full softmax. LLMs simply pay for the full softmax over 32K to 262K entries, but the idea lives on in contrastive objectives: InfoNCE, whose minimisation "maximizes a lower bound on mutual information" (van den Oord et al. 2018 section 2.3), and the training of embedding models such as CLIP.

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).

BPE from zero, on the running example

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:

  1. Bytes. The running story's opening is 874 bytes; the sentence of Fig. 1 is 33 of them. The vocabulary is the 256 byte values, and the pre-tokenizer has already cut the text into words, so no merge crosses a word.
  2. Count, merge the most frequent. The trainer counts every adjacent pair over the story: " a" 22 times, " t" 21, "he" 19. " a" becomes entry 257 and every occurrence is rewritten, so the story shrinks by exactly 22, to 852 symbols (the sentence has no " a").
  3. Recount, repeat. The counts change after each merge; " t" (21) and "he" (19) come next, and the sentence's " to" and " the" start to fuse: 812 symbols, 259 entries.
  4. Merges 4 to 10. " s", "ll", "nd", "ill", "ed", "li", " i": later merges build on earlier ones ("ill" is "i" + "ll"). 718 symbols.
  5. Merges 11 to 13: "Roxy". This story says Roxy 11 times, so "R" + "o", "x" + "y" and then "Ro" + "xy" win: "Roxy" becomes one token. 685 symbols.
  6. Merges 14 to 32. " climb", " to", " the", " hill" and " icy" become whole tokens; the story is down from 874 to 542 symbols and the sentence to 12 tokens.
  7. The corpus decides. The real tokenizer, trained the same way on all 477 million characters of TinyStories, has every word of the sentence whole except "Roxy", which never earned a merge there (four byte tokens, orange): 11 tokens. Same algorithm, different corpus, different vocabulary.

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.

The trainer's ordering and main loop, quoted (tokenizers v0.23.3, trainer.rs)

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.

The nine trained sizes as a table (measured)

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.

WordPiece, Unigram and SentencePiece

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:

MethodTraining: how the vocabulary is builtEncoding a new wordUnknown inputUsed by
BPEStart 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 learnedFalls back to characters; a character never seen is unknownLLaMA 1 and 2 (LLaMA section 2.1), Mistral 7B (via SentencePiece)
Byte-level BPEThe same, over the 256 possible byte values instead of charactersSameImpossible: every string is a byte sequenceGPT-2 onward, Llama 3 and 4, Qwen, DeepSeek, Kimi, gpt-oss, GLM, MiniMax, Olmo, Nemotron 3, and the running example
WordPieceSame skeleton as BPE; merge the pair maximising freq(ab) / (freq(a) × freq(b))Greedy longest match from the left, ## marks a continuationThe whole word becomes [UNK]BERT and its descendants
Unigram LMStart from a large candidate set; prune the tokens whose removal hurts corpus likelihood least (Kudo 2018)Most probable segmentation (Viterbi); can sample othersCharacters, or bytes with byte fallbackT5, XLNet, ALBERT, mBART (HF course)
SentencePieceA 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 insideOptional byte fallbackT5, 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.

How the three trainers were checked, and where WordPiece's score comes from (provenance)

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

Edit the training text and the sizes

Corpus, as the model would now see it
Candidates this step

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).

Encoding is a different algorithm

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).

  1. Bytes, and every pair's rank. " climb" is 6 bytes. Each adjacent pair is looked up in the merge list: " c" is merge 20, "im" merge 45, "mb" merge 2,464; "cl" and "li" are not in the list at all.
  2. Lowest rank first. " c" (merge 20) is merged. The new pair " c" + "l" is in the list as merge 237.
  3. "im" (45). It takes the "m" that "mb" (2,464) wanted, so that merge never applies to this word.
  4. " cl" (237). Then only " cl" + "im" + "b" are left.
  5. "imb" (748). One pair remains, " cl" + "imb".
  6. " climb" (758): one token, id 1014, the library's id. Training ranked the merges by frequency; encoding only uses that order, never a count.
  7. "Roxy". No adjacent pair of "Roxy" is in the merge list, so nothing merges: four byte tokens, whatever order the merges are tried in.

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.

The library's BPE encoder, quoted (tokenizers v0.23.3, word.rs)

"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):

Vocabulary size: what it costs and what it buys

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.

Predict: the tiny GPT has 4,721,920 parameters outside its embedding. If it used GPT-2's tokenizer (50,257 entries, tied, width 256) instead of the 4,096-entry one, what share of its parameters would be the embedding table?
  1. The tiny GPT, 4,096 entries. The table is 4,096 × 256 = 1.05M parameters against 4.72M in the six blocks: 18%. The running text is 255 tokens.
  2. The same model with GPT-2's 50,257 entries. The table grows twelve times, to 12.87M: 73% of the model is a lookup table, and the output layer costs 25.7M FLOPs per token against 9.4M for all six blocks. The running text only shrinks to 228 tokens.
  3. Gemma 3 1B. 262,144 × 1,152 = 302M, tied: 30% of 1.0B parameters.
  4. Llama 3.1 8B. Untied: an input and an output table of 128,256 × 4,096 = 525M each, 13% of 8.03B; the output layer is 7% of the decode FLOPs.
  5. gpt-oss-20b, all weights. Two tables of 201,088 × 2,880 = 579M each: 6% of 20.9B.
  6. gpt-oss-20b, per token. Only 4 of 32 experts run per token, but both tables run every time: 28% of the 4.19B active parameters, and the output layer 16% of the decode FLOPs.

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.

Thirteen configs as a table (derived)

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.

Where transformers pads, and a tying trap (transformers 5.20.1)

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.

What current models use

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:

  • Tokenizers are inherited, not redesigned. DeepSeek-V4 keeps V3's 128,000 ordinary tokens exactly and only adds special tokens; Gemma 4 keeps 262,125 of Gemma 3's 262,144 entries; GLM, MiniMax and Olmo equal their predecessors (the full list is in the table below). A new tokenizer invalidates every embedding and output row of the predecessor and every cached tokenization of the data, so labs change it only with a new pretraining run and a measured reason.
  • The exception is the multilingual push. Qwen3.5 grew from 151,669 to 248,070 entries and shares 131,586 of Qwen3's ordinary tokens; Llama 4 grew from 128,256 to 201,135 and shares 100,438 with Llama 3. Both cut Hindi sharply (Qwen3 56 to Qwen3.5 27 tokens on the same FLORES sentence, Llama 3 32 to Llama 4 22) while English stays at 16 to 17 tokens in every tokenizer of the table.
  • Sizes cluster at 128K to 262K. 128K (Llama 3, DeepSeek, Nemotron 3 Super at 131,072), 150K to 165K (Qwen3, GLM, Kimi), 200K (Llama 4, MiniMax, OpenAI), 248K to 262K (Qwen3.5, Gemma). Vocabularies grew from 32K (LLaMA, 2023), mostly for multilingual and code compression, and the 32K vocabularies of 2023 are gone from new models; the Vocabulary timeline tab puts 41 models from 2018 to 2026 on one axis.

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's own compression figure against FLORES, and where its tokenizer came from (sources)

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 2026 tokenizers, read from their files (measured, table)

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.

Numbers and code

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).

The digit rules with their sources (table)
TokenizerDigit rule"12345678" becomesSource
GPT-2 (r50k_base)Any run of digits, then BPE merges inside it123|45|678GPT-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 K3Groups of 1 to 3 digits, from the left123|456|78Pattern \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, SmolLM2Every digit on its own1|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.

Predict: OLMo 2 1B (a base model whose tokenizer cuts digits in threes from the left) gets 8 worked examples, then 100 additions of 4- and 5-digit numbers, greedy. Once written plainly (12345 + 6789 =), once with commas (12,345 + 6,789 =). What happens?

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.

The problems and the answers, digit by digit (measured)

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.

The language tax

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

  1. English, GPT-2. 17 tokens for the 78 bytes of FLORES sentence 366, "The major organ of the circulatory system is the heart, which pumps the blood." The dashed footprint under each row is the sentence's UTF-8 bytes, what a byte-level model would read.
  2. Six more languages, same tokenizer. French 32, Russian 88, Chinese 52, Hindi 97, Tamil 246, Burmese 285: Tamil and Burmese get nearly one token per byte. Over all of FLORES, Tamil pays 15.6 times English and Burmese 16.9.
  3. GPT-4's cl100k (2023). Tamil 118 tokens (7.65 times English over FLORES), Hindi 60 (4.79), Russian 36 (2.49).
  4. GPT-4o's o200k (2024). Tamil 29 (1.96), Hindi 21 (1.56), Burmese 52 (3.18).
  5. Gemma 3's 262K (2025). Tamil 24 (1.46), Chinese 13 (1.11), Burmese 36 (2.42): the same sentence now costs about the same in every language but Burmese.

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.

Failure modes, with real outputs

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

A prompt that ends in a space

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.

Letters inside tokens

" 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

All 24 words, pieces and answers (measured)

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.

Glitch tokens: entries the model never trained

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

What the tiny GPT writes after an unseen token (measured)

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 and chat templates

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.

Both traps as code that ran, with their output (provenance)

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.

Beyond subwords

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.

ByT5, MegaByte, BLT and SuperBPE in their own words (sources and numbers)
  • ByT5 (2021) feeds raw UTF-8 bytes to a T5: "a vocabulary of 256 possible byte values. An additional 3 IDs are reserved for special tokens". Sequences are about 4 times longer than SentencePiece's ("4.1 bytes per SentencePiece token" on mC4); byte models "are significantly more robust to noise and perform better on tasks that are sensitive to spelling", at "+33% pre-training time" and inference up to 10 times slower (ByT5).
  • MegaByte (2023) "segments sequences into patches and uses a local submodel within patches and a global model between patches", with fixed patches of 8 bytes for text (MegaByte).
  • Byte Latent Transformer, BLT (Meta, December 2024) makes the patches dynamic: a small byte-level model predicts the next byte, and a new patch starts where its entropy is high, 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"; "The bpe tokenizers of Llama 2 and 3 have an average token size of 3.7 and 4.4 bytes. In contrast, BLT can achieve similar scaling trends with an average patch size of 6 and even 8 bytes" (BLT section 5.1).
  • SuperBPE (2025) goes the other way and lets tokens cross spaces in a second training stage ("superword" tokens such as "by the way"): with a 200K vocabulary it "encodes a fixed piece of text with up to 33% fewer tokens on average than BPE", and an 8B model trained with it scores "+4.0% absolute improvement over the BPE baseline across 30 downstream tasks" with "27% less compute at inference time" (SuperBPE). The old page said frontier labs are experimenting with SuperBPE-style tokens; that is unconfirmed: no released frontier tokenizer measured here has superword tokens.
  1. Bytes (ByT5). One step per UTF-8 byte: 79 steps for this sentence, computed.
  2. 4-byte strides (MegaByte-style). Fixed patches, computed (the figure's row agrees): a quarter of the steps, but a patch boundary falls anywhere, even mid-word.
  3. BPE (Llama 3). The real tokenizer, run offline: 23 tokens, boundaries learned from frequency.
  4. Space patching. A new patch after a space-like byte (transcribed): about one patch per word, 15 in all.
  5. Entropy, global threshold. A new patch where the small byte model's next-byte entropy is high (transcribed): hard bytes such as the start of a name get short patches, predictable stretches long ones.
  6. Entropy with monotonicity. A new patch where entropy rises relative to the previous byte (transcribed): the fewest, longest steps.

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.

Training your own

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.

The training code, its recorded result, and the settings that matter (code that ran)

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.

Depth

Interview rehearsal: three design questions (optional)
Why does gpt-oss-20b's vocabulary matter more than Llama 3.1 8B's, although its table is a smaller share of total parameters?
Total parameters do not run per token; active ones do. gpt-oss-20b activates 4 of 32 experts, so its 201,088 × 2,880 untied tables are 28% of the active parameters and its output layer 16% of the decode FLOPs per token, against 13% and 7% for dense Llama 3.1 8B (root Config calculator numbers).
What is a glitch token and how would you find them in a model you are given?
A vocabulary entry the model almost never saw in training, so its embedding is untrained. Find candidates from the weights: rows that cluster together or have unusual norms (here 132 unseen entries had cosine similarity 0.996 with each other and norms 2.5 times the median), check frequency in a training sample, then confirm by prompting the model to repeat the token.
Design: you are pretraining a 3B model that must serve English, Hindi, Japanese and Python. How do you choose the tokenizer?
Train byte-level BPE (no holes) on a sample matching the target mix, oversampling the smaller languages so they get merges; pick digit handling (single digits, or groups of three from the right) and whitespace-run tokens for code before training; reserve chat and tool special tokens up front. Size: measure characters per token on held-out text per language at, say, 64K, 128K and 256K, and weigh tokens saved against the table's cost (at width 3,072 a 256K untied vocabulary is 1.6B parameters, half the model, so tie the embeddings or stay near 128K: SmolLM3 3B ties a 128,256-entry table, root map config). Check the result: fertility per language within about 1.5 times English, no unseen entries in a training sample, round-trip decode exact on every test string.