Highlights

Contents

Part I
01

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.

YOU ARE HERE"raw text"tokenizerembeddings+ positionslearnedwavesRoPEDECODER BLOCK× NnormattentionQKVsoftmaxmaskheadsn × n+normMLP+residual streamKV cachefinal normLM headsoftmaxP(next)training: the loss sends a correction back to every weight

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

ONE PREDICTION = ONE PROBABILITY FOR EVERY TOKEN IN THE VOCABULARYI’llhaveacupof0.638tea0.235coffee0.095water0.032rocks≈ 0 each…31,996 moreall 32,000 bars add up to 1Values are illustrative: they are what a well-trained model might say after this prompt.
Figure 1.1One prediction. After the prompt, the model hands back a probability for every token it knows. Most of the 32,000 bars are tiny; a handful carry nearly all the weight. (Values are illustrative.)

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 VV. For Finch-19, V=32,000V = 32{,}000.

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.

STEP 1ThecatsatFinch-19becauseP(because | The cat sat)STEP 2ThecatsatbecauseFinch-19itP(it | The cat sat because)append it,feed it back insame weights every steprepeat until an end-of-text token appears or a length limit is reached
Figure 1.2Autoregressive generation. The same model with the same weights runs once per new token. Each output is appended to the input before the next step, which is why chat answers appear one piece at a time.

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.

UTF-8: EVERY CHARACTER IS STORED AS 1 TO 4 BYTEScharsbytesn6Ea61ïC3AF2 bytesv76e65␠20c63a61f66éC3A92 bytes␠20🙂F09F99824 bytes12 characters → 17 bytes
Figure 1.3UTF-8. Each character sits above the bytes that store it. Plain letters are one byte; accented letters take two; the emoji takes four. Twelve characters become seventeen bytes.

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.

FOUR WAYS TO CUT THE WORD “UNHAPPINESS”wordsunhappiness1 tokenvocab: every word ever written; a new word becomes [UNK]charactersunhappiness11 tokensvocab: about 150,000 Unicode charactersbytes756E68617070696E65737311 tokensvocab: 256. Never unknown, but long.BPEunhappiness3 tokensvocab: 256 bytes + learned mergesshort AND neverunknown
Figure 1.4Four answers to "what is a token?". Words are short but fail on new words; characters and bytes never fail but make long sequences; BPE is short for common text and never unknown.
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.

PRE-TOKENIZATION: SPLIT INTO CHUNKS BEFORE ANY MERGINGIword’llsuffix␠payword␠1number,symbol250number␠forword␠3number␠catsword!!symbolred bars are walls: merges never cross them“I’ll pay 1,250 for 3 cats!!” → 10 chunks
Figure 1.5Pre-tokenization. The sentence is split into ten chunks before any merging happens. Notice that the space travels with the word after it, so "␠cats" with its space is one chunk.

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.

STEP 0: COUNT EVERY PAIR OF NEIGHBOURS, WEIGHTED BY HOW OFTEN THE WORD APPEARS×3banana×2bandana×2band×1bada + n12b + a8n + a8n + d4d + a2a + d1a + n wins with 12corpus: 8 words, 43 bytes, 43 tokens
Figure 1.6The first counting pass. Each word is spelled out in single bytes with its frequency on the left; the bars count every adjacent pair across the corpus. The pair a + n wins with 12.

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.

SIX MERGES LEARNED FROM THE TOY CORPUS, IN ORDERidmerge rulecorpus after this merge (banana ×3, bandana ×2, band ×2, bad ×1)tokens256a + n → anseen 12 timesbananabandanabandbad31257b + an → banseen 7 timesbananabandanabandbad24258an + a → anaseen 5 timesbananabandanabandbad19259ban + d → bandseen 4 timesbananabandanabandbad15260ban + ana → bananaseen 3 timesbananabandanabandbad12261band + ana → bandanaseen 2 timesbananabandanabandbad10next best pair appears once: stop
Figure 1.7The six merges, in the order they were learned. Each row shows the rule, how often the winning pair appeared, the corpus after applying it, and the total token count. Highlighted chips are the newly created token.

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.

ENCODING A NEW WORD: REPLAY THE MERGES IN THE ORDER THEY WERE LEARNEDraw bytesbandanas8 tokens#256 a + nbandanas6 tokens#257 b + anbandanas5 tokens#258 an + abandanas4 tokens#259 ban + dbandanas3 tokens#260 ban + ana (no match)#261 band + anabandanas2 tokensbanana + ana never fires:there is no "banana" herefinal ids: [261, 115]
Figure 1.8Encoding "bandanas" with the six learned merges. Each row applies one more rule. Merge 260 finds no match because "ban" was already absorbed into "band". The final encoding is two tokens.

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.

BIGGER VOCABULARY: SHORTER SEQUENCES, BIGGER EMBEDDING TABLEvocab size (log scale)bytes per token2564k32k256kFinchillustrative shape: gains flattenvocab size (log scale)embedding parameters (millions), d = 5122564k32k256k16.4M65.7Mexact: V × 512 numbers, a straight lineFinch-19 picks 32,000, the same as Llama 2 and Mistral 7B
Figure 1.9The vocabulary trade-off. Left: the average text covered by one token rises with vocabulary size and flattens (illustrative shape). Right: the embedding table grows in a straight line, exactly V × 512 for Finch-19.

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 ee 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=loss per token (nats)ln⁡2×bytes per token\text{bits per byte} = \frac{\text{loss per token (nats)}}{\ln 2 \times \text{bytes per token}}

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.

TWO MODELS, TWO TOKENIZERS: WHICH ONE IS BETTER?perplexity per token (lower wins)20.1model A13.5model Bbits per byte (lower wins)1.082model A1.250model BA: 3.0 nats per token, 4.0 bytes per token B: 2.6 nats per token, 3.0 bytes per tokenthe rankings flip
Figure 1.10Perplexity and bits per byte disagree. Model B wins per token because its tokens are shorter, but model A spends fewer bits on each byte of real text, so A is the better model.

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

EIGHT PLACES WHERE TOKENIZERS SURPRISE PEOPLEEmoji split mid-character🙂 is 4 bytes; a token boundary can fall inside01“␠the” is not “the”the leading space makes a different token and id02Numbers split unevenly1234567 may become 123 | 45 | 6703Some languages cost moreEnglish-heavy merges split Hindi into many pieces04Case changes the idHello, hello and HELLO are unrelated tokens05Ties in pair countsbreak them by a fixed rule or runs disagree06Special tokens are not text<|endoftext|> must be one reserved id07Under-trained tokenstokens the model almost never saw act strangely08
Figure 1.11Eight common tokenizer surprises. The highlighted one, the leading space, causes more prompt bugs than all the others together.

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.