AI from scratch · Tokens · Stage 5: seeing and reading
Text as numbers: tokens
A network only takes numbers. Chapter 10's transformer and the RNN lesson read station names one character at a time. Real language models don't: they read tokens, pieces of text from a vocabulary of 50,000 to 200,000 that a separate algorithm learned before the model ever trained. The choice of pieces decides how long every text is, what the model can easily see, and what it costs to run. It's also behind some famous chatbot failures: counting the r's in "strawberry", adding long numbers, charging more for the same sentence in Ukrainian than in English. This lesson builds a tokenizer by hand.
1. Three ways to cut text
| Unit | Vocabulary | "Court Sq-23 St" becomes | Trouble |
|---|---|---|---|
| Characters | ~100 (or 256 bytes) | 14 tokens | Long sequences: attention costs grow with the square of the length (chapter 7) |
| Words | hundreds of thousands | 3 or 4 tokens | Every new word, typo, name or number is "unknown"; "run", "runs", "running" share nothing |
| Subwords | 30,000 – 200,000 | a handful | Common words are one token, rare ones split into pieces, nothing is unknown |
Subwords won, and the usual way to find them is byte-pair encoding (BPE): start from single characters and repeatedly glue together the pair that appears most often.
Characters make sequences too long and words make vocabularies too big; subwords keep common words whole and split rare ones into pieces.
2. Byte-pair encoding, built live
The corpus is the 379 NYC subway station names. Every name starts as a list of characters. Each merge finds the most frequent neighboring pair across all names and makes it one new token. Slide the number of merges, and type to see how text gets cut.
The first merges are " S", " St", "Av", " Av": the corpus's favorite endings. By 300 merges an average station name shrinks from about 12 characters to about 5 tokens, and "Court Sq" is just "Court" and " Sq". A word the corpus never saw, like "Strawberry", still works: it falls back to smaller pieces, down to single characters if needed. Nothing is ever unknown.
The box uses one piece of Python the path hasn't needed yet: a while loop. for runs once per item of a list; while condition: repeats its indented lines as long as the condition is true, checking it before each round. merge needs it because it moves through the tokens by 1 or by 2, depending on whether it just glued a pair: while i < len(w): keeps going until it has passed the last token. (If nothing inside ever makes the condition false, it loops forever; here every round moves i forward.)
After BPE learns its merges, how is a word it never saw during training tokenized?
- As one "unknown" token
- It's added to the vocabulary
- By applying the learned merges in order: frequent pieces it contains merge, the rest stay as smaller pieces or characters
BPE starts from characters and keeps gluing the most frequent neighboring pair, so the vocabulary grows toward the corpus's common pieces and any new text can still be cut.
Why BPE is a kind of compression
- Each merge replaces every occurrence of a pair with one token, so the corpus gets shorter by exactly the pair's count. Choosing the most frequent pair is choosing the merge that shortens it most.
- So BPE is a greedy compressor: each step makes the biggest saving available right now. (It's how Philip Gage introduced it in 1994, as a data compression scheme.)
- Shorter text for the model means more text fits in the context window, and each step of attention covers more meaning.
- But every merge adds a row to the embedding matrix (chapter 7) and a column to the output layer: a vocabulary of 200,000 with 4,096-number embeddings is 0.8 billion parameters in each. The vocabulary size is a trade between sequence length and those two layers.
- Probability 5's link: a model's loss is measured per token, and bits per character is that loss divided by the average characters per token. Comparing models with different tokenizers needs the per-character (or per-byte) number.
3. Bytes, so nothing is unknown
Text in a computer is UTF-8 bytes: English letters take 1 byte each, accented and Cyrillic letters 2, Chinese and Japanese characters 3, emoji 4. GPT-2's tokenizer starts BPE from the 256 possible bytes instead of characters, so any text in any language, and any emoji, can be encoded.
Text is stored as UTF-8 bytes (1 to 4 per character), and byte-level BPE starts from those 256 bytes, so every text in every language can be tokenized.
4. Real tokenizers, and their famous failures
OpenAI's tokenizers, counted with their own library (tiktoken):
| Text | GPT-2 (50,257 tokens) | GPT-4 (cl100k, 100,277) | GPT-4o (o200k, 200,019) |
|---|---|---|---|
Hello, how are you today? | 7 | 7 | 7 |
Привіт, як ти сьогодні? (the same, in Ukrainian) | 26 | 16 | 9 |
こんにちは、今日は元気ですか? (in Japanese) | 22 | 10 | 8 |
strawberry | st · raw · berry | str · aw · berry | st · raw · berry |
12345 + 67890 | 123 · 45 · + · 6 · 78 · 90 | 123 · 45 · + · ␣ · 678 · 90 | 123 · 45 · + · ␣ · 678 · 90 |
- Counting letters. The model never sees the letters of "strawberry", only three token ids (and with a space before it, one id for the whole word). How many r's are inside token 4, 67, 1987 is something it can only have memorized, which is why "how many r's in strawberry?" tripped up chatbots for years.
- Arithmetic. 12345 is cut into "123" and "45", 67890 into "678" and "90": the pieces don't line up by place value, so adding them digit by digit is awkward. Some newer models split numbers into single digits for exactly this reason.
- Languages. A tokenizer trained mostly on English text has few merges for Ukrainian or Japanese, so the same sentence costs 2 to 4 times the tokens: more money per request, less text in the context window, and less meaning per attention step. Each newer tokenizer narrows the gap.
The Ukrainian sentence costs 26 GPT-2 tokens; the English one, 7. If an API charges per token, how many times more does the Ukrainian question cost? (One decimal.)
Models see token ids, not letters or digits, which is why spelling, digit arithmetic and non-English text are harder and costlier than they look.
Where it breaks: tokens the model barely knows
- Glitch tokens. GPT-2's tokenizer was trained on a different text collection than the model. A few merges, like " SolidGoldMagikarp" (a Reddit user name, one token), were frequent in the tokenizer's data and nearly absent from the model's, so their embeddings were barely trained: GPT-3-era models produced bizarre answers when asked to repeat them. Train the tokenizer on data like the model's.
- Spaces matter. " strawberry" (with a leading space) is one token; "strawberry" at the start of a line is three. The same word gets different ids in different positions, which can make prompts behave differently after a trivial edit.
- Changing the tokenizer means retraining. Embedding rows belong to specific ids. Swap the tokenizer and the model's input and output layers no longer mean anything: fine-tuning can't fix it, only (expensive) retraining can.
5. What to carry forward
- Models read token ids; each id looks up a row of the embedding matrix (chapter 7) and the output layer scores every id.
- BPE: start from characters or bytes, merge the most frequent pair, repeat. Nothing is unknown.
- Vocabulary size trades sequence length against embedding and output layer size.
- Tokens explain letter counting, digit arithmetic, per-language costs and prompt sensitivity to spaces.
- Compare models with different tokenizers per character or per byte, not per token.
All lessons: AI from scratch. Token counts: OpenAI's tiktoken library. Andrej Karpathy's "Let's build the GPT Tokenizer" video is the long-form companion.
Last updated