Tokenizers in Depth
BPE step by step, byte-level vocabularies, chat templates and glitch tokens.
A language model never sees text. It sees a list of integers, and the tokenizer decides what those integers are. That decision sets how long your prompts are, what they cost, which languages are expensive, why models stumble on digits, and how a conversation is framed. It is also the piece most often misconfigured when a model is self-hosted.
Section 2.2 introduced tokens with a small tokenizer. This chapter builds a larger one on the full Shakespeare text, 2,048 merges, and uses it to measure each claim.
6.1Bytes and Unicode
Unicode and normalization decide what the tokenizer sees.
Three different things get called a character. A code point is a number that Unicode assigns to a symbol. A byte is what is stored: UTF-8 writes each code point as one to four bytes. And what a reader perceives as one character can be several code points.
| What you see | Code points | Bytes in UTF-8 | Bytes after NFKC normalization |
|---|---|---|---|
| e | 1 | 1 | 1 |
| é stored as one code point | 1 | 2 | 2 |
| é stored as e plus a combining accent | 2 | 3 | 2 |
| न | 1 | 3 | 3 |
| 😀 | 1 | 4 | 4 |
| fi (a ligature) | 1 | 3 | 2 |
The two forms of “é” look identical and are different byte sequences, so without care they become different tokens. Normalization rewrites text into one canonical form before tokenizing. The common forms are NFC, which composes characters, and NFKC, which also folds look-alikes such as the “fi” ligature into plain letters.
Common take“A token is roughly a word, and a word is made of characters.”
Sharper take“Underneath it is bytes. One visible character can be one to four bytes or several code points, and the tokenizer works on whatever byte sequence it is given.”
6.2Why subwords
Characters make sequences too long, and words make vocabularies too large.
There are three natural units to choose from.
- Characters or bytes. A tiny vocabulary, and nothing is ever out of vocabulary. But sequences are long, every prediction carries little information, and the model has to learn spelling before it can learn anything else.
- Words. Short sequences, but the vocabulary runs to millions, most words are rare, and a new word has no entry at all.
- Subwords. Frequent words become single tokens; rare words are spelled from pieces. The vocabulary is a size you choose, typically tens or hundreds of thousands.
Every production model uses subwords, and the dominant way to find them is byte-pair encoding (BPE). The method was originally a text-compression algorithm, and that is still the right way to think of it: a tokenizer is a compressor tuned to its training text.
Common take“Tokens are a quirk of how models read.”
Sharper take“Tokens are a compression scheme. The better the scheme fits your text, the fewer tokens you pay for and the more of your document fits in the context.”
6.3BPE training
Count the most frequent pair, merge it, repeat.
Start with the text as bytes, so the initial vocabulary is the 256 possible byte values. Then repeat one step: find the pair of adjacent tokens that occurs most often, give that pair a new token id, and replace every occurrence. Each repetition is one merge, and the list of merges, in order, is the tokenizer.
Most frequent adjacent pairs now
Merges learned, in order
On the one-megabyte Shakespeare text, the first merges are what you would guess:
| Merge | Pair | Occurrences | Tokens left in the text |
|---|---|---|---|
| 1 | e + · | 25,010 | 978,844 |
| 2 | t + h | 20,592 | 958,252 |
| 3 | t + · | 14,879 | 943,373 |
| 4 | s + · | 13,986 | 929,387 |
| 5 | d + · | 12,795 | 916,592 |
| 6 | , + · | 12,485 | 904,107 |
| 7 | o + u | 11,506 | 892,601 |
| 8 | e + r | 10,559 | 882,042 |
After 2,048 merges the text has shrunk from 1,003,854 tokens to 311,247. By then the tokenizer has also memorized quirks of its training text. Its longest tokens are whole speaker headings such as .↵↵HENRY·BOLINGBROKE:↵, each stored as a single token, because that exact string recurs so often.
The whole algorithm, including encoding and decoding, fits on one screen:
from collections import Counter
def merge(ids, pair, new_id):
"""Replace every occurrence of pair in ids with new_id."""
out, i = [], 0
while i < len(ids):
if i + 1 < len(ids) and (ids[i], ids[i + 1]) == pair:
out.append(new_id); i += 2
else:
out.append(ids[i]); i += 1
return out
def train_bpe(data: bytes, n_merges: int):
ids = list(data) # start from raw bytes: ids 0 to 255
merges = [] # the learned pairs, in order
for new_id in range(256, 256 + n_merges):
pairs = Counter(zip(ids, ids[1:])) # count every adjacent pair
pair = max(pairs, key=pairs.get) # the most frequent one
ids = merge(ids, pair, new_id)
merges.append(pair)
return merges
def encode(text: str, merges):
ids = list(text.encode("utf-8"))
for k, pair in enumerate(merges): # replay the merges in the order they were learned
ids = merge(ids, pair, 256 + k)
return ids
def decode(ids, merges):
table = {i: bytes([i]) for i in range(256)}
for k, (a, b) in enumerate(merges):
table[256 + k] = table[a] + table[b]
return b"".join(table[i] for i in ids).decode("utf-8", errors="replace")Real tokenizers add one step before the merges, called pre-tokenization: the text is first split at spaces and punctuation, and merges are not allowed to cross those boundaries. That keeps tokens word-shaped and prevents oddities like the speaker headings above.
Common take“The tokenizer is designed by linguists.”
Sharper take“It is learned from data by a counting loop, and it inherits the habits of whatever text it was trained on.”
6.4Encoding and decoding
Replay the merges in order, then concatenate to reverse.
To encode new text, turn it into bytes and apply the merges in the order they were learned. To decode, look up each token’s bytes and join them. Because the starting alphabet is all 256 bytes, any text can be encoded, and decoding always returns exactly what went in.
| Text | Characters | Tokens, vocabulary 512 | Tokens, vocabulary 2,304 | Pieces at 2,304 |
|---|---|---|---|---|
To be, or not to be, that is the question. | 42 | 17 | 14 | To· b e,· or· not· to· b e,· that· is·the· qu est ion . |
unbelievable | 12 | 8 | 6 | un be li ev ab le |
2026-11-16 | 10 | 10 | 10 | 2 0 2 6 - 1 1 - 1 6 |
for i in range(10): | 19 | 14 | 10 | for· i ·in· ran ge ( 1 0 ) : |
नमस्ते | 6 | 18 | 18 | 18 single bytes |
😀 | 1 | 4 | 4 | 4 single bytes |
Four things in this table recur in every production tokenizer:
- Spaces attach to words. “not” with its trailing space is one token. The same word at the end of a sentence, or capitalized, is a different token.
- Digits fragment. The date takes one token per character. A model that sees numbers as irregular fragments has to work harder at arithmetic, which is part of why digit-level tasks are a classic weak spot (section 2.2).
- Unfamiliar text falls back to bytes. The Hindi word costs 18 tokens for 6 characters, and one emoji costs 4. Nothing fails, but the cost is real.
- Code compresses poorly on a tokenizer that has never seen code.
Common take“Token count is about a quarter of the character count.”
Sharper take“For English prose on a tokenizer trained on English prose. For dates, code or another script the ratio can be several times worse. I count with the actual tokenizer.”
6.5Vocabulary size
A bigger vocabulary compresses more, until its tokens become too rare to learn.
Each merge shortens the text and adds a row to the model’s embedding table. How far should it go?
- training text
- held-out text
The gains come with three costs:
- Bigger tables. The embedding and output layers each have vocabulary × width weights. At a width of 4,096, a vocabulary of 128,000 puts half a billion weights in each.
- Rarer tokens. In the tokenizer above, 102 of the 2,048 learned tokens never appear in the final encoding of its own training text, and 134 appear fewer than ten times. They were absorbed into longer tokens by later merges. A model trained with this vocabulary would have embeddings for them that had almost never been updated.
- A harder prediction. The model chooses among more options at every step.
The second cost has a name in production models: under-trained or glitch tokens. They are vocabulary entries the model almost never saw during training, and feeding one in can produce erratic output. They are one reason unusual strings sometimes derail a model.
Production vocabularies have settled between about 32,000 and 250,000 entries: GPT-2 used 50,257, Llama 3 uses about 128,000, and recent multilingual models go to 200,000 or more to give other scripts reasonable compression.
Common take“A bigger vocabulary is strictly better: fewer tokens, lower cost.”
Sharper take“Each doubling compresses less and leaves more tokens too rare to train. The vocabulary size is a trade between sequence length and how well each token is learned.”
6.6Out of domain
A tokenizer is tuned to its training text, and you pay for the mismatch.
The same 2,048-merge tokenizer, applied to four kinds of text:
| Text | Bytes per token | Tokens per character |
|---|---|---|
| Shakespeare, held out | 2.89 | 0.35 |
| Modern English prose | 2.82 | 0.35 |
| Python code | 1.58 | 0.63 |
| Hindi | 1.00 | 2.58 |
Modern English does nearly as well as held-out Shakespeare, because the common words are the same. Code gets about half the compression. Hindi gets none: every byte is its own token, 2.6 tokens for every character.
Production tokenizers are trained on far broader text, so the gaps are smaller, but the same ordering holds. Token counts per word are lowest for English, higher for other European languages, and higher again for scripts that were rare in the tokenizer’s training data. Since price, latency and context usage are all counted in tokens (section 2.6), the same product costs more to run for some users than for others.
Common take“The model handles every language, so the tokenizer doesn’t matter.”
Sharper take“It handles them at different prices. I measure tokens per character on real traffic for each language and content type, and budget from that.”
6.7Other algorithms
WordPiece and Unigram solve the same problem by different routes.
| Algorithm | How the vocabulary is built | Where you meet it |
|---|---|---|
| BPE | Start small; repeatedly merge the most frequent pair | The GPT family, Llama 3, most current models |
| WordPiece | Start small; merge the pair that most improves the likelihood of the text. Word-internal pieces are marked with “##” | BERT and many encoder models |
| Unigram | Start with a large candidate vocabulary; repeatedly remove the pieces that matter least | T5 and other models built with SentencePiece |
Two names you will see are libraries, not algorithms. SentencePiece implements both BPE and Unigram, and treats spaces as an ordinary symbol, written “▁”, so it needs no language-specific word splitting. tiktoken and Hugging Face tokenizers are fast implementations of BPE and its relatives.
At the far end are models with no learned tokenizer, which read raw bytes and group them inside the network. They remove this whole chapter’s failure modes and pay with much longer sequences. As of this writing they are an active research direction and not what production models use.
Common take“Which tokenizer algorithm is best?”
Sharper take“The algorithm matters less than the training text and the vocabulary size. And I never get to choose: a model only works with the tokenizer it was trained with.”
6.8Special tokens and chat templates
The control channel that turns text into a conversation.
Beyond the learned vocabulary, every tokenizer reserves special tokens that ordinary text can never produce: markers for the start and end of a sequence, for the start and end of each speaker’s turn, and often for tool calls and reasoning. They are how structure is signaled to the model.
A chat template is the recipe that turns a list of messages into one token sequence using those markers. One widely used format looks like this once rendered:
<|im_start|>system
You are a helpful assistant.<|im_end|>
<|im_start|>user
What is the capital of France?<|im_end|>
<|im_start|>assistant
The model continues from the last line, and generation stops when it emits the end-of-turn token. This is the whole mechanism behind roles: the system prompt, the user’s message and the assistant’s reply are one stream of tokens with markers between them (section 2.1). A model behaves like an assistant because it was fine-tuned on text in exactly this layout (Chapter 9).
Two consequences follow. Each model family has its own template, and using the wrong one produces no error, only worse answers. And because the markers carry authority, user-supplied text must never be able to introduce them; hosted APIs strip or escape special tokens in input for that reason.
Common take“The system prompt is a separate channel the model treats specially.”
Sharper take“It is text in the same sequence, set apart by special tokens. The model respects it only because it was trained on that layout, which is why the exact template matters.”
6.9Lab: swap the tokenizer
Swap the tokenizer into the model, and compare on equal terms.
Does a subword tokenizer help a model, or only shorten its input? I trained the small transformer from Chapter 7 twice with identical settings and 6,000 steps each: once on characters, and once on tokens from the first 256 merges of this chapter’s tokenizer, a vocabulary of 512.
The raw losses cannot be compared. The character model reaches 1.71 per character; the BPE model reaches 3.21 per token, but each of its tokens covers 1.94 characters on average. Dividing gives the fair number:
The BPE model is ahead, for two reasons you can now name. Its 64-token context spans about 124 characters where the character model sees 64. And it does not have to spend capacity learning to spell common words. It pays with a larger embedding table, 219,136 parameters against 161,920.
Common take“Model A has a lower loss than model B, so it is the better model.”
Sharper take“Lower loss per what? If the tokenizers differ, I convert both to loss per byte before comparing.”
Key takeaways
- A tokenizer is a compressor tuned to its training text. BPE builds it by repeatedly merging the most frequent adjacent pair.
- Underneath tokens are bytes. One visible character can be one to four bytes, and text that looks identical can differ in normalization.
- Encoding replays the merges in order; decoding concatenates bytes. Starting from all 256 bytes means nothing is ever out of vocabulary.
- Spaces attach to words, digits fragment, and unfamiliar scripts fall back to bytes: a six-character Hindi word cost 18 tokens here.
- A bigger vocabulary compresses more with diminishing returns, enlarges the embedding tables, and leaves rare tokens under-trained: 102 of 2,048 learned tokens were never used.
- The same tokenizer gave 2.89 bytes per token on held-out Shakespeare, 1.58 on Python code and 1.0 on Hindi. Count tokens with the real tokenizer on real traffic.
- Special tokens and the chat template are how roles and turns are signaled. The wrong template gives worse answers and no error.
- Losses are comparable only between models with the same tokenizer. Convert to a per-character or per-byte figure otherwise.
Check your understanding
-
Your product launches in a market that writes in a non-Latin script. Usage per user matches the English market, but the bill per user is 2.4 times higher and responses feel slower. Explain the likely cause, how you would confirm it, and what you could change.
Answer outline
The likely cause is tokens per character: the tokenizer compresses that script less well, so the same conversation uses more input and output tokens, and both cost and generation time scale with tokens. Confirm by counting tokens with the model’s tokenizer on matched samples from both markets and comparing tokens per request. Options: a model whose tokenizer handles the script better, shorter system prompts and tighter output limits for that market, prompt caching for the shared prefix, and budgets set per market from measured token counts.
-
You deploy open weights on your own servers. Speed is fine, but answers are worse than the same model through a hosted API: more rambling, sometimes continuing as the user. Name the most likely cause and how to verify it in ten minutes.
Answer outline
The chat template or special tokens are wrong: a different role format, a missing end-of-turn marker, a doubled start-of-sequence token, or the stop token not set as a stop condition. Continuing as the user is the signature of a missing or unrecognized end-of-turn token. To verify, render a short conversation with the tokenizer’s built-in template function and compare the token ids with what your serving code sends; then check that generation stops on the end-of-turn token.
-
A teammate wants to add 5,000 new tokens for product codes to an existing model’s vocabulary so that each code is a single token. What happens if you just add them, and what would you propose?
Answer outline
New tokens get new embedding rows that start untrained, so the model has no idea what they mean; they are the under-trained tokens of section 6.5 by construction. They only become useful after fine-tuning on enough text that contains them, and codes that appear rarely will stay poorly learned. A cheaper first step is to leave the codes as subword pieces, measure how many tokens they cost and how accurately the model copies them, and add tokens only if that measurement shows a real problem and there is data to train them.
Further reading
- Andrej Karpathy, “Let’s build the GPT Tokenizer” (video, with the minbpe repository): BPE from an empty file, close to the code in section 6.3.
- Jurafsky and Martin, Speech and Language Processing, the chapter on words and tokens: Unicode, normalization and BPE.
- Sebastian Raschka, Build a Large Language Model (From Scratch), chapter 2: tokenizing text and building the input pipeline.
- The Hugging Face tokenizers documentation: normalizers, pre-tokenizers and chat templates as they are configured in practice.