Shelves / AI and ML Foundations
AI·155
Tokenization
How text becomes the integers a model actually sees, and why it shapes cost, context and behaviour: tokens and vocabularies, the trade-off between characters, words and subwords, Unicode code points and UTF-8 bytes, byte-pair encoding trained and applied from scratch, byte-level BPE with pre-tokenisation regexes, WordPiece and its likelihood criterion, the Unigram language model and SentencePiece, special tokens and chat templates, token budgets and cost arithmetic, multilingual and code fairness, number and whitespace quirks, glitch tokens and prompt-boundary effects, tokenizer libraries in Python, Rust, Go, Java and JavaScript, and practical rules for engineers.
Start here: how text becomes numbers
A language model never sees letters or words. A tokenizer first splits text into tokens (pieces drawn from a fixed vocabulary) and maps each to an integer ID; the model reads and writes those IDs. Most modern tokenizers use byte-pair encoding (BPE): start from the 256 possible bytes, then repeatedly merge the most frequent adjacent pair into a new token, until the vocabulary reaches its target size. Common words end up as single tokens; rare words are split into pieces; any text at all can still be written, byte by byte.
Bigger vocabulary, fewer tokens
BPE tokenizers of four sizes, trained on 95% of the textbook's text and measured on the other 5% (254,134 characters, 38,791 words):
vocab 512: 132,943 tokens 3.43 tokens per word 1.91 characters per token
vocab 2,048: 87,737 tokens 2.26 tokens per word 2.90 characters per token
vocab 8,192: 64,740 tokens 1.67 tokens per word 3.93 characters per token
vocab 32,768: 57,303 tokens 1.48 tokens per word 4.43 characters per token
Fewer tokens means shorter sequences: cheaper attention (chapter 154), more text in the same context window, and lower cost per request, since APIs charge per token. The price is a bigger embedding table and output layer, and rarer tokens that the model sees less often during training.
What the pieces look like
With the 8,192-token vocabulary:
"Today's lunch is dal tadka with jeera rice…" → 'T' 'od' 'ay' "'s" ' lunch' ' is' ' d' 'al' ' t' 'ad' 'ka' ' with' ' j' 'e' … (23 tokens)
"Order 4729183 costs ₹1,234.50" → 'Order' ' 47' '2' '9' '18' '3' ' costs' ' ₹' '1' ',' '23' '4' '.' '50' (14 tokens)
Words common in the training text (" lunch", " with") became single tokens with their leading space; less common ones ("dal", "tadka") were cut into fragments. Numbers were chopped irregularly (47 | 2 | 9 | 18 | 3), one reason models find arithmetic on long numbers hard; many modern tokenizers split numbers into single digits or groups of three on purpose.
Languages the tokenizer didn't learn
The same sentence about lunch, in three languages, with each vocabulary size:
vocab 512 2,048 8,192 32,768
English (57 characters) 32 26 23 17
Hindi (64 characters, 164 bytes) 164 164 164 114
Telugu (64 characters, 172 bytes) 172 172 172 122
The training text was almost all English, so up to 8,192 tokens BPE had learned no merges for Devanagari or Telugu script: each character's 3 UTF-8 bytes became 3 tokens, and the Hindi sentence cost 7× as many tokens as the English one. The same information costs Hindi and Telugu speakers more money, fits less of their text in the context window, and gives the model less to learn from. Multilingual tokenizers are trained on balanced multilingual text for exactly this reason. Every sentence still round-tripped exactly (decode(encode(text)) = text), because byte-level BPE can always fall back to bytes.
How deep to go in tokenization
Volume 17 defines six mastery levels. For this chapter they look like this; the chapter aims at L3 everywhere, and its lab at L4.
| Level | What you can do |
|---|---|
| L1 | Explain tokens, vocabularies and why token counts drive cost and context |
| L2 | Count and inspect tokens for prompts and documents with a model's tokenizer |
| L3 | Explain BPE, WordPiece, Unigram, byte fallback, normalisation and special tokens |
| L4 | Diagnose tokenization problems: multilingual inflation, number splitting, whitespace and Unicode bugs |
| L5 | Choose or train a tokenizer for a model and its languages and domains |
| L6 | Design tokenization strategy for multilingual and multimodal foundation models |
What a token is
A language model never sees characters or words; it sees a sequence of token ids, integers indexing a fixed vocabulary. A tokenizer is the reversible mapping between text and ids:
"Tokenization isn't trivial!" → ["Token", "ization", " isn", "'t", " trivial", "!"] → [3404, 2065, 4183, 956, 36747, 0]
(ids illustrative: each model's tokenizer differs.)
Why it matters to engineers:
- Cost and limits are in tokens: API pricing, rate limits, context windows and output caps are all counted in tokens of that model's tokenizer.
- Behaviour: models reason about what they see; spelling, character counting, arithmetic on long numbers and rare-language text are harder when tokens split them oddly.
- Efficiency: fewer tokens per text = more content per context window, faster generation, lower cost.
Granularity trade-offs
| Unit | Vocabulary | Sequence length | Problems |
|---|---|---|---|
| Characters / bytes | Tiny (256 bytes) | Very long (≈4× subwords for English) | Attention cost grows quadratically; model must learn spelling-to-meaning composition |
| Words | Huge (millions incl. inflections, names, typos) | Short | Out-of-vocabulary words; no sharing between "run", "running", "runner" |
| Subwords | 32k–260k | Moderate (≈ 0.75 words per token in English) | The practical compromise: frequent words are one token, rare words split into pieces, nothing is out of vocabulary |
All mainstream LLM tokenizers are subword tokenizers learned from data: BPE, WordPiece or Unigram.
Unicode and bytes
Text is a sequence of Unicode code points (over 150,000 assigned characters), stored as bytes in an encoding. UTF-8 (chapter 4's encodings) uses 1 byte for ASCII, 2–4 bytes for other characters:
for s in ["A", "é", "అ", "😀"]: # Latin, Latin accent, Telugu, emoji
print(s, hex(ord(s)), list(s.encode("utf-8")))
# A 0x41 [65] · é 0xe9 [195, 169] · అ 0xc05 [224, 176, 133] · 😀 0x1f600 [240, 159, 152, 128]
Byte-level tokenizers start from the 256 possible byte values, so any string, in any language, emoji, or binary-ish junk, can be encoded with no unknown token. Merges then build larger units on top.
Normalisation (NFC/NFKC) may be applied first so visually identical strings ("é" as one code point vs "e" + combining accent) map to the same tokens.
Byte-pair encoding (BPE)
BPE (originally a compression algorithm; applied to NLP by Sennrich et al., 2016) learns merges greedily:
Training
- Start with each word split into base symbols (bytes or characters), with word frequencies from a corpus.
- Count every adjacent pair of symbols, weighted by word frequency.
- Merge the most frequent pair into a new symbol; record the merge rule.
- Repeat until the vocabulary reaches the target size.
Encoding new text: split into base symbols, then apply the learned merges in the order they were learned.
A complete BPE trainer and encoder:
from collections import Counter
def get_pair_counts(words):
pairs = Counter()
for symbols, freq in words.items():
for a, b in zip(symbols, symbols[1:]):
pairs[(a, b)] += freq
return pairs
def merge_pair(words, pair):
merged = {}
for symbols, freq in words.items():
out, i = [], 0
while i < len(symbols):
if i + 1 < len(symbols) and (symbols[i], symbols[i + 1]) == pair:
out.append(symbols[i] + symbols[i + 1]); i += 2
else:
out.append(symbols[i]); i += 1
merged[tuple(out)] = merged.get(tuple(out), 0) + freq
return merged
def train_bpe(corpus_counts, num_merges):
words = {tuple(w): c for w, c in corpus_counts.items()}
merges = []
for _ in range(num_merges):
pairs = get_pair_counts(words)
if not pairs: break
best = max(sorted(pairs), key=pairs.get) # ties → alphabetically first pair
merges.append(best)
words = merge_pair(words, best)
return merges
def encode_word(word, merges):
symbols = list(word)
rank = {pair: i for i, pair in enumerate(merges)}
while True:
candidates = [(rank[(a, b)], i) for i, (a, b) in enumerate(zip(symbols, symbols[1:])) if (a, b) in rank]
if not candidates: return symbols
_, i = min(candidates) # apply the earliest-learned merge first
symbols[i:i + 2] = [symbols[i] + symbols[i + 1]]
corpus = {"low": 5, "lower": 2, "newest": 6, "widest": 3}
merges = train_bpe(corpus, 4)
merges # [('e','s'), ('es','t'), ('l','o'), ('lo','w')]
encode_word("lowest", merges) # ['low', 'est']
encode_word("slowly", merges) # ['s', 'low', 'l', 'y']
Byte-level BPE in practice
GPT-2 and most later models (GPT-4-family cl100k_base, o200k_base; Llama 3+; Qwen; Mistral's Tekken) use byte-level BPE with a pre-tokenisation step: a regex first splits text into chunks (words with their leading space, runs of digits, punctuation, whitespace) and merges never cross chunk boundaries. Consequences:
- A leading space is usually part of the token: " cat" and "cat" are different tokens.
- Digits are often split into groups of up to three ("12345" → "123", "45"), making arithmetic more regular; some tokenizers split every digit.
- Merges are learned on byte sequences, so non-Latin scripts start from multi-byte sequences and need many merges to become efficient.
WordPiece
Used by BERT and its descendants. Like BPE it grows a vocabulary by merging, but instead of the most frequent pair it picks the pair that most increases the training data's likelihood under a unigram model: score(a, b) = count(ab) / (count(a) · count(b)). That prefers pairs whose parts rarely appear apart. Continuation pieces are marked with "##": "tokenization" → ["token", "##ization"]. Encoding is greedy longest-match-first from the left.
Unigram language model and SentencePiece
The Unigram method (Kudo, 2018) works in reverse:
- Start from a large candidate vocabulary (all frequent substrings).
- Fit a unigram language model: each token has a probability; a segmentation's probability is the product of its tokens' probabilities; the best segmentation of a word is found with the Viterbi algorithm (dynamic programming).
- Repeatedly remove the tokens whose removal least reduces the corpus likelihood, until the target size is reached.
Because it is probabilistic, it can sample alternative segmentations during training ("subword regularisation"), improving robustness.
SentencePiece (Google) is a library and format implementing BPE and Unigram that treats input as a raw stream of Unicode characters, including spaces (encoded as "▁"), so it needs no language-specific pre-tokeniser and works for languages without spaces (Japanese, Chinese, Thai). With byte fallback, unknown characters fall back to UTF-8 bytes. Used by T5, Llama 1–2, Gemma, many multilingual models.
| Algorithm | Builds vocab by | Encoding | Typical users |
|---|---|---|---|
| BPE (byte-level) | Merging most frequent pairs | Apply merges in learned order | GPT family, Llama 3+, Qwen, Mistral |
| WordPiece | Merging pairs maximising likelihood | Greedy longest match | BERT, DistilBERT, many encoders |
| Unigram (SentencePiece) | Pruning a large vocab by likelihood | Viterbi best segmentation | T5, ALBERT, XLNet, Gemma |
Special tokens and chat templates
Vocabularies reserve special tokens that never come from normal text:
- Sequence boundaries:
<|begin_of_text|>,<s>,</s>,<|endoftext|>. - Padding
<pad>, unknown<unk>(rare with byte fallback), masking[MASK], classification[CLS], separator[SEP]. - Chat roles and turns:
<|start_header_id|>user<|end_header_id|>,<|im_start|>assistant, end-of-turn markers. - Tool calls, thinking segments, images or audio placeholders in multimodal models.
Chat models are trained on conversations serialised with a specific chat template. Using the wrong template (or hand-building prompts with the wrong special tokens) silently degrades quality. Libraries render templates for you:
from transformers import AutoTokenizer
tok = AutoTokenizer.from_pretrained("Qwen/Qwen3-0.6B")
messages = [{"role": "system", "content": "You are concise."},
{"role": "user", "content": "What is BPE?"}]
text = tok.apply_chat_template(messages, tokenize=False, add_generation_prompt=True)
print(text) # <|im_start|>system\nYou are concise.<|im_end|>\n<|im_start|>user\n...<|im_start|>assistant\n
ids = tok(text, add_special_tokens=False).input_ids
Token budgets and cost
A context window must hold everything: system prompt, tool definitions, retrieved documents, conversation history, the user message, and room for the output (and, for reasoning models, thinking tokens).
input_tokens + output_tokens ≤ context_window
Rules of thumb for English with modern tokenizers: about 4 characters or 0.75 words per token; 1,000 tokens ≈ 750 words. Code, JSON and non-English text usually need more tokens per character.
Cost arithmetic (prices illustrative; check your provider):
def request_cost(input_tokens, output_tokens, in_price_per_m, out_price_per_m, cached_tokens=0, cache_discount=0.9):
fresh = input_tokens - cached_tokens
return (fresh * in_price_per_m + cached_tokens * in_price_per_m * (1 - cache_discount)
+ output_tokens * out_price_per_m) / 1_000_000
# A RAG request: 1.5k system+tools, 6k retrieved context, 500 question/history, 700 output
per_req = request_cost(8_000, 700, in_price_per_m=3.0, out_price_per_m=15.0)
round(per_req, 4), round(per_req * 1_000_000, 0) # ≈ $0.0345 per request; ≈ $34,500 per million requests
cached = request_cost(8_000, 700, 3.0, 15.0, cached_tokens=1_500) # cache the stable 1.5k prefix
round(cached, 4) # ≈ $0.0305
Output tokens typically cost several times more than input tokens and dominate latency (they're generated one at a time, chapter 157). Budget levers: shorter system prompts, retrieving fewer but better chunks, summarising history, structured outputs that avoid verbosity, prompt caching for stable prefixes, smaller models for easy steps (routing, chapter 158).
Fairness, languages and quirks
- Multilingual inefficiency: tokenizers trained mostly on English need many more tokens for the same content in other scripts: Telugu, Hindi, Amharic or Burmese text can take several times as many tokens as an English translation, meaning higher cost, less effective context and often lower quality. Larger, more multilingual vocabularies (e.g. 200k+ entries) reduce the gap.
- Code: whitespace-heavy languages (Python indentation) benefit from tokens for runs of spaces; tokenizers trained with code handle this well.
- Numbers: inconsistent splits ("2024" as one token, "2025" as two) make arithmetic and digit-level tasks harder; tool use (a calculator, code execution) is the reliable fix.
- Spelling and counting: "how many r's in strawberry?" is hard when the word is one or two tokens; the model never sees its letters directly.
- Glitch tokens: tokens that appeared in tokenizer training data but almost never in model training data (e.g. usernames from scraped forums) had poorly trained embeddings and triggered bizarre behaviour in older models.
- Prompt boundaries: ending a prompt with a trailing space or half a word changes which tokens are natural next; "token healing" in some libraries backs up and regenerates the boundary token.
- Different models, different counts: never estimate one provider's token count with another's tokenizer for hard limits; use the provider's counting API or tokenizer.
Tokenizer libraries
# Python: tiktoken (OpenAI encodings), Hugging Face tokenizers/transformers, sentencepiece
import tiktoken
enc = tiktoken.get_encoding("o200k_base")
ids = enc.encode("Tokenization isn't trivial!")
len(ids), [enc.decode([i]) for i in ids]
from tokenizers import Tokenizer, models, trainers, pre_tokenizers # Rust core, Python bindings
tk = Tokenizer(models.BPE(unk_token=None))
tk.pre_tokenizer = pre_tokenizers.ByteLevel(add_prefix_space=False)
tk.train(["corpus.txt"], trainers.BpeTrainer(vocab_size=8000, special_tokens=["<|endoftext|>"]))
// Rust: Hugging Face `tokenizers` crate (the engine behind the Python library), tiktoken-rs
use tokenizers::Tokenizer;
let tok = Tokenizer::from_file("tokenizer.json")?;
let enc = tok.encode("Tokenization isn't trivial!", false)?;
println!("{:?} {:?}", enc.get_ids(), enc.get_tokens());
// Go: tiktoken-go (community port) or call a tokenizer service
import "github.com/pkoukk/tiktoken-go"
enc, _ := tiktoken.GetEncoding("cl100k_base")
ids := enc.Encode("Tokenization isn't trivial!", nil, nil)
fmt.Println(len(ids))
// Java: DJL's HuggingFaceTokenizer (Rust tokenizers via JNI), or JTokkit for tiktoken encodings
try (HuggingFaceTokenizer tok = HuggingFaceTokenizer.newInstance(Paths.get("tokenizer.json"))) {
Encoding e = tok.encode("Tokenization isn't trivial!");
System.out.println(Arrays.toString(e.getIds()));
}
EncodingRegistry reg = Encodings.newDefaultEncodingRegistry(); // JTokkit
int n = reg.getEncoding(EncodingType.O200K_BASE).countTokens("Tokenization isn't trivial!");
// JavaScript/TypeScript: js-tiktoken, @huggingface/transformers (tokenizers in the browser)
import { getEncoding } from "js-tiktoken";
const enc = getEncoding("o200k_base");
console.log(enc.encode("Tokenization isn't trivial!").length);
Practical rules for engineers
- Count with the target model's tokenizer (or the provider's token-counting endpoint) before enforcing limits.
- Budget the whole window: reserve output space; truncate or summarise inputs deliberately (keep instructions and the latest turns; trim retrieved context first).
- Chunk documents by tokens, not characters, for embeddings and RAG (chapter 161), respecting the embedding model's own limit.
- Use chat templates from the model's tokenizer configuration; never hand-roll special tokens.
- Treat user text as text: disable special-token parsing for untrusted input.
- Watch multilingual cost and test quality per language.
- Delegate exact character, digit and arithmetic work to tools.
- When fine-tuning, the tokenizer is fixed by the base model; adding tokens requires resizing embeddings and enough data to train them.
Lab: training BPE tokenizers on this textbook
Hugging Face tokenizers 0.23.3 on the lab machine. Corpus: the Markdown chapters of every volume of this textbook written so far (excluding Volume 10, kept aside for chapter 158), with quizzes, code blocks and diagram markup removed: about 5.08 million characters, almost entirely English. 95% trains the tokenizer; the last 5% (254,134 characters, 38,791 whitespace-separated words, 254,695 UTF-8 bytes) is held out. Byte-level pre-tokenisation (GPT-2 style), no prefix space.
Experiment 1: vocabulary size
| Vocab | Train time | Held-out tokens | Tokens/word | Chars/token |
|---|---|---|---|---|
| 512 | 0.9 s | 132,943 | 3.43 | 1.91 |
| 2,048 | 1.0 s | 87,737 | 2.26 | 2.90 |
| 8,192 | 1.2 s | 64,740 | 1.67 | 3.93 |
| 32,768 | 1.5 s | 57,303 | 1.48 | 4.43 |
Each 4× increase in vocabulary saved less than the one before (−34%, −26%, −11%): diminishing returns, since the most frequent strings are merged first. For comparison, commercial English-heavy tokenizers with 100,000–200,000 tokens reach roughly 4–4.5 characters per token on ordinary English prose; this small, technical corpus already gets close at 32,768.
Experiment 2: what gets split
English sentence (57 chars) → 23 tokens: 'T' 'od' 'ay' "'s" ' lunch' ' is' ' d' 'al' ' t' 'ad' 'ka' ' with' ' j' 'e' …
"Order 4729183 costs ₹1,234.50" (29 chars, 31 bytes) → 14 tokens: 'Order' ' 47' '2' '9' '18' '3' ' costs' ' ₹' '1' ',' '23' '4' '.' '50'
"Today" was split as 'T' 'od' 'ay' because capitalised sentence-initial "Today" was rare in this corpus, while ' lunch' (lower case, with its space) was common: the same word can tokenize differently by case and position, which is one reason prompts that differ only in spacing or capitalisation can behave differently.
Experiment 3: multilingual inflation
| Sentence | Characters | Bytes | 512 | 2,048 | 8,192 | 32,768 |
|---|---|---|---|---|---|---|
| English | 57 | 57 | 32 | 26 | 23 | 17 |
| Hindi | 64 | 164 | 164 | 164 | 164 | 114 |
| Telugu | 64 | 172 | 172 | 172 | 172 | 122 |
| number string | 29 | 31 | 25 | 22 | 14 | 12 |
| two lines of Python | 50 | 50 | 39 | 31 | 24 | 21 |
Decoding single byte tokens of a Devanagari character gives invalid partial UTF-8, which is why streaming LLM output must buffer bytes until a character is complete. Round trip decode(encode(s)) == s held for every sample. At 32,768 the tokenizer had learned a few merges from the handful of Indian-script characters and symbols present (the rupee sign, names), cutting Hindi from 164 to 114, still 6.7× English.
Try it yourself
- Train a 32,768-token tokenizer on a mix of this corpus and some Hindi or Telugu text you write or have the rights to, and remeasure the three sentences.
- Add a digit-splitting pre-tokenizer (
pre_tokenizers.Digits(individual_digits=True)) and compare token counts for the number string. - Train a Unigram tokenizer (
models.Unigram) at 8,192 and compare tokens per word with BPE. - Count how many of the 8,192 tokens appear fewer than 10 times in the training text. Why does that matter for the model?
Revision sheet: tokenization
Key ideas
- Tokens are vocabulary entries; models consume and emit token IDs; cost, latency and context are measured in tokens.
- Granularity: characters (long sequences), words (huge vocabularies, unknown words), subwords (the compromise).
- Algorithms: BPE (merge frequent pairs), WordPiece (likelihood-based merges, BERT), Unigram (prune a large vocabulary probabilistically, SentencePiece).
- Byte-level vocabularies guarantee any text is encodable (byte fallback); decoding needs care with partial UTF-8.
- Normalisation (Unicode NFKC, case, whitespace) and pre-tokenisation (splitting on spaces, digits, punctuation) shape results.
- Special tokens: beginning/end of text, padding, chat role markers, tool-call markers.
- Effects: multilingual inflation, irregular number splits, whitespace/case sensitivity, glitch tokens from rare vocabulary entries.
Numbers to remember
- Lab: vocab 512 → 32,768 cut held-out tokens from 132,943 to 57,303 (3.43 → 1.48 tokens/word).
- Lab: a Hindi sentence took 164 tokens vs 23 for English (8,192 vocab, English-trained).
- English prose ≈ 4 characters per token with large production tokenizers.
Pitfalls
- Estimating cost or context in words or characters instead of tokens.
- Using a tokenizer trained on one language or domain for another.
- Mismatched tokenizer and model (IDs mean different things).
- Breaking multi-byte characters when streaming.
- Prompt formats with inconsistent spaces or special tokens.
Glossary
- Vocabulary: the set of tokens a model knows.
- Merge rule: a learned pair-to-token rule in BPE.
- Byte fallback: encoding unknown characters as raw bytes.
- Fertility: tokens per word for a language.
- Special token: a reserved token with control meaning.