Skip to content

Chapter 7: Tokenizers

Every model in this book reads ids, not text, and the tokenizer decides what those ids are. Until now the tracer has used the simplest possible answer: 256 byte ids, no training, every text round-trips. That costs one token per byte and makes the model learn to spell UTF-8. This chapter goes from bytes to trained subword vocabularies, and it does so with an unusual standard of correctness: wherever a real model’s tokenizer exists, your implementation must reproduce its ids exactly.

Concepts from other sections (13)

This section uses these ideas. Each has a short definition and a link to the section that explains it in full. Tap a dotted term in the text to preview it.

  • Byte-level: the base alphabet is the 256 bytes (through the byte map), so every text encodes and there is no unknown token. Read more: 7.2 Byte-level BPE
  • Greedy longest match: segmenting a word by repeatedly taking the longest vocabulary entry that matches at the current position. Read more: 7.3 WordPiece
  • Likelihood: ∏ipθ(xi)\prod_i p_\theta(x_i), the probability of the observed data as a function of the parameter. Read more: 13.10 Probability problem set, part b: joint distributions, covariance, MLE in Mathematics
  • Bytes per token: total UTF-8 bytes over total tokens; the compression ratio. Read more: 7.6 Tokenizer metrics
  • Bits per byte: total loss in bits divided by total UTF-8 bytes; equal to bits per token over bytes per token. Read more: 7.6 Tokenizer metrics
  • Tokenizer protocol: the six-member structural interface (vocab_size, special_ids, unk_id, encode/decode, token_to_id/id_to_token, save/load) every tokenizer satisfies. Read more: 7.1 The tokenizer protocol and the char tokenizer
  • Merge rank: a merge’s position in the learned merges list; lower ranks were learned earlier and apply first when encoding. Read more: 7.2 Byte-level BPE
  • Viterbi: the dynamic program for the highest-scoring path through the lattice. Read more: 7.4 The Unigram language model tokenizer
  • Fallback rate: the share of token occurrences that are fallbacks. Read more: 7.6 Tokenizer metrics
  • Basic tokenizer: BERT’s normalizer and pre-tokenizer: clean, space CJK, strip accents, lowercase, split on white space and punctuation. Read more: 7.3 WordPiece
  • Forward-backward: the log-sum-exp recursions α\alpha and β\beta that give each edge’s posterior probability. Read more: 7.4 The Unigram language model tokenizer
  • Removal loss: how much corpus likelihood is lost if a piece is removed and its text must be spelled another way. Read more: 7.4 The Unigram language model tokenizer
  • Streaming decoder: a decoder that emits only complete UTF-8 after each token and holds back up to 3 bytes of an unfinished character. Read more: 7.5 Fast BPE in Rust

The chapter’s arc follows one idea: a tokenizer is a contract. It opens by fixing that contract, the Tokenizer protocol, so that encode(decode(ids)) == ids and decode(encode(text)) == text hold for every string, including invalid UTF-8 split across a stream, and so that everything downstream is written once. Three trained families then implement it. Byte-level BPE merges the most frequent adjacent pair until the vocabulary is full, and encoding replays the merges by rank; it loads GPT-2’s and SmolLM2’s Hugging Face files. WordPiece is BERT’s normalizer plus greedy longest match. The Unigram language model starts from a large vocabulary, prunes by likelihood loss, and can sample segmentations, which the capstone’s BPE-versus-Unigram ablation measures. BPE is then reimplemented independently in Rust as tl-tok, with a streaming UTF-8 decoder, and Python and Rust are held to the same frozen fixtures through tokenizer.json. The chapter ends with the metrics that decide a vocabulary size for the capstone, of which compression comes first: bytes per token and bits per byte on held-out text.

Learning objectives

  • State the tokenizer protocol and its laws, and validate ids and files against it.
  • Train byte-level BPE and encode by merge rank, reproducing GPT-2’s and SmolLM2’s ids from their real files.
  • Implement BERT’s WordPiece pipeline and the Unigram language model (Viterbi, EM, subword sampling).
  • Build a fast Rust BPE with a lazy merge heap and a streaming UTF-8 decoder that matches the Python id for id.
  • Measure fertility, bytes per token, and fallback rate, and use bytes per token to compare models in bits per byte.

The mathematics this chapter uses comes from Mathematics: the GPT-2 byte map, trees and tries with longest-prefix match, categorical sampling, maximum-likelihood estimation, and perplexity and bits per byte, with practice in the problem sets on trees and hashing and joint distributions and MLE. For the Rust section you also need the Rust primer in Programming and Algorithms, and the Robin Hood hash map and binary heap with lazy deletion from Programming and Algorithms. You should have read the byte bigram, whose byte ids this chapter generalizes.

  1. The tokenizer protocol and the char tokenizer: the one interface every tokenizer implements, shared id validation, the byte tokenizer rewritten against it, and a char tokenizer whose ids do not depend on the order of its training texts.
  2. Byte-level BPE: a hand-written GPT-2 pre-tokenizer, a lazy-heap BPE trainer that matches Hugging Face’s merges, rank-ordered encoding, and loaders that reproduce GPT-2’s and SmolLM2’s ids.
  3. WordPiece: BERT’s basic tokenizer and greedy longest match, exact enough to reproduce bert-base-uncased’s ids, template, and decodes.
  4. The Unigram language model tokenizer: Viterbi encoding over a lattice, EM training by forward-backward, pruning by removal loss, and exact sampling of segmentations.
  5. Fast BPE in Rust: the tl-tok crate, with an O(nlog⁡n)O(n \log n) merge heap, Unicode tables generated from Python, parallel batch encoding, and a streaming decoder for the server.
  6. Tokenizer metrics: fertility, bytes per token, and fallback rate for any tokenizer, and why bytes per token is the exchange rate to bits per byte.