Tokens: Turning Text into Numbers
A decoder needs numbers rather than raw text. Tokenization defines the pieces it predicts. Follow bytes through reusable merges, then compare the choices and their failure cases.
#Section 1The One Job a Language Model Has
Your phone suggests a word after “see you”. A language model uses the same prediction task at a larger scale, conditioning on a longer prefix and a learned representation of it.
That is worth saying slowly, because everything in this chapter serves that one sentence. A language model does not “understand the question” and then “write an answer” as two separate steps. It predicts the next piece of text. Then it predicts the one after that. Answering questions, writing code and holding a conversation all fall out of doing that one thing extremely well.
A probability for every possible next piece
The model assigns a probability to every possible next token. After “I’ll have a cup of”, a trained model may favor tea over rocks. The probabilities sum to one.
The word for one of these pieces is token. A token is usually a whole common word like tea, a chunk of a rarer word like happi, or a single punctuation mark. The full list of tokens a model knows is its vocabulary, and its size is written . For Finch-19, .
A conditional probability describes a chance given a prefix. The bar in the notation means "given"; changing the prefix changes the prediction.
Writing one token at a time
Generation selects a token, appends it, and predicts again. This feedback of previous outputs into the next input is autoregressive generation.
Each chosen token becomes context for the next decision. A cache retains intermediate computation, not a separate plan of what the model intends to say.
A tokenizer splits text into pieces and assigns each an ID, making it usable by the network.
#Section 2Text Is Already Numbers
A byte is a unit of storage with 256 possible values. UTF-8 encodes characters as byte sequences, which gives tokenization a representation that can cover any valid text.
UTF-8 uses different numbers of bytes for different characters. English letters, accented letters, and emoji therefore have different storage lengths; a character is not the same as a byte.
So we never have to invent a way to turn text into numbers. UTF-8 already did it. The only question left is how to group those bytes into useful pieces.
#Section 3What Should One Token Be?
Suppose we have to pick one rule for cutting text into tokens. Take the word unhappiness and try four candidates. The choice looks like a technical detail, but it decides how long every input is and how large the model's first table must be, so it is worth getting right.
Whole words are the obvious first idea. unhappiness becomes one token, which is wonderfully short. The trouble is the vocabulary. You need one entry for every word that has ever existed, in every language, every spelling mistake, every product name. Any word you did not include becomes a special "unknown" token, written [UNK], and the model loses all information about it. A name it has never seen, a new slang word, a typo: all of them collapse into the same meaningless token.
Characters fix the unknown-word problem for English, but the vocabulary is still about 150,000 Unicode characters, and sequences get long: unhappiness is eleven tokens. Long sequences are expensive, as Part X will show in detail, because attention compares every token with every other token.
Raw bytes go all the way down. The vocabulary is exactly 256, nothing can ever be unknown, and any text in any language can be spelled. But sequences get even longer, and an emoji costs four tokens.
Byte pair encoding, or BPE, takes the middle road. It starts from the 256 bytes, so nothing is ever unknown, and then adds common chunks on top: un, happi, ness, the, ing, and tens of thousands more. Common words become one token, rare words become a few familiar pieces, and anything truly strange falls back to bytes.
| Scheme | Vocabulary size | unhappiness | Unknown words? | Sequence length |
|---|---|---|---|---|
| Words | hundreds of thousands, open-ended | 1 token | yes, [UNK] |
shortest |
| Characters | about 150,000 | 11 tokens | rarely | long |
| Bytes | 256 | 11 tokens | never | longest for non-English |
| Byte-level BPE | 256 + merges (32k to 256k) | about 3 tokens | never | short |
Byte pair encoding started life in 1994, when Philip Gage published it as a simple data compression algorithm. In 2016 Rico Sennrich and colleagues adapted it for machine translation, applying it to characters. GPT-2 in 2019 made the change that stuck: run BPE on raw UTF-8 bytes instead of characters. That version, byte-level BPE, is what GPT-2, GPT-3, GPT-4, Llama 3 and most current models use, and it is what Finch-19 uses.
#Section 4Drawing Walls Before Merging
Before BPE starts gluing bytes together, the tokenizer first splits the text into rough chunks: words, numbers, punctuation and whitespace. This step is called pre-tokenization. Think of it as drawing walls through the text. Later, merges are only allowed inside a wall, never across one.
Why bother? Without walls, BPE would happily learn tokens like dog. with the full stop stuck on, or of the glued across a space, because those byte sequences are common. Then dog., dog, and dog! would be three unrelated tokens, and the model would have to learn three times over that they all mean dog. Walls keep tokens sensible.
GPT-2's walls come from a single pattern (a regular expression, a little rule written in a text-matching language). In plain words it says: a chunk is an optional space followed by a run of letters, or an optional space followed by a run of digits, or an optional space followed by a run of punctuation, or a run of whitespace, or one of the English contractions 's, 't, 're, 've, 'm, 'll, 'd.
Look closely at where the spaces go. The space before pay is glued to the front of pay, giving ␠pay. This convention has a large effect later: the at the start of a sentence and ␠the in the middle of one end up as two different tokens with two different ids. Notice also that 1,250 became three chunks, ␠1, , and 250, because digits and punctuation sit in different walls.
Llama 3 and GPT-4 use slightly different patterns. One notable change: they split numbers into chunks of at most three digits, so 1234567 becomes 123, 456, 7 rather than whatever the merges happened to learn. We return to why in Section 8.
#Section 5Learning the Merges, by Hand
BPE stands for byte pair encoding, and the training procedure is simple enough to do with a pencil. Start with every chunk spelled out as bytes. Count every pair of neighbouring tokens across the whole training text. Find the most frequent pair. Glue it into one new token, give it the next free id, and record the rule. Repeat until you have as many tokens as you want. The ordered list of rules is the tokenizer.
Start with a toy corpus containing banana, bandana, band, and bad. Split each into bytes, then learn reusable pieces from repeated neighboring pairs.
Step 0: count the pairs
Count adjacent pairs across the corpus, weighting each word by its frequency. Here a + n is most frequent, so the first merge makes an.
So the first rule is a + n → an, with id 256. Replace every a n in the corpus with the single token an. banana becomes b an an a, and the corpus shrinks from 43 tokens to 31.
Keep going
Recount after each merge because the available neighbors change. Later steps build ban, ana, band, then whole frequent words. The figure shows the sequence.
Real tokenizers stop at a chosen vocabulary budget. New pieces reuse earlier merges; rare words can still be represented using smaller pieces.
Use a fixed tie-breaking rule and save the ordered merge list. Both affect which tokenizer training produces.
#Section 6Encoding New Text
Training produced an ordered list of merges. To tokenize new text, called encoding, we pre-tokenize it into chunks, spell each chunk as bytes, and then replay the merges in the order they were learned, applying each one everywhere it matches. When we reach the end of the list, the tokens left over are the answer, and their ids are what the model receives.
For unseen bandanas, replay the learned merges until bandana remains beside the final s. Reusable pieces encode a word that never appeared in tokenizer training.
An unseen word came out as a familiar token plus one byte. That is the whole promise of byte-level BPE: common things are cheap, new things are a few familiar pieces, and nothing is ever unknown.
The order matters because merges compete for the same bytes. If you applied ban + d before b + an, there would be no ban token yet and the rule would never fire, giving a different, longer encoding. This is why the tokenizer file stores merges as an ordered list, and why "the same vocabulary with merges in a different order" is a different tokenizer. Decoding, turning ids back into text, is simpler: look up the bytes for each id, join them, and interpret the result as UTF-8.
#Section 7How Big Should the Vocabulary Be?
Every merge adds one token to the vocabulary. So how many merges should we learn? There is no free lunch, and the trade-off is easy to state.
A larger vocabulary usually makes sequences shorter, but additional rare pieces offer diminishing returns. Shorter sequences reduce downstream work and fit more text into a context window.
Each vocabulary entry needs a learned embedding row. A larger vocabulary increases that table and leaves rare rows with fewer training updates.
Multilingual coverage affects the choice too: useful pieces for one language may fragment another. Choose a tokenizer using representative text rather than one universal characters-per-token rule.
Comparing models with different tokenizers
The vocabulary choice causes one more subtle problem: it makes models hard to compare. The usual score for a language model is its average loss per token, a measure of surprise we define properly in Part XIII. For now, think of it as "how badly the model was surprised by the real next token, on average", measured in units called nats. Lower is better. People often report perplexity instead, which is raised to the loss: roughly, how many tokens the model was torn between at each step.
Here is the snag. Loss and perplexity are measured per token. If model B uses a smaller vocabulary, its tokens are shorter, each prediction is easier, and its per-token score looks better even if it understands text worse. The fair fix is to measure surprise per byte of original text, which is the same for everyone. That is bits per byte:
Bits per byte spreads prediction cost over the original text's bytes. A lower token loss can still mean worse compression if the tokenizer uses smaller pieces, as the figure shows.
#Section 8Where Tokenizers Bite
Tokenizers are full of small surprises that bite people in real projects. None of them is deep, but each one has cost someone days of debugging, and interviewers like them because they reveal whether you have shipped anything.
Emoji and other multi-byte characters can split across tokens. 🙂 is four bytes, and the merges might cut it as two tokens of two bytes each. When a model streams its answer token by token, the screen shows broken replacement symbols (�) until the second half arrives. The fix is to buffer bytes until they form complete UTF-8 characters before displaying them.
“ the” and “the” are different tokens. Section 4 showed why: the space travels with the following word. A stray space at the end of a prompt can change what the model does next.
Numbers split unevenly. With plain BPE, 1234567 might become 123, 45, 67, chunks that do not line up with thousands, hundreds and units. That makes arithmetic harder to learn, because the same digit position lands in different places of different tokens. This is why Llama 3 and GPT-4 split digits into groups of at most three, and some models split every digit separately.
Some languages cost more. Merges are learned from the tokenizer’s training text. If that text is mostly English, English words become single tokens while Hindi or Thai stay split into many small byte-level pieces. The same sentence then costs several times more tokens, which means more money per request and less room in the context window. The fix is to train the tokenizer on a balanced multilingual corpus.
Case changes everything. Hello, hello and HELLO usually get completely different ids. To the tokenizer they are unrelated; the model has to learn from examples that they mean the same thing. This is not a bug to fix, just something to know.
Special tokens are not text. Markers like <|endoftext|> tell the model where a document ends. They must be single reserved ids, added outside the merge process. If a user types that literal string into a chat, it should be encoded as ordinary text (thirteen bytes’ worth of tokens), never as the real marker, or users could forge document boundaries.
Some tokens are under-trained. A token can be common in the tokenizer’s training data but almost absent from the model’s training data. The famous example is ␠SolidGoldMagikarp, a Reddit username that became a single GPT-2 token. Researchers found in 2023 that models produced bizarre output when asked to repeat it, because its embedding row had barely been trained. The fix is to train the tokenizer on data that looks like the model’s.