llm.guideChapter 6Tokenizers in Depth

Tokenizers in Depth

BPE step by step, byte-level vocabularies, chat templates and glitch tokens.

Part 2: Foundations. 9 sections, about 15 minutes.

To·be,·or·not·to·be,·that·is·the·question.42 characters, 14 tokens
To·be,·or·not·to·be,·that·is·the·question.42 characters, 14 tokens
One sentence as a tokenizer trained on Shakespeare sees it. Each box is one token; a dot marks a space.

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 seeCode pointsBytes in UTF-8Bytes after NFKC normalization
e111
é stored as one code point122
é stored as e plus a combining accent232
न133
😀144
fi (a ligature)132

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.

Text → code points → UTF-8 bytes“é”, composedU+00E9C3A9“é”, decomposedU+0065U+030165CC81Both look identical on screen. Without normalization (NFC) they become different tokens,so a search, a cache key or a tokenizer treats one word as two.
Figure 6.1 Two spellings of one letter. Normalizing text to one form (usually NFC) before it reaches the tokenizer keeps them the same.

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

      Figure 6.2 Computed live in your browser on a one-line text, with spaces shown as ·. Each click finds the most frequent adjacent pair (top left), gives it a new token, and replaces every occurrence (highlighted). The list on the right is the whole tokenizer.

      On the one-megabyte Shakespeare text, the first merges are what you would guess:

      MergePairOccurrencesTokens left in the text
      1e + ·25,010978,844
      2t + h20,592958,252
      3t + ·14,879943,373
      4s + ·13,986929,387
      5d + ·12,795916,592
      6, + ·12,485904,107
      7o + u11,506892,601
      8e + r10,559882,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.

      TextCharactersTokens, vocabulary 512Tokens, vocabulary 2,304Pieces at 2,304
      To be, or not to be, that is the question.421714To· b e,· or· not· to· b e,· that· is·the· qu est ion .
      unbelievable1286un be li ev ab le
      2026-11-161010102 0 2 6 - 1 1 - 1 6
      for i in range(10):191410for· i ·in· ran ge ( 1 0 ) :
      नमस्ते6181818 single bytes
      😀1444 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?

      1232565121,0242,304bytes per tokenvocabulary sizetraining text: 3.23held-out text: 2.89
      1232565121,0242,304bytes per tokenvocabulary sizetraining text: 3.23held-out text: 2.89
      • training text
      • held-out text
      Figure 6.3 Real tokenizer. Compression keeps improving as the vocabulary grows, but each doubling buys less, and held-out text compresses less well than the text the tokenizer was trained on (2.89 against 3.23 bytes per token at a vocabulary of 2,304).

      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:

      TextBytes per tokenTokens per character
      Shakespeare, held out2.890.35
      Modern English prose2.820.35
      Python code1.580.63
      Hindi1.002.58
      Shakespeare, held out0.35
      Modern English prose0.35
      Python code0.63
      Hindi2.58
      Figure 6.4 Real measurement: the table above as tokens per character, for the same 2,048-merge tokenizer. Hindi text costs more than seven times as many tokens as English for the same number of characters.

      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.

      AlgorithmHow the vocabulary is builtWhere you meet it
      BPEStart small; repeatedly merge the most frequent pairThe GPT family, Llama 3, most current models
      WordPieceStart small; merge the pair that most improves the likelihood of the text. Word-internal pieces are marked with “##”BERT and many encoder models
      UnigramStart with a large candidate vocabulary; repeatedly remove the pieces that matter leastT5 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.

      <|im_start|>systemYou are a support assistant.<|im_end|><|im_start|>userWhere is my order?<|im_end|><|im_start|>assistantthe model writes from here…Special tokens (highlighted) are singleids the tokenizer reserves; user textcannot produce them by typing thesame characters.Each model family has its own template.Use the tokenizer’s chat templaterather than writing the markers yourself;a wrong template quietly lowers quality.The answer begins after the openassistant turn.
      Figure 6.5 A chat template in the ChatML style. The control channel is made of tokens no user can type, which is what separates a conversation from a document.

      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:

      Charactersvocabulary of 65, context of 64 characters1.71
      BPE tokensvocabulary of 512, context of about 124 characters1.65
      6-gram counting modelChapter 41.63
      Figure 6.6 Real result, validation loss in nats per character; lower is better. Same architecture, same number of steps. The count-based 6-gram from Chapter 4 is shown for reference.

      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

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

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

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

      ↑↓ to move↵ to openesc to close