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

UnitVocabulary"Court Sq-23 St" becomesTrouble
Characters~100 (or 256 bytes)14 tokensLong sequences: attention costs grow with the square of the length (chapter 7)
Wordshundreds of thousands3 or 4 tokensEvery new word, typo, name or number is "unknown"; "run", "runs", "running" share nothing
Subwords30,000 – 200,000a handfulCommon 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?

That's the point of subwords: "Strawberry" isn't a station, but "St", "raw" (maybe), "berry"-like pieces or single letters still cover it. A typo costs a few extra tokens, never a crash.

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
  1. 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.
  2. 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.)
  3. Shorter text for the model means more text fits in the context window, and each step of attention covers more meaning.
  4. 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.
  5. 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):

TextGPT-2 (50,257 tokens)GPT-4 (cl100k, 100,277)GPT-4o (o200k, 200,019)
Hello, how are you today?777
Привіт, як ти сьогодні? (the same, in Ukrainian)26169
こんにちは、今日は元気ですか? (in Japanese)22108
strawberryst · raw · berrystr · aw · berryst · raw · berry
12345 + 67890123 · 45 · + · 6 · 78 · 90123 · 45 · + · ␣ · 678 · 90123 · 45 · + · ␣ · 678 · 90

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

\(26 / 7 \approx 3.7\). With GPT-4o's tokenizer it's \(9 / 7 \approx 1.3\). Tokenizers decide prices and context lengths per language, which is a fairness question as much as a technical one.

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

5. What to carry forward

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