Module 5 of 129 lessons

Build a GPT-like Language Model

We put the pieces together into a real (tiny) language model, train it on a small text, generate with it, and look honestly at why it makes things up.

Course contents · Module 5 of 12
← Build Claude from scratch
98 lessons · 12 modules
  1. 1Understanding Claude and modern AI6
    1. 1.1What is Claude?
    2. 1.2What is an LLM?
    3. 1.3How ChatGPT, Claude, Gemini and other AI assistants work
    4. 1.4AI, machine learning, deep learning, transformers and LLMs
    5. 1.5What happens when you send a message to an AI?
    6. 1.6Tokens, context windows and embeddings
  2. 2Mathematics and foundations6
    1. 2.1Essential linear algebra
    2. 2.2Vectors, matrices and matrix multiplication
    3. 2.3Probability and statistics
    4. 2.4Softmax, gradients and loss functions
    5. 2.5Neural networks and backpropagation
    6. 2.6Practical Python demonstrations
  3. 3Neural network from scratch7
    1. 3.1Set up Python and NumPy
    2. 3.2Build neurons and layers
    3. 3.3Implement forward propagation
    4. 3.4Implement backpropagation
    5. 3.5Implement gradient descent
    6. 3.6Train a small neural network without PyTorch or TensorFlow
    7. 3.7Visualize training and loss
  4. 4Understanding transformers9
    1. 4.1Why traditional RNNs have limitations
    2. 4.2The transformer architecture
    3. 4.3Tokenization and embeddings
    4. 4.4Positional encoding
    5. 4.5Self-attention and multi-head attention
    6. 4.6Query, Key and Value explained visually
    7. 4.7Feed-forward networks
    8. 4.8Layer normalization and residual connections
    9. 4.9Implement a simplified transformer in NumPy
  5. 5Build a GPT-like model9
    1. 5.1Tokenizer implementation
    2. 5.2Vocabulary creation
    3. 5.3Dataset preparation
    4. 5.4Next-token prediction
    5. 5.5Building a decoder-only transformer
    6. 5.6Training a tiny language model
    7. 5.7Text generation and temperature
    8. 5.8Top-k and top-p sampling
    9. 5.9Understanding hallucinations and limitations
  6. 6How Claude is different9
    1. 6.1Claude's architecture at a conceptual level
    2. 6.2Constitutional AI
    3. 6.3Supervised fine-tuning
    4. 6.4Reinforcement learning from human feedback
    5. 6.5Preference optimization
    6. 6.6Safety training and alignment
    7. 6.7System prompts and instruction following
    8. 6.8Long-context processing
    9. 6.9Tool use and agentic behavior
  7. 7Build your own AI assistant10
    1. 7.1Design a Claude-like chat interface
    2. 7.2Conversation management
    3. 7.3System instructions
    4. 7.4Chat history and context management
    5. 7.5Streaming responses
    6. 7.6Markdown and code rendering
    7. 7.7Syntax highlighting
    8. 7.8Error handling
    9. 7.9File upload and document understanding concepts
    10. 7.10Building a frontend chatbot
  8. 8Memory and RAG8
    1. 8.1What is AI memory?
    2. 8.2Short-term vs long-term memory
    3. 8.3Embeddings and vector databases
    4. 8.4Semantic search
    5. 8.5Retrieval-Augmented Generation (RAG)
    6. 8.6Chunking and document retrieval
    7. 8.7Build a basic document Q&A system
    8. 8.8Context injection and source citations
  9. 9Function calling and agents9
    1. 9.1What is function calling?
    2. 9.2Tool definitions and JSON schemas
    3. 9.3Calling external tools
    4. 9.4Tool execution loops
    5. 9.5Search, calculator and other tools
    6. 9.6Multi-step reasoning and planning
    7. 9.7Agent architecture
    8. 9.8Safety restrictions and tool permissions
    9. 9.9Build a basic tool-using AI agent
  10. 10Fine-tuning and training8
    1. 10.1Pretraining vs fine-tuning
    2. 10.2Dataset collection and cleaning
    3. 10.3Instruction datasets
    4. 10.4Fine-tuning concepts
    5. 10.5LoRA and QLoRA
    6. 10.6GPU and VRAM requirements
    7. 10.7Training costs and realistic hardware requirements
    8. 10.8Model evaluation and benchmarking
  11. 11Deployment and production9
    1. 11.1Model inference
    2. 11.2Quantization
    3. 11.3CPU vs GPU inference
    4. 11.4Running open-source LLMs locally
    5. 11.5Ollama and Hugging Face concepts
    6. 11.6API design
    7. 11.7Docker deployment
    8. 11.8Monitoring and logging
    9. 11.9Security, rate limiting and cost optimization
  12. 12Capstone project8
    1. 12.1Capstone overview and architecture
    2. 12.2The conversational UI
    3. 12.3Conversation history and system prompts
    4. 12.4Streaming output with Markdown and code
    5. 12.5Configurable model providers and error handling
    6. 12.6Document Q&A and memory
    7. 12.7Tool calling
    8. 12.8Testing, deployment and the capstone challenge

Lesson 5.1Module 5: Build a GPT-like model

Tokenizer implementation

  • ⏱ 19 min read
  • Intermediate

Learning objectives

  • Explain why modern tokenizers start from UTF-8 bytes, so that any text, in any language, can be encoded with no "unknown" token.
  • Implement byte-level BPE training, encoding and decoding in plain Python, and check the round trip.
  • Explain pre-tokenization: why text is split into chunks before merging, and what goes wrong without it.
  • Add special tokens safely, so that text typed by a user can never forge them.

This module turns the parts you built in module 4 into a working language model that you train and sample from yourself. The first part of the pipeline is the tokenizer: the program that turns text into a list of integer ids for the model, and the model's output ids back into text. In lesson 4.3 you trained a small character-level BPE tokenizer and saw how merges grow a vocabulary. That version was good for learning the idea, but it had gaps: it could not encode a character it had never seen, it treated "the." and "the" as unrelated words, and it had no way to mark where a document ends. This lesson closes those gaps and produces the tokenizer our tiny GPT will actually use.

Analogy: a court stenographer's shorthand

A court stenographer cannot write every letter of every word at speaking speed, so they invent shorthand: one quick stroke for "the", another for "-ing", another for "objection". Common letter groups get their own symbol; rare words are still spelled out letter by letter, so nothing is ever impossible to write down. A BPE tokenizer is a shorthand learned automatically from data: the most frequent byte pairs get their own symbol first, then pairs of those symbols, and so on. And because the alphabet underneath is the 256 possible bytes, any text at all can still be "spelled out".

Start from bytes, not characters

Computers store text as bytes. The standard encoding, UTF-8, uses one byte for each plain English letter, digit and punctuation mark, two bytes for most accented letters (é is C3 A9), three for most Chinese, Japanese and Korean characters, and four for emoji (😀 is F0 9F 98 80). There are only 256 possible byte values, so if the tokenizer's starting vocabulary is "all 256 bytes", then every possible string can be encoded. There is never an unknown character, never a crash on an unusual name, and never a silent replacement with a placeholder.

That is the idea behind byte-level BPE, used by the GPT-2 family and by many later models. A character-level tokenizer, like the one in lesson 4.3, needs one base symbol for every character it might meet; Unicode has about 150,000 of them, so in practice a character vocabulary must leave some out and fall back to an <unk> token. The byte-level version trades that problem for a different, much milder one: rare characters cost several tokens instead of one. An emoji may take four tokens, but it is still represented exactly.

TextCharactersUTF-8 bytesByte ids before any merge
cat3399, 97, 116
é12195, 169
日13230, 151, 165
😀14240, 159, 152, 128

Pre-tokenization: split into chunks before merging

If you run BPE on raw text, it happily learns merges such as e. (the end of "the." and "here.") or d t (across the gap in "and the"). Those tokens waste vocabulary slots on accidents of punctuation and make the same word come out differently depending on what follows it. Real tokenizers therefore first split text into chunks with a regular expression, then run BPE inside each chunk only. A merge can never cross a chunk boundary.

Our chunk rule is short: an optional space followed by letters, or an optional space followed by digits, or an optional space followed by punctuation, or a run of whitespace. So "The cat sat." becomes the chunks "The", " cat", " sat", ".". Two details matter. First, the space is glued to the front of the next word, so " cat" becomes one token that means "the word cat, not at the start of the text"; this is why tokenizer output so often shows tokens like ␣the (we draw the space as ␣). Second, words and punctuation never share a chunk, so "cat" followed by a full stop is still the token " cat" followed by ".".

Training: count, merge, repeat

Training a BPE tokenizer is a loop that you already know from lesson 4.3, now on bytes:

  1. Split the training text into chunks and count how often each distinct chunk occurs. A chunk like " the" that appears 200 times is stored once with the count 200, which makes training fast.
  2. Write every chunk as its list of byte ids (0 to 255).
  3. Count every adjacent pair of ids inside every chunk, weighted by the chunk's count.
  4. Take the most frequent pair, give it the next free id (256, then 257, and so on), and replace that pair everywhere with the new id. Record the merge.
  5. Repeat until you have the number of merges you asked for, or until no pair occurs at least twice (merging a pair that occurs once saves nothing).

The output is two tables: the ordered list of merges (pair → new id) and the vocabulary (id → the bytes it stands for). The order of the merges is part of the tokenizer: merge 1 was the most frequent pair in the whole corpus, merge 2 the most frequent after that, and so on. Try it below: type any text, then merge one step at a time and watch frequent pieces fuse.

Byte-level BPE, one merge at a timeInteractive

    No merges yet: every token is a single byte. Press "Merge once".

    Each chip is one token; the small number is its id. Ids below 256 are raw bytes; a chip like ⟨C3⟩ is a byte that is only part of a character. Merges never cross the chunk boundaries (spaces stay at the front of words).

    Encoding new text: replay the merges in order

    Once trained, the tokenizer must encode text it has never seen, such as a user's prompt. The rule is: split into chunks, turn each chunk into bytes, then repeatedly apply the earliest-learned merge that is present, until no learned merge applies. "Earliest-learned" matters. Suppose the merges were h+e → he (rank 1), t+he → the (rank 3) and ␣+the → ␣the (rank 4). For the chunk " the" the encoder first finds h e and merges it, then t he, then ␣ the, ending with one token, exactly as training did. If you instead merged the most frequent pair in the new text, or the longest match, you would sometimes produce token sequences the model never saw during training, and its predictions on them would be poor.

    Decoding is the easy direction: look up the bytes of every id, join them, and decode the bytes as UTF-8. One subtlety: a single token can be part of a character (for example the first byte of an emoji). If you decode tokens one at a time, as a chat interface does while streaming, you must buffer incomplete bytes until the character is complete, otherwise you print a replacement symbol (�). Our decode uses errors="replace" so that it never crashes on a half character.

    Special tokens

    A language model also needs a few tokens that are not text at all. The most important is an end-of-sequence token, here <|eos|>: we insert it between documents during training, and when the model generates it later, we know it has "finished". Chat models use more of these, for example to mark where a system prompt, a user turn or an assistant turn starts (you will meet chat formats in lesson 6.7).

    Special tokens get reserved ids outside the merge table, and they must be handled before BPE runs: split the text on the exact special strings, map each one to its id, and BPE-encode only the ordinary text in between. The crucial security rule is the reverse: text from a user is always encoded as ordinary text. If a user types the characters <|eos|>, they become a handful of punctuation and letter tokens, never the real end-of-sequence id. Otherwise anyone could forge "the assistant's turn starts here" markers inside their message. Production APIs follow the same principle.

    The tokenizer in Python

    Here is the whole tokenizer. It is self-contained (only the standard library), trains 30 merges on a small text and then checks everything this lesson promised: the round trip, unseen text including an emoji, and safe special tokens.

    # @run
    # bpe.py: a byte-level Byte Pair Encoding (BPE) tokenizer from scratch.
    # Train merges on a small text, encode, decode, check the round trip, add special tokens.
    import re
    from collections import Counter
    
    TEXT = (
        "The cat sat on the mat. The cat ate the fish. "
        "Then the cat sat by the door and the dog sat on the mat. "
        "The other cats watched the fish in the river. "
        "The baker gave the cat the rest of the bread. "
    ) * 3
    
    # Split text into word-like chunks first; merges never cross a chunk boundary,
    # so " the" can become one token but "the." can never swallow the full stop.
    CHUNK = re.compile(r" ?[A-Za-z]+| ?[0-9]+| ?[^\sA-Za-z0-9]+|\s+")
    
    
    def pair_counts(chunks):
        """How often each adjacent pair of ids appears, weighted by chunk frequency."""
        counts = Counter()
        for ids, freq in chunks.items():
            for a, b in zip(ids, ids[1:]):
                counts[(a, b)] += freq
        return counts
    
    
    def merge(ids, pair, new_id):
        """Replace every occurrence of `pair` in the tuple `ids` with `new_id`."""
        out, i = [], 0
        while i < len(ids):
            if i < len(ids) - 1 and (ids[i], ids[i + 1]) == pair:
                out.append(new_id)
                i += 2
            else:
                out.append(ids[i])
                i += 1
        return tuple(out)
    
    
    def train_bpe(text, n_merges):
        words = Counter(CHUNK.findall(text))
        chunks = {tuple(w.encode("utf-8")): f for w, f in words.items()}
        vocab = {i: bytes([i]) for i in range(256)}       # ids 0..255 = raw bytes
        merges = {}                                       # (id, id) -> new id, in order
        for _ in range(n_merges):
            counts = pair_counts(chunks)
            if not counts:
                break
            pair, n = max(counts.items(), key=lambda kv: kv[1])
            if n < 2:                                     # merging a one-off pair saves nothing
                break
            new_id = 256 + len(merges)
            merges[pair] = new_id
            vocab[new_id] = vocab[pair[0]] + vocab[pair[1]]
            chunks = {merge(ids, pair, new_id): f for ids, f in chunks.items()}
        return merges, vocab
    
    
    def encode(text, merges):
        out = []
        for chunk in CHUNK.findall(text):
            ids = tuple(chunk.encode("utf-8"))
            while len(ids) >= 2:
                # apply the EARLIEST learned merge that is present, exactly like training did
                pair = min(zip(ids, ids[1:]), key=lambda p: merges.get(p, float("inf")))
                if pair not in merges:
                    break
                ids = merge(ids, pair, merges[pair])
            out.extend(ids)
        return out
    
    
    def decode(ids, vocab):
        return b"".join(vocab[i] for i in ids).decode("utf-8", errors="replace")
    
    
    def show(b):
        return b.decode("utf-8", errors="replace").replace(" ", "␣")   # show spaces as ␣
    
    
    SPECIAL = ["<|bos|>", "<|eos|>"]
    
    
    def add_special(vocab):
        ids = {}
        for s in SPECIAL:
            ids[s] = len(vocab)
            vocab[ids[s]] = s.encode("utf-8")
        return ids
    
    
    def encode_with_special(text, merges, special_ids):
        pattern = "(" + "|".join(re.escape(s) for s in special_ids) + ")"
        out = []
        for part in re.split(pattern, text):
            if part in special_ids:
                out.append(special_ids[part])   # one reserved id, never split into bytes
            elif part:
                out.extend(encode(part, merges))
        return out
    
    
    if __name__ == "__main__":
        merges, vocab = train_bpe(TEXT, 30)
        print(f"learned {len(merges)} merges; vocabulary = 256 bytes + {len(merges)} = {len(vocab)}")
        for (a, b), new_id in list(merges.items())[:8]:
            print(f"  merge {new_id - 255:2d}: {show(vocab[a]):>6} + {show(vocab[b]):<6} -> {show(vocab[new_id])}")
    
        sample = "The cat sat on the mat by the river."
        ids = encode(sample, merges)
        n_bytes = len(sample.encode("utf-8"))
        print(f"\n{sample!r}")
        print(f"bytes: {n_bytes}   BPE tokens: {len(ids)}   ({n_bytes / len(ids):.2f} bytes per token)")
        print("tokens:", " | ".join(show(vocab[i]) for i in ids))
        print("ids:   ", ids)
        print("round trip ok:", decode(ids, vocab) == sample)
    
        unseen = "Zebras eat 42 kiwis! été \U0001F600"
        ids2 = encode(unseen, merges)
        print(f"\nunseen text {unseen!r}: {len(ids2)} tokens, round trip ok: {decode(ids2, vocab) == unseen}")
    
        special = add_special(vocab)
        chat = "<|bos|>The cat sat.<|eos|>"
        ids3 = encode_with_special(chat, merges, special)
        print(f"\nspecial ids: {special}")
        print(f"{chat!r} -> {ids3}")
        print("the literal text '<|eos|>' typed by a user is NOT the special id:",
              special["<|eos|>"] not in encode("<|eos|>", merges))
    1. CHUNK = re.compile(r" ?[A-Za-z]+| ?[0-9]+| ?[^\sA-Za-z0-9]+|\s+"): the pre-tokenization rule: optional space + letters, optional space + digits, optional space + other symbols, or whitespace. findall returns the chunks in order.
    2. pair_counts(chunks): for every distinct chunk (a tuple of ids) and its frequency, counts adjacent pairs with zip(ids, ids[1:]), adding the chunk's frequency each time.
    3. merge(ids, pair, new_id): walks through a tuple left to right and replaces every non-overlapping occurrence of pair with new_id.
    4. chunks = {tuple(w.encode("utf-8")): f ...}: the training data: each distinct chunk as a tuple of byte ids, with its count.
    5. vocab = {i: bytes([i]) for i in range(256)}: the base vocabulary, one entry per possible byte. This line is what makes "unknown character" impossible.
    6. pair, n = max(counts.items(), key=lambda kv: kv[1]): the most frequent pair. On a tie, Python's max keeps the first one it met, so training is deterministic.
    7. vocab[new_id] = vocab[pair[0]] + vocab[pair[1]]: the new token's bytes are simply the two parts' bytes joined.
    8. pair = min(zip(ids, ids[1:]), key=lambda p: merges.get(p, float("inf"))): in encode, finds the adjacent pair with the lowest merge rank; pairs that were never merged get rank infinity. If even the best pair is unknown, the chunk is finished.
    9. b"".join(vocab[i] for i in ids).decode("utf-8", errors="replace"): decoding: concatenate bytes, then interpret as UTF-8.
    10. re.split(pattern, text) in encode_with_special: splits on the special strings (the brackets in the pattern keep them in the result), maps each special string to its reserved id and BPE-encodes the rest.
    learned 30 merges; vocabulary = 256 bytes + 30 = 286
      merge  1:      h + e      -> he
      merge  2:      a + t      -> at
      merge  3:      t + he     -> the
      merge  4:      ␣ + the    -> ␣the
      merge  5:      T + he     -> The
      merge  6:      ␣ + c      -> ␣c
      merge  7:     ␣c + at     -> ␣cat
      merge  8:      ␣ + The    -> ␣The
    
    'The cat sat on the mat by the river.'
    bytes: 36   BPE tokens: 13   (2.77 bytes per token)
    tokens: The | ␣cat | ␣sat | ␣on | ␣the | ␣mat | ␣by | ␣the | ␣r | i | ve | r | .
    ids:    [260, 262, 266, 268, 259, 270, 282, 259, 277, 105, 278, 114, 46]
    round trip ok: True
    
    unseen text 'Zebras eat 42 kiwis! été 😀': 30 tokens, round trip ok: True
    
    special ids: {'<|bos|>': 286, '<|eos|>': 287}
    '<|bos|>The cat sat.<|eos|>' -> [286, 260, 262, 266, 46, 287]
    the literal text '<|eos|>' typed by a user is NOT the special id: True

    Read the output from the top. The first merges are the pairs you would guess for English: h+e, a+t, then t+he builds on merge 1, and ␣+the builds on that. After 30 merges the 36-byte sentence needs 13 tokens, about 2.8 bytes per token. Words the training text used a lot (␣cat, ␣the) are single tokens, while "river", which appeared only three times, is still in pieces: ␣r, i, ve, r. The unseen sentence with a zebra, digits, accents and an emoji still round-trips exactly, because every byte is in the vocabulary. Finally the special tokens get ids 286 and 287, and the literal text <|eos|> typed by a user does not produce id 287.

    How production tokenizers differ from this one

    Richer chunk rules. GPT-2's published pre-tokenizer regex also separates English contractions ('s, 're, 'll) and treats letters and numbers from every script, not just A to Z. Later tokenizers changed how digits are handled: some split numbers into single digits or groups of up to three, because tokenizing "2024" and "2025" into unrelated pieces makes arithmetic harder for the model.

    Speed. Our encode rescans the whole chunk after every merge, which is quadratic in the chunk length. Production encoders (for example OpenAI's open-source tiktoken or the Hugging Face tokenizers library) are written in Rust, use the merge ranks with a priority queue, and cache the encodings of frequent chunks. Training them on hundreds of gigabytes of text uses the same counting idea with heavy engineering.

    Other algorithms. SentencePiece (Kudo and Richardson, 2018) treats the input as a raw character stream with the space as a visible symbol, and offers both BPE and a "unigram language model" tokenizer that starts from a large vocabulary and prunes it. Several open-weight model families use SentencePiece with byte fallback: characters outside the vocabulary are emitted as byte tokens, which gives the same "never unknown" guarantee as byte-level BPE. Public vocabulary sizes range from about 32,000 to over 250,000 tokens; GPT-2 used 50,257.

    Claude's tokenizer. Not public Anthropic has not published the details of the tokenizer used by current Claude models (its algorithm, vocabulary size or merges). What it does provide is a way to count tokens through the API, which is what you should use for budgeting rather than assuming any rule of thumb. The Industry practice designs above are what is publicly known about tokenizers in general.

    Common mistakes and debugging tips

    Skipping pre-tokenization

    Without chunks, BPE learns merges across spaces and punctuation (e., d␣t), and the same word gets different tokens depending on its neighbours. The vocabulary fills up with junk and the model has to learn many spellings of one word.

    Fix: always split with a chunk regex first and merge inside chunks only. Print your 20 most frequent merges: they should look like word pieces, not punctuation accidents.

    Encoding by "most frequent pair in this text" instead of merge rank

    The encoder must replay the training merges in their learned order. Picking pairs by frequency in the new text, or by longest match, gives token sequences that training never produced.

    Fix: store the merges with their rank (the order they were learned) and always apply the lowest-ranked pair present. Test: encoding the training text should give exactly the ids that training ended with.

    Printing streamed tokens one at a time and getting �

    A token can end in the middle of a multi-byte character, so decoding each token on its own produces replacement symbols for accents and emoji.

    Fix: keep a byte buffer while streaming, and only print the part that decodes to complete characters (Python's codecs.getincrementaldecoder("utf-8") does exactly this).

    Letting user text become special tokens

    If your encoder looks for <|eos|> inside user input and maps it to the special id, a user can end the conversation early or forge role markers.

    Fix: insert special ids only from your own code (when you assemble the prompt), and encode all user-supplied text as plain text. The last line of the script's output is a test for exactly this.

    Key takeaways

    • Byte-level BPE starts from the 256 byte values, so any text can be encoded and decoded exactly.
    • A chunk regex splits text first; merges never cross chunk boundaries, and spaces stay at the front of words.
    • Encoding replays the learned merges in rank order; decoding joins bytes and decodes UTF-8.
    • Special tokens get reserved ids and are inserted only by your code, never parsed out of user text.

    Exercise: split numbers into single digits

    Change the chunk rule in bpe.py so that every digit becomes its own chunk (so no merge can ever join two digits). Then compare the tokens for "In 2024 we sold 12345 apples" with the original rule after training on a text that contains a few numbers (add "In 2024 we sold 2024 apples. " to TEXT). Why might a model be better at arithmetic with your version?

    Hint

    In the regex, replace the alternative ?[0-9]+ (optional space plus one or more digits) with [0-9] (exactly one digit). The space before a number then becomes its own whitespace chunk.

    Show a solution

    Use CHUNK = re.compile(r" ?[A-Za-z]+|[0-9]| ?[^\sA-Za-z0-9]+|\s+"). With the original rule, the frequent chunk " 2024" gets merged into one or two tokens, while the unseen " 12345" is split into whatever pieces happen to exist, so two similar numbers get unrelated token patterns. With one chunk per digit, every number is spelled digit by digit: 1, 2, 3, 4, 5. Sequences get a little longer, but the model sees a consistent, place-by-place representation of every number, which makes patterns such as carrying in addition much easier to learn. Several public open-weight model families split digits for this reason.

    Check your understanding

    Why can a byte-level BPE tokenizer encode any string, even one with characters it never saw in training?

    1. It falls back to an <unk> token for unknown characters
    2. Its base vocabulary contains all 256 byte values, and every string is a sequence of bytes
    3. It learns a merge for every Unicode character
    Every UTF-8 string is made of bytes, and all 256 byte values are in the vocabulary before any merge, so the worst case is "one token per byte". No <unk> token is needed, and the merges only add shortcuts for frequent byte sequences.

    The merges learned were (1) h+e, (2) a+t, (3) t+he. How should the encoder handle the chunk "the"?

    1. Merge t+h first because it comes first in the word
    2. Look up the longest vocabulary entry that matches
    3. Apply h+e (lowest rank) first, then t+he
    Encoding replays merges in the order they were learned: the lowest-ranked pair present is merged first. t+h was never learned, and longest-match can produce sequences training never made.

    A user types the text <|eos|> in a chat message. What should the tokenizer produce?

    1. Ordinary tokens for the characters <, |, eos, | and >
    2. The special end-of-sequence id
    3. An error, because special strings are not allowed
    User text is always encoded as plain text. Only the application's own code inserts special ids, otherwise users could forge control markers. Refusing the text is unnecessary: it is harmless once encoded as ordinary tokens.

    Lesson 5.2Module 5: Build a GPT-like model

    Vocabulary creation

    • ⏱ 14 min read
    • Intermediate

    Learning objectives

    • Describe what a model's vocabulary is: a fixed table from token ids to tokens that the tokenizer and the model must share forever.
    • Choose a vocabulary size by measuring the trade-off between sequence length and model size.
    • Find rare tokens, unused bytes and "stepping-stone" merges, and decide what to keep.
    • Build the id tables for our tiny GPT, with special tokens and an unknown-token fallback, and explain what that fallback costs.

    The tokenizer from lesson 5.1 can turn any text into ids. Before a model can use those ids, we have to fix its vocabulary: the exact, numbered list of tokens it will read and predict. Every id is a row in the embedding table at the bottom of the model and a column in the output layer at the top (lesson 4.3 showed both). Once training starts, the vocabulary is frozen: change the meaning of id 42 and every weight that learned about id 42 now refers to the wrong thing. This lesson is about making that decision deliberately.

    Analogy: the keys on a cash register

    A café's till has one button per item. Too few buttons, and the cashier types every order item by item ("milk", "coffee", "sugar") and queues get long. Too many, and the panel becomes huge, most buttons are pressed once a year, and new staff never learn them. The owner picks the buttons by looking at what people actually order. A vocabulary is the model's button panel: each token is a button with its own learned weights, and we choose the set by looking at what the training text actually contains.

    What exactly is a vocabulary?

    Concretely, a vocabulary is two lookup tables. itos ("integer to string") is a list where position i holds the bytes of token i; stoi (or in our code to_model) goes the other way. Together with the ordered merge list, they are the tokenizer. In practice they are saved as files next to the model weights (often JSON or a text file of merges), and a model is useless without the exact tokenizer it was trained with. Load the wrong one and the model reads gibberish, even though nothing crashes.

    Our vocabulary has three parts, in this order:

    • Special tokens at ids 0 and 1: <|eos|> (end of document) and <|unk|> (unknown). Putting them first means their ids never move when we change the number of merges.
    • Base bytes: the bytes that actually occur in our corpus. The corpus is plain English, so only 47 of the 256 possible byte values appear.
    • Merged tokens: all 120 merges learned by BPE, in rank order.

    How many merges? Measure the trade-off

    Every merge adds one token to the vocabulary and, on average, makes the encoded text shorter. Shorter sequences are good: a model with a context window of 32 tokens sees more text per window, training processes more text per step, and generation needs fewer steps. But every token also costs parameters: one row of the embedding table and, unless the weights are tied, one row of the output layer. For our model that is 48 numbers per token. Rare tokens are also badly trained, because the model sees too few examples of them to learn good vectors.

    The cost in parameters is easy to write down. With vocabulary size V and model width dmodel:

    Pembed=V×dmodeland the output layer costs anotherV×dmodelunless tied

    In words: each token in the vocabulary owns one learned vector of length d_model at the input, and one score vector at the output. Our tiny GPT ties them (the same table is used for both), as GPT-2 did.

    The other side of the trade-off, compression, has no formula: you measure it on your data. Drag the slider to train BPE in your browser on a part of our corpus and see both sides move.

    Vocabulary size versus sequence lengthInteractive

    The line shows how many tokens the text needs after each merge. The sentence below is encoded with the current merges:

    Two things stand out. The first few dozen merges buy a lot (frequent pieces like ␣the, ␣and, ing), then the curve flattens: each new merge only fuses some rare word that appears a handful of times. And the vocabulary grows linearly while the savings shrink. Real tokenizers face the same curve on a far larger scale, which is why public vocabulary sizes cluster between roughly 32,000 and 256,000 for models with billions of parameters: there, an embedding table of 100,000 × 4,096 numbers is a small fraction of the model, while shorter sequences save a lot of compute.

    For our tiny model the balance is different. Its transformer blocks hold about 56,000 weights, so a vocabulary of 1,000 would make the embedding table bigger than everything else combined. We use 120 merges: the text shrinks to about half the bytes, and the vocabulary stays at 169 tokens.

    Look inside before you commit

    Before freezing a vocabulary, inspect it. Three kinds of token deserve attention:

    • Rare tokens. Tokens that occur once or twice in the corpus get almost no training signal, so their embeddings stay close to random. In large models this has caused odd behaviour: researchers found tokens that were common in the tokenizer's training data but almost absent from the model's training data, and the model produced strange output when it met them. The lesson is to train the tokenizer on text that looks like the model's training data.
    • Stepping-stone merges. Some merged tokens exist only on the way to a longer token. Our corpus learns ␣Mir on the way to ␣Mira; after the longer merge, ␣Mir never appears in the encoded corpus. It is still a valid token for new text ("Miranda"), so we keep it.
    • Unused bytes. 209 of the 256 byte values never occur in plain English text. Keeping them costs 209 × 48 ≈ 10,000 parameters that would never be trained.

    That last point leads to a design choice that is specific to our tiny model, so it is worth stating clearly.

    Simplified implementation Simplified

    Real byte-level tokenizers keep all 256 byte tokens so that any text can be encoded. To keep our model small and fast, we keep only the 47 bytes that occur in the corpus and map any other byte to <|unk|>. The price: text with characters our corpus never used (a "Z", an accent, an emoji) loses information. You will see the model meet <|unk|> in lesson 5.9.

    Build it in Python

    The script reuses the tokenizer from bpe.py unchanged, trains it on corpus.txt (the 9 KB story about a small town called Lindale that our GPT will learn from), measures the trade-off, inspects the tokens and builds the final tables. It reads a file, so it has no ▶ Run button; run it locally next to corpus.txt.

    # ---- 1. how many merges? measure the trade-off
    HERE = os.path.dirname(os.path.abspath(__file__))
    with open(os.path.join(HERE, "corpus.txt"), encoding="utf-8") as f:
        text = " ".join(f.read().split())                   # one line, single spaces
    n_chars = len(text)
    print(f"corpus: {n_chars:,} characters, {len(set(text))} distinct characters")
    print(f"{'merges':>6} {'vocab':>6} {'tokens':>7} {'chars/token':>12} {'ids used':>9}")
    for n in (0, 30, 60, 120, 240, 480):
        merges, vocab = train_bpe(text, n)
        ids = bpe_encode(text, merges)
        print(f"{len(merges):>6} {len(vocab):>6} {len(ids):>7} {n_chars / len(ids):>12.2f} {len(set(ids)):>9}")
    
    # ---- 2. look inside the 120-merge vocabulary
    merges, vocab = train_bpe(text, 120)
    ids = bpe_encode(text, merges)
    freq = Counter(ids)
    print("\nmost frequent tokens:", "  ".join(f"{show(vocab[i])}:{c}" for i, c in freq.most_common(8)))
    rare = [i for i, c in freq.items() if c == 1]
    print(f"tokens seen only once: {len(rare)} (for example {', '.join(show(vocab[i]) for i in sorted(rare)[:4])})")
    stepping = [i for i in range(256, 256 + len(merges)) if i not in freq]
    print(f"merged tokens never used in the final encoding: {len(stepping)} "
          f"(for example {', '.join(show(vocab[i]) for i in stepping[:4])})")
    print(f"byte ids (0-255) never used: {sum(1 for i in range(256) if i not in freq)} of 256")
    
    # ---- 3. the model's vocabulary: specials first, then every byte the corpus uses, then the merges
    SPECIALS = ["<|eos|>", "<|unk|>"]
    keep = sorted(set(text.encode("utf-8"))) + list(range(256, 256 + len(merges)))
    itos = SPECIALS + [vocab[i].decode("utf-8") for i in keep]   # model id -> token text
    to_model = {b: len(SPECIALS) + k for k, b in enumerate(keep)}  # BPE id -> model id
    EOS, UNK = 0, 1
    print(f"\nmodel vocabulary: {len(itos)} = {len(SPECIALS)} special + "
          f"{len(keep) - len(merges)} bytes seen in the corpus + {len(merges)} merges")
    print("first ids:", json.dumps({i: itos[i] for i in range(6)}, ensure_ascii=False))
    
    
    def encode(s):
        return [to_model.get(i, UNK) for i in bpe_encode(s, merges)]
    
    
    def decode(model_ids):
        return "".join(itos[i] for i in model_ids)
    
    
    for s in ("Mira sells bread.", "Zoe sells bread."):
        m = encode(s)
        print(f"{s!r:20} -> {m} -> {decode(m)!r}")
    
    # the trap: keep only the ids that appear in the encoded corpus, and a plain "M" disappears
    only_used = {b: k for k, b in enumerate(sorted(freq))}
    lost = [show(vocab[i]) for i in bpe_encode("Mira", merges) if i not in only_used]
    print(f"if we kept only ids seen in the encoded corpus, 'Mira' would lose: {lost}")
    
    # ---- 4. what the vocabulary costs inside the model
    for name, v, d in (("this course's tiny GPT", len(itos), 48), ("GPT-2 small (public)", 50257, 768)):
        print(f"{name:24} vocab {v:>6,} x d_model {d:>4} = {v * d:>12,} embedding weights")
    1. text = " ".join(f.read().split()): tidies the corpus into one line with single spaces, so blank lines between paragraphs do not create rare whitespace tokens.
    2. for n in (0, 30, 60, 120, 240, 480): trains six tokenizers and prints, for each, the vocabulary size, how many tokens the corpus needs, the characters per token and how many distinct ids are actually used.
    3. freq = Counter(ids): counts every token in the encoded corpus; most_common(8) shows the top of the list and the c == 1 filter finds the rare tail.
    4. stepping = [i for i in range(256, 256 + len(merges)) if i not in freq]: merged tokens that never survive into the final encoding of the corpus.
    5. keep = sorted(set(text.encode("utf-8"))) + list(range(256, 256 + len(merges))): the tokens we keep: every byte value seen in the corpus, then every merge.
    6. itos = SPECIALS + [...] and to_model = {b: len(SPECIALS) + k ...}: the two id tables. Model id = 2 + position in keep, so specials stay at 0 and 1.
    7. to_model.get(i, UNK): the fallback: any BPE id we did not keep becomes <|unk|>.
    8. only_used = {b: k for k, b in enumerate(sorted(freq))}: demonstrates a tempting but wrong shortcut (keep only ids seen in the encoded corpus) and shows what it breaks.
    corpus: 9,047 characters, 47 distinct characters
    merges  vocab  tokens  chars/token  ids used
         0    256    9047         1.00        47
        30    286    6107         1.48        77
        60    316    5272         1.72       105
       120    376    4360         2.08       153
       240    496    3443         2.63       255
       480    736    2647         3.42       419
    
    most frequent tokens: ␣the:228  .:174  s:170  e:155  ␣s:90  ␣and:85  n:83  ␣a:82
    tokens seen only once: 10 (for example ', D, G, T)
    merged tokens never used in the final encoding: 5 (for example ␣Lind, ␣Mir, hildr, ␣fr)
    byte ids (0-255) never used: 218 of 256
    
    model vocabulary: 169 = 2 special + 47 bytes seen in the corpus + 120 merges
    first ids: {"0": "<|eos|>", "1": "<|unk|>", "2": " ", "3": "'", "4": ",", "5": "."}
    'Mira sells bread.'  -> [16, 105, 23, 53, 112, 41, 54, 85, 100, 5] -> 'Mira sells bread.'
    'Zoe sells bread.'   -> [1, 37, 27, 53, 112, 41, 54, 85, 100, 5] -> '<|unk|>oe sells bread.'
    if we kept only ids seen in the encoded corpus, 'Mira' would lose: ['M']
    this course's tiny GPT   vocab    169 x d_model   48 =        8,112 embedding weights
    GPT-2 small (public)     vocab 50,257 x d_model  768 =   38,597,376 embedding weights

    The table confirms the curve from the demo: 120 merges take the corpus from 9,047 tokens (one per byte) to 4,360, about 2.1 characters per token; 480 merges only get to 3.4. The most frequent token is ␣the, used 228 times. "Zoe" starts with a "Z", which the corpus never contains, so it becomes <|unk|>: the cost of our simplification, made visible. The second-to-last line explains why we keep every base byte: in the encoded corpus, a capital "M" only ever appears inside merged tokens such as ␣Mira, so a vocabulary of "ids that were used" would lose it, and "Mira" at the very start of a prompt (no leading space) would turn into <|unk|>ira.

    Vocabulary design in large models

    Size and compute. In a model with N transformer parameters, the embedding table is V×dmodel and the output layer's cost per token is 2Vdmodel floating-point operations. For GPT-2 small (public configuration) that is 50,257 × 768 ≈ 38.6 million weights, almost a third of its 124 million. For a model with billions of parameters, the same vocabulary is a few percent, which is why larger models can afford larger vocabularies. Larger vocabularies also help multilingual text: a vocabulary trained mostly on English splits other languages into many more tokens, so the same sentence costs more and fits less into the context.

    Padding for hardware. Industry practice Vocabulary sizes are often rounded up to a multiple of 64 or 128 (with unused dummy tokens) because matrix multiplications run faster on GPUs when dimensions are multiples of these numbers.

    Reserved and chat tokens. Tokenizers usually reserve a block of special ids up front (for chat roles, tool calls, padding, fill-in-the-middle markers) even if they are unused at first, so that fine-tuning can add behaviour later without changing the vocabulary. A padding token, when used, is masked out of the loss so that the model is never trained to predict padding.

    Tied embeddings. Using the same matrix for input embeddings and the output layer (weight tying, as in GPT-2 and our model) saves V×dmodel parameters and often helps small models. Many larger models untie them; which choice any closed model uses is generally not published.

    Common mistakes and debugging tips

    Keeping only the tokens that appear in the encoded corpus

    It looks tidy, but base bytes that only ever occur inside merged tokens disappear, and new text can no longer be encoded (the output shows "M" vanishing).

    Fix: keep every base symbol your text uses (or all 256 bytes) plus every merge. Test by encoding and decoding a few new sentences with capitals at the start.

    Rebuilding the vocabulary after training has started

    If you retrain the tokenizer (even with the same settings on slightly different text), ids can shift. The model's embedding rows now belong to different tokens, and it produces nonsense without any error message.

    Fix: save the merges and id tables once, version them with the checkpoint, and always load them from the file. A quick check: decode a known id list and compare with the expected text.

    Choosing a huge vocabulary for a tiny model

    With few parameters and little data, most tokens of a large vocabulary are rare, so their embeddings barely train, and the embedding table can dwarf the rest of the model.

    Fix: measure tokens-per-character and count how many tokens occur fewer than about 10 times. Stop adding merges when the rare tail starts to grow quickly.

    Key takeaways

    • A vocabulary is the frozen table between token ids and bytes; the tokenizer files must ship with the model weights.
    • More merges mean shorter sequences but more parameters and more rare, poorly trained tokens: measure the curve.
    • Put special tokens at fixed ids, keep every base symbol, and inspect rare and stepping-stone tokens.
    • Our tiny GPT uses 169 tokens; dropping unused bytes is a size optimisation that real byte-level tokenizers do not make.

    Exercise: find the elbow

    Extend the measurement loop in vocab.py to also print, for each merge count, how many tokens occur fewer than 3 times in the encoded corpus. Run it for 0, 30, 60, 120, 240 and 480 merges. Where would you stop adding merges for this corpus and a model with about 60,000 transformer weights? Justify your answer with the numbers.

    Hint

    Inside the loop you already have ids. Build c = Counter(ids) and count sum(1 for k in c.values() if k < 3). Compare that with the drop in tokens per extra merge.

    Show a solution

    Add rare = sum(1 for k in Counter(ids).values() if k < 3) and print it as a new column. You will see the token count fall by about 1,000 for each of the first 30-merge steps, but only by a few hundred per 100 merges later on, while the number of rare tokens keeps climbing because late merges fuse words that occur only a few times. Somewhere between 100 and 200 merges, each extra merge saves only a few tokens of a 4,000-token corpus but adds a weakly trained token with 48 weights. That is the elbow; 120 is a reasonable choice. With ten times more text, the same analysis would justify more merges, because more tokens would occur often enough to train well.

    Check your understanding

    Why can you not change a model's vocabulary halfway through training?

    1. Tokenizers are too slow to retrain
    2. The context window would change size
    3. Embedding rows and output weights are tied to specific ids; changing ids changes what those weights mean
    Every weight that relates to a token is indexed by its id. Re-numbering tokens silently swaps their meanings. Retraining a tokenizer is cheap, and the context window is a separate setting.

    What is the main cost of adding many more merges to a small model's tokenizer?

    1. More parameters in the embedding (and output) tables, and many rare tokens that barely get trained
    2. Encoded sequences get longer
    3. The model can no longer encode emoji
    More merges make sequences shorter, not longer. Byte-level coverage does not depend on the merges. The costs are V × d_model extra weights and a long tail of rarely seen tokens.

    Our vocabulary maps unseen bytes to <|unk|>. What does that lose compared with a full byte-level vocabulary?

    1. Nothing: <|unk|> is decoded back to the original character
    2. The exact characters: "Zoe" comes back as "<|unk|>oe"
    3. The ability to use special tokens
    <|unk|> is one id for every unknown byte, so the original character cannot be recovered. A full byte-level vocabulary would encode "Z" exactly. Special tokens are unaffected.

    Lesson 5.3Module 5: Build a GPT-like model

    Dataset preparation

    • ⏱ 14 min read
    • Intermediate

    Learning objectives

    • Turn a collection of documents into one long stream of token ids, with an end-of-document token between them.
    • Split the data into training and validation sets without leaking text between them.
    • Build (input, target) windows by shifting one sequence by one position, and explain why one window holds T training examples.
    • Sample random batches of shape (B, T) and reason about epochs, data size and data quality at real scale.

    We now have a tokenizer (lesson 5.1) and a vocabulary (lesson 5.2). The next job is to turn text into the exact arrays the training loop will consume. This step looks like plumbing, but mistakes here are some of the most common and most silent bugs in language-model training: a target that is not shifted, a validation set that overlaps the training set, or a document boundary the model cannot see will all produce a model that "trains" while learning the wrong thing.

    Analogy: flashcards cut from a scroll

    Imagine gluing all your books end to end into one long scroll, with a red stamp between books. To make flashcards, you slide a window along the scroll: the front of each card shows a stretch of text, and the back shows the same stretch moved one word to the right, so every word on the front has its "what comes next" right behind it. You keep a few books aside, never cut into cards, to test yourself honestly later. That is exactly how a language-model dataset is built.

    From documents to one stream

    Training data starts as many separate documents: web pages, books, code files, or in our case the 35 paragraphs of corpus.txt. We first clean each one (our cleaning is minimal: collapse runs of whitespace into single spaces), then encode it to ids and append an <|eos|> token, and finally concatenate everything into one long array. Our corpus becomes a stream of 4,421 ids.

    Why one stream instead of a list of separate sequences? Because documents have wildly different lengths, while the model wants fixed-size blocks of exactly T tokens. With one stream, every block is completely filled with real text; nothing is wasted on padding. This is often called packing. The <|eos|> separators tell the model where one document stops, so it can learn that text after the marker starts fresh, and later, during generation, the model can produce <|eos|> itself to say "this text is finished".

    Train and validation: split before you cut

    We hold back part of the data as a validation set. The model never trains on it; we only measure the loss on it, to estimate how well the model handles text it has not memorised. You saw the same idea for small networks in lesson 3.7. For language models, one rule matters most: split by document (or by a contiguous region of the stream), and do it before cutting windows. If you cut overlapping windows first and then shuffle them into two sets, nearly every validation window shares most of its tokens with some training window, and the validation loss is meaningless.

    train_gpt.py uses the simplest correct split: the last 10% of the stream (442 tokens, the final few paragraphs) is validation. That makes the validation text genuinely new: it describes things like the bus driver and the music evenings, which the training part never mentions. As you will see in lesson 5.6, this makes our validation loss much higher than the training loss, which is an honest picture of how little a 66,000-parameter model can generalise from 4,000 tokens.

    Inputs and targets: the same window, shifted by one

    A training example for next-token prediction is a pair of arrays cut from the stream at a start position s:

    x=ids[s:s+T],y=ids[s+1:s+T+1],soyt=xt+1

    In words: the input is T consecutive tokens starting at s; the target is the same T tokens moved one step to the right. At every position t, the target is simply the token that comes next in the text.

    This is where the causal mask from lesson 4.5 pays off. Position 0 of the model may only look at x0 and must predict y0; position 1 sees x0,x1 and predicts y1; and so on. So one window of length T is really T separate prediction problems, with contexts of length 1, 2, …, T, all computed in one forward pass. No labelling is needed: the text is its own answer key, which is why this is called self-supervised learning. Step through it below.

    Cut a training windowInteractive

    Each card is one position: the input token x on top, its target y (the next token) below. Highlighted cards are what position t can see; the filled card is the prediction being made.

    Notice what happens when the window crosses an <|eos|>: the model is asked to predict the first word of the next document from the end of the previous one. That is impossible to do well, and it is fine: the model learns that after <|eos|> the next token is "some typical document start", and it learns to pay less attention to tokens before the marker. Some large training setups instead mask attention so that tokens cannot see across a document boundary at all; both approaches are used.

    Batches, steps and epochs

    One window gives T predictions, but a single window is a noisy sample of the language. Each training step therefore uses a batch of B windows with random start positions, stacked into two integer matrices x and y of shape (B, T). The model processes all B × T positions in parallel, and the loss is the average over all of them. Our tiny GPT uses B = 8 and T = 32, so each step learns from 256 next-token predictions.

    How much data is that? Our training stream has 3,979 tokens. 360 steps × 256 predictions ≈ 92,000 predictions, so on average the model sees every training token about 23 times, that is, 23 epochs. Sampling random start positions (instead of cutting the stream into fixed blocks) means each pass sees the text with different alignments, which acts as a mild form of data augmentation. Large models are in the opposite regime: their training sets are so large that most text is seen once or only a few times.

    The pipeline in Python

    The script below runs the whole pipeline on five tiny documents. To keep the printout readable it uses whole words as tokens; train_gpt.py does exactly the same steps with the BPE ids from lessons 5.1 and 5.2.

    # @run
    # dataset.py: from raw documents to (input, target) batches for next-token training.
    # A word-level toy tokenizer keeps the printout readable; train_gpt.py does exactly the
    # same steps with the BPE ids from lessons 5.1 and 5.2.
    import re
    import numpy as np
    
    DOCS = [
        "Mira bakes bread. Tom sells fish. Pip sleeps by the oven.",
        "The river is cold in winter. The bridge is old and grey.",
        "Anna opens the library at nine. The children read stories.",
        "Tom fixes his nets. Lena paints the small blue boat.",
        "The market starts early and ends at noon.",
    ]
    
    # 1. tokenize: words and punctuation become tokens (a stand-in for BPE)
    pieces = lambda s: re.findall(r"[A-Za-z]+|[.,]", s)
    words = sorted({w for d in DOCS for w in pieces(d)})
    itos = ["<|eos|>"] + words                      # id 0 is the end-of-document token
    stoi = {w: i for i, w in enumerate(itos)}
    EOS = 0
    
    # 2. split by DOCUMENT before anything else, so no sentence leaks into both sets
    train_docs, val_docs = DOCS[:4], DOCS[4:]
    
    
    def to_stream(docs):
        ids = []
        for d in docs:
            ids += [stoi[w] for w in pieces(d)] + [EOS]   # documents joined by <|eos|>
        return np.array(ids)
    
    
    train_ids, val_ids = to_stream(train_docs), to_stream(val_docs)
    print(f"vocab {len(itos)} tokens | train stream {len(train_ids)} tokens | val stream {len(val_ids)} tokens")
    print("train stream starts:", " ".join(itos[i] for i in train_ids[:16]))
    
    # 3. one training window: x is a slice, y is the same slice moved one step to the right
    T = 8
    s = 9
    x, y = train_ids[s:s + T], train_ids[s + 1:s + T + 1]
    print(f"\nwindow at {s}, context T = {T}:")
    print("  x:", " ".join(f"{itos[i]:>7}" for i in x))
    print("  y:", " ".join(f"{itos[i]:>7}" for i in y))
    print("one window = T separate lessons:")
    for t in range(3):
        print(f"  after {' '.join(itos[i] for i in x[:t + 1])!r:28} predict {itos[y[t]]!r}")
    print(f"  ... and {T - 3} more, all computed in ONE forward pass thanks to the causal mask")
    
    # 4. how many windows exist, and what one epoch means
    n_windows = len(train_ids) - T
    print(f"\nwindows in the train stream: {n_windows}  ({n_windows * T} next-token predictions)")
    
    # 5. a random batch: B windows stacked into a (B, T) matrix
    rng = np.random.default_rng(0)
    B = 4
    starts = rng.integers(0, len(train_ids) - T, size=B)
    xb = np.stack([train_ids[i:i + T] for i in starts])
    yb = np.stack([train_ids[i + 1:i + T + 1] for i in starts])
    print(f"batch starts {[int(i) for i in starts]} -> x {xb.shape}, y {yb.shape}")
    print("x[0]:", xb[0].tolist())
    print("y[0]:", yb[0].tolist())
    print("every row of y is its x row shifted by one:", bool((xb[:, 1:] == yb[:, :-1]).all()))
    1. itos = ["<|eos|>"] + words: a word-level vocabulary with the end-of-document token at id 0.
    2. train_docs, val_docs = DOCS[:4], DOCS[4:]: the split happens on whole documents, before anything is cut into windows.
    3. ids += [stoi[w] for w in pieces(d)] + [EOS]: encodes each document and appends the separator; the result is one flat stream per split.
    4. x, y = train_ids[s:s + T], train_ids[s + 1:s + T + 1]: one window and its targets, shifted by one.
    5. for t in range(3): prints the first three of the T prediction problems hidden in that window.
    6. n_windows = len(train_ids) - T: every start position that leaves room for the shifted target gives a window.
    7. starts = rng.integers(0, len(train_ids) - T, size=B): random start positions for one batch; a seeded generator makes the run repeatable.
    8. np.stack([...]): stacks the B windows into (B, T) matrices; the last line checks the shift relation on the whole batch at once.
    vocab 44 tokens | train stream 56 tokens | val stream 10 tokens
    train stream starts: Mira bakes bread . Tom sells fish . Pip sleeps by the oven . <|eos|> The
    
    window at 9, context T = 8:
      x:  sleeps      by     the    oven       . <|eos|>     The   river
      y:      by     the    oven       . <|eos|>     The   river      is
    one window = T separate lessons:
      after 'sleeps'                     predict 'by'
      after 'sleeps by'                  predict 'the'
      after 'sleeps by the'              predict 'oven'
      ... and 5 more, all computed in ONE forward pass thanks to the causal mask
    
    windows in the train stream: 48  (384 next-token predictions)
    batch starts [40, 30, 24, 12] -> x (4, 8), y (4, 8)
    x[0]: [41, 1, 0, 7, 21, 23, 28, 1]
    y[0]: [1, 0, 7, 21, 23, 28, 1, 3]
    every row of y is its x row shifted by one: True

    The window starting at position 9 shows the boundary case from the demo: after "oven ." comes <|eos|>, and after that "The river", the start of the next document. The 56-token training stream holds 48 windows of length 8, which is 384 prediction problems. The batch's first row starts at position 40, and its y row is its x row shifted by one.

    In train_gpt.py the same logic is the function get_batch:

    def get_batch(split, batch_size, ctx, rng):
        d = train_data if split == "train" else val_data
        starts = rng.integers(0, len(d) - ctx - 1, size=batch_size)
        x = np.stack([d[s:s + ctx] for s in starts])
        y = np.stack([d[s + 1:s + ctx + 1] for s in starts])   # the same window, shifted by one
        return x, y
    Data preparation at real scale

    Cleaning and filtering. Industry practice Web-scale datasets go through many stages before tokenization: extracting text from HTML, language identification, removing exact and near-duplicate documents (duplicates make models memorise and waste compute), quality filtering with heuristics or small classifier models, removing personal data, and filtering unsafe content. Several public papers and open datasets describe these pipelines in detail. Module 10 covers dataset collection and cleaning for fine-tuning (lesson 10.2).

    Mixtures. Large training sets are mixtures (web text, books, code, scientific papers, multilingual text…), and the sampling weight of each source is an important, carefully tuned choice. Anthropic describes Claude's training data only in broad terms in its published model documentation; Not public the exact sources, mixture weights and filtering pipeline are not public.

    How much data? The "Chinchilla" study (Hoffmann et al., 2022, arXiv:2203.15556) found that, for a fixed compute budget, the best loss came from training on roughly 20 tokens per parameter. Many recent models train on far more tokens than that, because a smaller model trained longer is cheaper to run afterwards. Public frontier-scale training runs use trillions of tokens. Our model has 66,000 parameters and 4,000 training tokens: less than one token per parameter, which is why it memorises.

    Storage and loading. At scale the token stream is stored once, already tokenized, as a flat binary file of 16- or 32-bit integers, and read with memory mapping, so a training job can pick random windows from terabytes of tokens without loading them into memory. Evaluation sets are kept apart, and serious projects check that benchmark questions do not appear in the training data (contamination), because a model that has seen the test will score too well.

    Common mistakes and debugging tips

    Targets not shifted (or shifted the wrong way)

    If y equals x, the model learns to copy its input: with the causal mask, position t can see token t, so the loss drops to almost zero within a few steps and generation is garbage. Shifting the wrong way asks it to predict the past.

    Fix: assert (x[:, 1:] == y[:, :-1]).all() on a real batch, and be suspicious of any training loss that falls far below what the data allows.

    Overlapping train and validation windows

    Cutting windows first and then randomly assigning them to train or validation leaks nearly all validation text into training. Validation loss then tracks training loss and hides overfitting.

    Fix: split documents (or one contiguous region of the stream) first, then cut windows separately from each split.

    An off-by-one in the last start position

    y needs one more token than x. If the highest start allowed is len(ids) - T instead of len(ids) - T - 1, the last window's target can come out one token short and np.stack fails, but only occasionally, when that start is drawn.

    Fix: compute the valid range once and test it by forcing the largest start. Note that NumPy's integers(low, high) excludes high.

    Key takeaways

    • Documents are encoded, separated by <|eos|> and packed into one stream, so every block is full of real text.
    • Split train and validation by document or region before cutting windows.
    • Targets are the inputs shifted by one; with the causal mask, a window of T tokens is T training examples.
    • A batch is a (B, T) matrix of random windows; our tiny model sees its data about 23 times, large models mostly once.

    Exercise: non-overlapping blocks and a validation check

    Add a function blocks(ids, T) to dataset.py that cuts the stream into consecutive, non-overlapping windows (start positions 0, T, 2T, …) and returns x and y matrices. Use it for the validation stream with T = 4, print the shapes, and explain why deterministic blocks are a better choice for measuring validation loss than random windows.

    Hint

    The number of full blocks is (len(ids) - 1) // T (minus one because the targets need one extra token). Build the starts with range(0, n * T, T).

    Show a solution
    def blocks(ids, T):
        n = (len(ids) - 1) // T
        starts = range(0, n * T, T)
        x = np.stack([ids[s:s + T] for s in starts])
        y = np.stack([ids[s + 1:s + T + 1] for s in starts])
        return x, y
    
    xv, yv = blocks(val_ids, 4)
    print(xv.shape, yv.shape)       # (2, 4) (2, 4): 10 tokens -> 2 full blocks

    With deterministic blocks every validation token is scored exactly once, and the number is the same every time you evaluate, so differences between evaluations reflect the model, not which random windows happened to be drawn. train_gpt.py gets a similar effect more cheaply by re-seeding its evaluation generator (np.random.default_rng(1234)) so the same windows are used at every evaluation.

    Check your understanding

    For the stream [5, 8, 2, 9, 4] and a window starting at 0 with T = 3, what are x and y?

    1. x = [5, 8, 2], y = [5, 8, 2]
    2. x = [5, 8, 2], y = [8, 2, 9]
    3. x = [8, 2, 9], y = [5, 8, 2]
    The target at each position is the next token: y is x shifted one step to the right. Equal x and y would teach copying, and the third option predicts the past.

    Why are documents concatenated with an <|eos|> token instead of padded to the same length?

    1. Padding is not supported by NumPy
    2. The model cannot handle sequences shorter than T
    3. Packing fills every block with real text (no wasted compute), and <|eos|> still marks where documents end
    Padding works but wastes computation on tokens that teach nothing. Packing avoids that, and the separator keeps the boundary information, which the model also needs in order to learn to stop.

    How many next-token predictions does one batch of shape (8, 32) contain?

    1. 256
    2. 8
    3. 32
    Each of the 8 windows has 32 positions, and every position predicts its next token: 8 × 32 = 256 predictions, all averaged into one loss.

    Lesson 5.4Module 5: Build a GPT-like model

    Next-token prediction

    • ⏱ 14 min read
    • Intermediate

    Learning objectives

    • State the training objective of a GPT-style model: maximise the probability of every next token, which is the same as minimising cross-entropy.
    • Compute softmax, the loss and its gradient (probabilities minus the one-hot target) for one position by hand and in NumPy.
    • Read loss numbers: the ln V baseline at initialisation, perplexity, and what a good loss means.
    • Explain why such a simple objective forces a model to learn grammar, facts and patterns of reasoning.

    You have met next-token prediction several times already: as a counting model in lesson 1.2, as softmax and cross-entropy in lesson 2.4, and as the final layer of the transformer in lesson 4.9. This lesson puts these pieces together into the precise objective our tiny GPT will be trained on, and shows the gradient that flows back from it. Everything a pretrained language model knows was learned through this single number.

    Analogy: betting on the next word

    Imagine reading a book with a friend who covers the next word. Before each word is revealed you must spread 100 chips across every word you think it could be. When the word is revealed, you are scored on how many chips you put on it: lots of chips on the right word costs you little, a handful costs you a lot, and zero chips costs you everything. To score well over a whole book you need grammar (only nouns fit here), facts (the capital of France), and the story so far (who "she" is). The language model plays this game on every token, and the loss is its score.

    One sentence, many predictions

    A language model assigns a probability to any sequence of tokens. The chain rule of probability (lesson 2.3) splits that probability into one factor per token, each conditioned on everything before it:

    P(x1,…,xn)=∏t=1nP(xt∣x1,…,xt−1)

    In words: the probability of a whole text equals the probability of its first token, times the probability of the second given the first, times the probability of the third given the first two, and so on. A model that can predict the next token given any prefix can therefore score, and generate, whole texts.

    This is exact, not an approximation: no information is thrown away by predicting one token at a time. The modelling choice is only in how each conditional probability is computed. A bigram model looks at the last token only. A transformer looks at the whole prefix, up to its context length, through attention. The training signal is the same for both.

    From logits to a loss at one position

    At every position, the last layer of the model produces one number per vocabulary entry: a vector of logits of length V. (This is the word "logit" from lesson 3.4; for our tiny GPT, V = 169.) Softmax turns the logits into probabilities that are positive and sum to 1. The loss at that position is the negative log of the probability given to the token that actually came next:

    pi=ezi∑j=1Vezj,ℓ=−lnptarget

    In words: exponentiate each logit and divide by the total so the probabilities sum to one; the loss is minus the natural log of the probability of the correct next token. If the model gave the right token probability 1 the loss is 0; probability 0.5 costs 0.69; probability 0.01 costs 4.6.

    The training loss of a batch is simply the average of ℓ over all B × T positions. This is cross-entropy, and minimising it is the same as maximising the (log) probability of the training text. The derivative of this loss with respect to the logits is remarkably clean, as you derived in module 3:

    ∂ℓ∂zi=pi−yi

    In words: the gradient on each logit is the predicted probability minus the target, where the target y is 1 for the correct token and 0 for every other. Gradient descent therefore raises the correct token's logit by (1 − p) and lowers every other token's logit in proportion to the probability it wrongly received.

    Play with it. Choose which word really came next, change the logits, and press "One gradient step" to apply z←z−η(p−y) with learning rate η = 1.

    Logits, probabilities, loss and gradientInteractive

    Reading loss numbers

    Loss values become intuitive once you know three reference points.

    • The ignorant baseline, ln V. A model that gives every token the same probability 1/V has loss lnV at every position. A freshly initialised model is close to this, because its logits are all near zero. For our vocabulary of 169 that is 5.13; for GPT-2's 50,257 it is 10.8. If your loss at step 0 is much higher than ln V, your initialisation is wrong (logits too large); you will see our model start at 5.14.
    • Perplexity, eloss, turns the loss back into a count: "the model is as uncertain as if it were choosing uniformly between this many tokens". Loss 5.13 is perplexity 169 (no idea); our trained model reaches a validation perplexity around 32.
    • Zero is impossible on real text. Language is genuinely uncertain: after "She bought a" many words are fine. The best achievable loss is the entropy of the text itself, which is unknown but well above zero. A training loss near zero on a large dataset almost always means a bug (often an unshifted target) or memorisation of a tiny one.

    Because the loss is in nats per token, numbers are only comparable between models with the same tokenizer. A tokenizer with longer tokens has fewer, harder predictions per sentence. To compare across tokenizers, researchers convert to bits per byte or per character.

    Next-token prediction in NumPy

    The script first does the single-position computation from the demo, then trains three very simple "models" by counting, and scores each on a held-out sentence. Lower loss is better.

    # @run
    # next_token.py: the next-token objective in miniature.
    # Logits -> softmax -> cross-entropy for one position, its gradient, and the same loss
    # measured for three simple "models" (uniform, unigram, bigram) on held-out text.
    import math
    import re
    from collections import Counter, defaultdict
    import numpy as np
    
    # ---- 1. one prediction: the model scores every token in the vocabulary
    vocab = ["mat", "dog", "river", "the", "sat", "."]
    logits = np.array([2.0, 0.5, -1.0, 0.1, -0.5, 0.3])      # what a model might output after "The cat sat on the"
    p = np.exp(logits - logits.max())
    p /= p.sum()
    target = vocab.index("mat")
    loss = -math.log(p[target])
    print("probabilities:", "  ".join(f"{w}:{float(q):.3f}" for w, q in zip(vocab, p)))
    print(f"target 'mat': p = {float(p[target]):.3f}  loss = -ln p = {loss:.3f}")
    grad = p.copy()
    grad[target] -= 1.0                                         # d loss / d logits = p - one_hot
    print("gradient on the logits:", np.round(grad, 3))
    print("-> push 'mat' up by", f"{float(-grad[target]):.3f};", "push every other token down by its probability")
    
    # ---- 2. three baseline models, scored on text they did not see
    train_text = ("the cat sat on the mat . the dog sat on the log . the cat saw the dog . "
                  "the dog ran to the river . the cat sat by the river . a dog sat on a mat .")
    test_text = "the dog sat on the mat . the cat ran to the log ."
    tok = lambda s: re.findall(r"\S+", s)
    train, test = tok(train_text), tok(test_text)
    V = sorted(set(train))
    print(f"\nvocabulary {len(V)} words; train {len(train)} tokens; test {len(test)} tokens")
    
    uni = Counter(train)
    bi = defaultdict(Counter)
    for a, b in zip(train, train[1:]):
        bi[a][b] += 1
    
    
    def p_uniform(prev, w):
        return 1 / len(V)
    
    
    def p_unigram(prev, w):                                     # add-one smoothing: no zero probabilities
        return (uni[w] + 1) / (len(train) + len(V))
    
    
    def p_bigram(prev, w):
        return (bi[prev][w] + 1) / (sum(bi[prev].values()) + len(V))
    
    
    print(f"{'model':8} {'avg loss (nats)':>16} {'perplexity':>11}")
    for name, f in (("uniform", p_uniform), ("unigram", p_unigram), ("bigram", p_bigram)):
        nll = [-math.log(f(a, b)) for a, b in zip(test, test[1:])]
        avg = sum(nll) / len(nll)
        print(f"{name:8} {avg:>16.3f} {math.exp(avg):>11.2f}")
    print(f"ln(V) = {math.log(len(V)):.3f}: the loss of a model that knows nothing")
    
    after = bi["the"]
    total = sum(after.values())
    print("\nbigram: what follows 'the'?", "  ".join(f"{w}:{c / total:.2f}" for w, c in after.most_common()))
    1. p = np.exp(logits - logits.max()): a numerically safe softmax (subtracting the maximum changes nothing mathematically but prevents overflow).
    2. loss = -math.log(p[target]): cross-entropy for one position: only the probability of the correct token matters.
    3. grad[target] -= 1.0: the gradient p - one_hot, built in place.
    4. p_uniform, p_unigram, p_bigram: three models of increasing context: none, word frequency only, and the previous word. Adding 1 to every count (add-one smoothing) keeps every probability above zero, so no test token gets an infinite loss.
    5. nll = [-math.log(f(a, b)) for a, b in zip(test, test[1:])]: the loss for every next-token prediction in the test sentence; avg is the cross-entropy and math.exp(avg) the perplexity.
    probabilities: mat:0.593  dog:0.132  river:0.030  the:0.089  sat:0.049  .:0.108
    target 'mat': p = 0.593  loss = -ln p = 0.523
    gradient on the logits: [-0.407  0.132  0.03   0.089  0.049  0.108]
    -> push 'mat' up by 0.407; push every other token down by its probability
    
    vocabulary 14 words; train 41 tokens; test 14 tokens
    model     avg loss (nats)  perplexity
    uniform             2.639       14.00
    unigram             2.449       11.58
    bigram              1.959        7.09
    ln(V) = 2.639: the loss of a model that knows nothing
    
    bigram: what follows 'the'? cat:0.30  dog:0.30  river:0.20  mat:0.10  log:0.10

    The model puts 0.593 on "mat", so the loss is 0.523. The gradient row shows the rule in action: −0.407 on "mat" (gradient descent will raise it) and a positive value on every other word equal to its probability. In the comparison, the uniform model scores exactly ln 14 = 2.639; knowing word frequencies helps a little (2.449); knowing the previous word helps a lot more (1.959, perplexity 7). A transformer is the same idea taken much further: it conditions on the entire prefix instead of one word.

    Why such a simple objective learns so much

    To push the loss down on a large and varied corpus, a model has to get good at whatever makes the next token predictable. Early in training that is spelling and frequent words. Then grammar: after "the cats" comes "are", not "is". Then facts, because "The capital of France is" is followed by "Paris" in thousands of documents. Then longer-range structure: the name of a character introduced three paragraphs ago, the variable defined at the top of a function, the step that follows in a worked solution. No one labels any of this; it is all implicit in "predict the next token". This is the core insight behind pretraining, discussed in lesson 1.2.

    The same objective also explains the limits you will analyse in lesson 5.9. The model is rewarded for producing text that is likely, not text that is true. Most of the time those agree, because most training text is roughly accurate. When they disagree, for example when asked about something it never saw, the model still produces a likely-sounding continuation.

    Teacher forcing, exposure bias and what the loss does not see

    During training, the model at position t always conditions on the real previous tokens from the dataset, never on its own earlier guesses. This is called teacher forcing, and it is what makes training parallel: all T positions can be computed at once because their inputs are known in advance. During generation, however, the model conditions on its own outputs. If it makes an unusual choice early, it ends up in a prefix unlike anything in training, and errors can compound. This mismatch is known as exposure bias; sampling strategies (lessons 5.7 and 5.8) and post-training (module 6) both help.

    Cross-entropy is a proper scoring rule: the expected loss is minimised exactly when the predicted distribution equals the true conditional distribution of the data. So a perfectly trained model would be perfectly calibrated with respect to its training text. Real models are not perfect, and post-training for helpfulness can change calibration, which is one reason a model's stated confidence is not a reliable measure of correctness.

    The loss treats all tokens as equally important. Getting "the" wrong costs as much as getting a key number in a calculation wrong. Some training recipes weight tokens differently, for example by masking the prompt part of instruction data so only the response is learned (lesson 6.3), but plain pretraining weights every token equally.

    Common mistakes and debugging tips

    Computing softmax, then log, separately

    np.log(softmax(z)) can underflow to log(0) = -inf when a probability is tiny, producing inf or nan losses.

    Fix: compute log-probabilities directly as z - z.max() - log(sum(exp(z - z.max()))) (the log-sum-exp trick), as cross_entropy in gpt_numpy.py does.

    Comparing losses across different tokenizers

    A model with a 50,000-token vocabulary and one with 169 tokens make different numbers of predictions per sentence, each of different difficulty, so "3.5 versus 2.8" says nothing about which model is better.

    Fix: compare models on the same tokenizer, or convert to bits per byte: total loss in nats ÷ ln 2 ÷ number of bytes of text.

    Starting loss far above ln V

    If step 0 shows a loss of 20 with a vocabulary of 169, the initial logits are too large and the model is confidently wrong before it has learned anything; early training then wastes steps undoing that.

    Fix: initialise weights with a small standard deviation (0.02 is standard for GPT-style models) and check that the first loss is within a few percent of ln V.

    Key takeaways

    • A language model factorises text probability into next-token conditionals; training maximises the probability of every real next token.
    • Per position: softmax over V logits, loss = −ln p(target), gradient = p − one-hot.
    • Expect ln V at initialisation; perplexity = eloss; compare losses only with the same tokenizer.
    • The objective rewards likely text, not true text, which is both why it learns so much and why it can make things up.

    Exercise: add a trigram model

    Add a fourth model to next_token.py that conditions on the previous two words, with add-one smoothing, and score it on the same test sentence. Does more context help here? Explain the result in terms of how much training data each context has.

    Hint

    Count with a defaultdict(Counter) keyed by the pair (a, b). To score, loop over zip(test, test[1:], test[2:]); the first test token has no two-word context, so either skip it or fall back to the bigram for that one position.

    Show a solution
    tri = defaultdict(Counter)
    for a, b, c in zip(train, train[1:], train[2:]):
        tri[(a, b)][c] += 1
    
    def p_trigram(a, b, w):
        return (tri[(a, b)][w] + 1) / (sum(tri[(a, b)].values()) + len(V))
    
    nll = [-math.log(p_bigram(test[0], test[1]))]          # first step: bigram fallback
    nll += [-math.log(p_trigram(a, b, c)) for a, b, c in zip(test, test[1:], test[2:])]
    avg = sum(nll) / len(nll)
    print(f"trigram  {avg:.3f}  perplexity {math.exp(avg):.2f}")

    On this tiny text the trigram is actually worse: loss 2.112 (perplexity 8.26) against the bigram's 1.959. Each two-word context was seen only a few times, so add-one smoothing spreads most of the probability over the 14 words. More context only helps when there is enough data to estimate the longer patterns. Counting models hit this wall fast because the number of contexts explodes; neural models avoid it by sharing what they learn between similar contexts through embeddings and attention.

    Check your understanding

    A freshly initialised model with a vocabulary of 1,000 tokens should have a training loss close to…

    1. 0
    2. ln 1000 ≈ 6.9
    3. 1000
    Small random weights give almost equal logits, so every token gets probability about 1/1000, and the loss is −ln(1/1000) = ln 1000. A loss of 0 would mean perfect prediction; the loss is a log, so it is never as large as V.

    At one position the model gives the correct token probability 0.7. What is the gradient of the loss with respect to that token's logit?

    1. −0.3
    2. 0.7
    3. −0.7
    The gradient is p − y = 0.7 − 1 = −0.3. It is negative, so gradient descent increases this logit. Every wrong token's gradient equals its own probability (positive).

    Why does next-token training also teach a model facts?

    1. Facts are added in a separate database during pretraining
    2. The loss gives extra weight to factual sentences
    3. Predicting text that states facts is easier when the model has absorbed those facts, so lowering the loss rewards learning them
    Pretraining has no separate fact store or special weighting. Facts are simply useful for predicting the next token in text that mentions them, so they end up encoded in the weights, imperfectly.

    Lesson 5.5Module 5: Build a GPT-like model

    Building a decoder-only transformer

    • ⏱ 27 min read
    • Advanced

    Learning objectives

    • Assemble a complete decoder-only (GPT-style) transformer: token and position embeddings, a stack of pre-norm blocks, a final LayerNorm and a tied output layer.
    • Explain how a small reverse-mode autodiff engine computes every gradient, so the model can be trained without deriving each backward pass by hand.
    • Verify a model before training: output shapes, loss at initialisation, causality, and a numerical gradient check.
    • List which parts of our model differ from what large public models use, and why.

    In lesson 4.9 you wrote a full GPT-style forward pass in NumPy. It could compute next-token probabilities, but they were meaningless: the weights were random and there was no way to improve them. To train, we need the gradient of the loss with respect to every one of the model's weights. This lesson builds the same architecture again, this time on top of a tiny automatic differentiation engine, and proves that its gradients are right before we spend any time training it in lesson 5.6.

    Analogy: a factory line with a complaints desk

    Picture an assembly line: raw tokens enter at one end, each station transforms the work-in-progress, and a guess about the next token comes out at the other. At the end, an inspector compares the guess with the real next token and files a complaint. Each station keeps a note of exactly what it did, so when the complaint is passed back down the line, every station can work out how much it contributed and how to adjust its machine. The forward pass is the line; the autodiff engine is that chain of notes and the complaint travelling backwards.

    The architecture, end to end

    A decoder-only transformer is the "decoder" half of the original transformer without the cross-attention to an encoder. Every layer uses the causal mask, so each position sees only itself and the past. You met all of its parts in module 4; here they are in the order the data flows. Click the boxes or step through the flow.

    Token ids
    A batch of B windows of T token ids each (lesson 5.3). For our model T = 32 and V = 169.
    Token embedding
    A learned table with one row of C = 48 numbers per vocabulary entry. Looking up row ids[b, t] gives the starting vector for each position.
    Position embedding
    A second learned table, one row per position 0…T−1, added to the token vectors so the model can tell "cat sat" from "sat cat" (lesson 4.4). GPT-2 used learned positions like this; many newer models use RoPE instead.
    LayerNorm 1
    Normalises each token's vector before attention (pre-norm, lesson 4.8). Each LayerNorm has a learned gain and bias.
    Causal attention
    Each position builds a query, key and value, attends to itself and earlier positions only, and the heads' outputs are mixed by an output matrix. The result is added to the input: the residual connection.
    LayerNorm 2
    Normalises again before the MLP.
    MLP
    The position-wise feed-forward network from lesson 4.7: expand to 4C = 192, apply GELU, project back to C, add to the residual stream.
    Final LayerNorm
    One last normalisation after the stack of blocks, standard in pre-norm models.
    Output layer
    Multiplies every final vector by the transpose of the token embedding table, giving V logits per position. Reusing the table is called weight tying.
    Loss
    Softmax and cross-entropy against the shifted targets, averaged over all B × T positions (lesson 5.4).
    1. Ids are looked up in two tables: what the token is, and where it is. The two vectors are added.
    2. Inside each block, LayerNorm then causal attention: tokens gather information from earlier tokens, and the result is added to the residual stream.
    3. LayerNorm then the MLP: each token processes what it gathered, and the result is added again. This repeats for every block.
    4. A final LayerNorm, then multiplication by the embedding table turns each vector into V logits.
    5. During training, the logits are scored against the next tokens. During generation, only the last position's logits are used.
    Our tiny GPT. Two blocks, four heads, width C = 48, context T = 32, vocabulary V = 169: 66,000 parameters in total. Every shape is (batch, positions, width) until the output layer turns width into vocabulary size.

    The forward pass is short enough to read in one go. Compare it with module 4's version: the structure is identical, only the operations are now functions of our autodiff engine (embedding, layer_norm, @, +) that remember how to send gradients back.

    def forward(self, ids, targets=None):
        B, T = ids.shape
        assert T <= self.T, "sequence longer than the context window"
        p = self.p
        x = embedding(p["wte"], ids) + embedding(p["wpe"], np.arange(T))
        for l in range(self.L):         # pre-norm residual blocks
            x = x + self.attention(layer_norm(x, p[f"h{l}.ln1.g"], p[f"h{l}.ln1.b"]), l)
            x = x + self.mlp(layer_norm(x, p[f"h{l}.ln2.g"], p[f"h{l}.ln2.b"]), l)
        x = layer_norm(x, p["lnf.g"], p["lnf.b"])
        logits = x @ transpose(p["wte"], 0, 1)      # weight tying: reuse the embedding
        loss = None if targets is None else cross_entropy(logits, targets)
        return logits, loss

    Gradients without the pain: a tiny autodiff engine

    In module 3 you wrote the backward pass of every layer by hand, and in lesson 2.5 you built a tiny autograd engine for single numbers. Writing a transformer's backward pass by hand is possible but error-prone: attention alone involves reshapes, transposes, a mask, a softmax and two matrix products. Real frameworks (PyTorch, JAX) solve this with reverse-mode automatic differentiation, and we do the same with a miniature version that works on whole NumPy arrays.

    The idea is the one from lesson 2.5, scaled up. Every operation creates a Tensor that stores three things: its value, the tensors it was computed from (its parents), and a small function that, given the gradient of the loss with respect to this tensor, adds the right gradient into each parent. Calling loss.backward() sorts all tensors so that every tensor comes after its parents (a topological order), sets the loss's own gradient to 1, and then walks the list backwards, calling each stored function once. This is the chain rule, applied mechanically.

    class Tensor:
        """A NumPy array that remembers how it was made, so it can send gradients back."""
    
        def __init__(self, data, parents=(), backward=None):
            self.data = np.asarray(data, dtype=np.float64)
            self.grad = None
            self.parents = parents          # tensors this one was computed from
            self.backward_fn = backward     # pushes self.grad into the parents
    
        @property
        def shape(self):
            return self.data.shape
    
        def add_grad(self, g):
            self.grad = g if self.grad is None else self.grad + g
    
        def backward(self):
            order, seen = [], set()
    
            def visit(t):                   # topological order: parents before children
                if id(t) not in seen:
                    seen.add(id(t))
                    for p in t.parents:
                        visit(p)
                    order.append(t)
            visit(self)
            self.grad = np.ones_like(self.data)
            for t in reversed(order):       # walk from the loss back to the weights
                if t.backward_fn is not None:
                    t.backward_fn(t.grad)
    
        def __add__(self, other):
            return add(self, other)
    
        def __matmul__(self, other):
            return matmul(self, other)

    Each operation then only needs its local rule. Most are one line: the gradient of a sum flows unchanged to both inputs; the gradient of a matrix product Y=AB is GBT for A and ATG for B. Here is the masked softmax used inside attention, forward and backward together:

    def causal_softmax(scores):
        """Softmax over the last axis where position t may only look at positions <= t."""
        T = scores.shape[-1]
        future = np.triu(np.ones((T, T), dtype=bool), k=1)
        s = np.where(future, -1e9, scores.data)
        s = s - s.max(axis=-1, keepdims=True)
        e = np.exp(s)
        p = e / e.sum(axis=-1, keepdims=True)
        out = Tensor(p, (scores,))
        # softmax backward: dS = P * (dP - sum(dP * P)); masked entries have P = 0
        out.backward_fn = lambda g: scores.add_grad(p * (g - (g * p).sum(-1, keepdims=True)))
        return out

    Two details in the engine deserve attention. unbroadcast handles NumPy broadcasting: when a bias of shape (C,) is added to activations of shape (B, T, C), its gradient must be summed over the batch and position axes back to shape (C,). And embedding's backward uses np.add.at, because when the same token appears twice in a batch, both gradients must be added to its row, not one overwriting the other.

    Simplified implementation Simplified

    Our engine is about 150 lines, uses float64 on the CPU, and keeps every intermediate array in memory. PyTorch's autograd follows the same principle but runs fused GPU kernels in 16-bit formats, frees memory as it goes and supports hundreds of operations. We use our own engine so that nothing is hidden: every gradient in the model is computed by code you can read.

    Check the model before you train it

    Training a model with a subtle bug wastes hours and teaches you nothing, because a buggy model still often trains a little. So we test four things first, using a toy configuration (vocabulary 13, context 8, width 16):

    • Shapes. Ids of shape (3, 8) must give logits of shape (3, 8, 13): one score per vocabulary entry, at every position, for every sequence.
    • Loss at initialisation. With small random weights the loss should be close to ln V (lesson 5.4).
    • Causality. Changing the last token must not change the logits at any earlier position. If it does, the mask is wrong and the model will "cheat" by reading the answer during training.
    • Gradients. For a sample of weights in every tensor, nudge the weight up and down by a tiny h and measure the change in loss: (L(w+h)−L(w−h))/2h. This numerical slope must match the gradient from backpropagation to many decimal places.

    The complete file contains the engine, the model and these checks. It needs only NumPy and runs in well under a second.

    Show the complete gpt_numpy.py
    # @run
    # gpt_numpy.py: a tiny decoder-only transformer (GPT-style) in pure NumPy, with a
    # small reverse-mode autodiff engine so we never derive a backward pass by hand.
    # Running this file builds a toy model, checks shapes and the loss at init, and
    # verifies every gradient against a numerical (finite-difference) gradient.
    import math
    import numpy as np
    
    
    # ---------------------------------------------------------------- autodiff engine
    class Tensor:
        """A NumPy array that remembers how it was made, so it can send gradients back."""
    
        def __init__(self, data, parents=(), backward=None):
            self.data = np.asarray(data, dtype=np.float64)
            self.grad = None
            self.parents = parents          # tensors this one was computed from
            self.backward_fn = backward     # pushes self.grad into the parents
    
        @property
        def shape(self):
            return self.data.shape
    
        def add_grad(self, g):
            self.grad = g if self.grad is None else self.grad + g
    
        def backward(self):
            order, seen = [], set()
    
            def visit(t):                   # topological order: parents before children
                if id(t) not in seen:
                    seen.add(id(t))
                    for p in t.parents:
                        visit(p)
                    order.append(t)
            visit(self)
            self.grad = np.ones_like(self.data)
            for t in reversed(order):       # walk from the loss back to the weights
                if t.backward_fn is not None:
                    t.backward_fn(t.grad)
    
        def __add__(self, other):
            return add(self, other)
    
        def __matmul__(self, other):
            return matmul(self, other)
    
    
    def unbroadcast(g, shape):
        """Sum a gradient back down to `shape` (undo NumPy broadcasting)."""
        while g.ndim > len(shape):
            g = g.sum(axis=0)
        for i, n in enumerate(shape):
            if n == 1 and g.shape[i] != 1:
                g = g.sum(axis=i, keepdims=True)
        return g
    
    
    def add(a, b):
        out = Tensor(a.data + b.data, (a, b))
        out.backward_fn = lambda g: (a.add_grad(unbroadcast(g, a.shape)),
                                     b.add_grad(unbroadcast(g, b.shape)))
        return out
    
    
    def scale(a, c):
        out = Tensor(a.data * c, (a,))
        out.backward_fn = lambda g: a.add_grad(g * c)
        return out
    
    
    def matmul(a, b):
        if b.data.ndim == 2:
            # (..., K) @ (K, N): fold every leading axis into one so NumPy uses one big BLAS call
            K = a.shape[-1]
            a2 = a.data.reshape(-1, K)
            out = Tensor((a2 @ b.data).reshape(a.shape[:-1] + (b.shape[1],)), (a, b))
    
            def back(g):
                g2 = g.reshape(-1, b.shape[1])
                a.add_grad((g2 @ b.data.T).reshape(a.shape))
                b.add_grad(a2.T @ g2)
            out.backward_fn = back
            return out
        out = Tensor(a.data @ b.data, (a, b))        # batched (B, H, T, T) style products
    
        def back(g):
            a.add_grad(unbroadcast(g @ np.swapaxes(b.data, -1, -2), a.shape))
            b.add_grad(unbroadcast(np.swapaxes(a.data, -1, -2) @ g, b.shape))
        out.backward_fn = back
        return out
    
    
    def reshape(a, shape):
        out = Tensor(a.data.reshape(shape), (a,))
        out.backward_fn = lambda g: a.add_grad(g.reshape(a.shape))
        return out
    
    
    def transpose(a, ax1, ax2):
        out = Tensor(np.swapaxes(a.data, ax1, ax2), (a,))
        out.backward_fn = lambda g: a.add_grad(np.swapaxes(g, ax1, ax2))
        return out
    
    
    def embedding(table, ids):
        """Row lookup: out[b, t] = table[ids[b, t]]."""
        out = Tensor(table.data[ids], (table,))
    
        def back(g):
            dt = np.zeros_like(table.data)
            np.add.at(dt, ids, g)           # a row used twice gets both gradients
            table.add_grad(dt)
        out.backward_fn = back
        return out
    
    
    def layer_norm(x, gain, bias, eps=1e-5):
        mu = x.data.mean(axis=-1, keepdims=True)
        var = x.data.var(axis=-1, keepdims=True)
        inv = 1.0 / np.sqrt(var + eps)
        xhat = (x.data - mu) * inv
        out = Tensor(xhat * gain.data + bias.data, (x, gain, bias))
    
        def back(g):
            gain.add_grad(unbroadcast(g * xhat, gain.shape))
            bias.add_grad(unbroadcast(g, bias.shape))
            dxhat = g * gain.data
            n = x.shape[-1]
            dx = inv / n * (n * dxhat - dxhat.sum(-1, keepdims=True)
                            - xhat * (dxhat * xhat).sum(-1, keepdims=True))
            x.add_grad(dx)
        out.backward_fn = back
        return out
    
    
    def gelu(x):
        """GELU, tanh approximation (as in GPT-2)."""
        c = math.sqrt(2.0 / math.pi)
        x2 = x.data * x.data                # x*x is much faster than x**2 in NumPy
        th = np.tanh(c * (x.data + 0.044715 * x2 * x.data))
        out = Tensor(0.5 * x.data * (1.0 + th), (x,))
    
        def back(g):
            du = c * (1.0 + 3 * 0.044715 * x2)
            x.add_grad(g * (0.5 * (1.0 + th) + 0.5 * x.data * (1.0 - th * th) * du))
        out.backward_fn = back
        return out
    
    
    def causal_softmax(scores):
        """Softmax over the last axis where position t may only look at positions <= t."""
        T = scores.shape[-1]
        future = np.triu(np.ones((T, T), dtype=bool), k=1)
        s = np.where(future, -1e9, scores.data)
        s = s - s.max(axis=-1, keepdims=True)
        e = np.exp(s)
        p = e / e.sum(axis=-1, keepdims=True)
        out = Tensor(p, (scores,))
        # softmax backward: dS = P * (dP - sum(dP * P)); masked entries have P = 0
        out.backward_fn = lambda g: scores.add_grad(p * (g - (g * p).sum(-1, keepdims=True)))
        return out
    
    
    def cross_entropy(logits, targets):
        """Mean of -log softmax(logits)[target] over every position."""
        z = logits.data - logits.data.max(axis=-1, keepdims=True)
        logp = z - np.log(np.exp(z).sum(axis=-1, keepdims=True))
        flat = logp.reshape(-1, logp.shape[-1])
        t = targets.reshape(-1)
        n = t.shape[0]
        out = Tensor(-flat[np.arange(n), t].mean(), (logits,))
    
        def back(g):
            d = np.exp(flat)                # softmax probabilities
            d[np.arange(n), t] -= 1.0       # minus the one-hot target
            logits.add_grad(g * (d / n).reshape(logits.shape))
        out.backward_fn = back
        return out
    
    
    # ---------------------------------------------------------------- the model
    class GPT:
        def __init__(self, vocab_size, ctx, d_model, n_heads, n_layers, seed=0):
            assert d_model % n_heads == 0
            rng = np.random.default_rng(seed)
            self.V, self.T, self.C, self.H, self.L = vocab_size, ctx, d_model, n_heads, n_layers
    
            def w(*shape, std=0.02):
                return Tensor(rng.standard_normal(shape) * std)
            zeros = lambda n: Tensor(np.zeros(n))
            ones = lambda n: Tensor(np.ones(n))
            C, proj_std = d_model, 0.02 / math.sqrt(2 * n_layers)
            self.p = {"wte": w(vocab_size, C), "wpe": w(ctx, C)}
            for l in range(n_layers):
                self.p.update({
                    f"h{l}.ln1.g": ones(C), f"h{l}.ln1.b": zeros(C),
                    f"h{l}.attn.wq": w(C, C), f"h{l}.attn.wk": w(C, C), f"h{l}.attn.wv": w(C, C),
                    f"h{l}.attn.wo": w(C, C, std=proj_std), f"h{l}.attn.bo": zeros(C),
                    f"h{l}.ln2.g": ones(C), f"h{l}.ln2.b": zeros(C),
                    f"h{l}.mlp.w1": w(C, 4 * C), f"h{l}.mlp.b1": zeros(4 * C),
                    f"h{l}.mlp.w2": w(4 * C, C, std=proj_std), f"h{l}.mlp.b2": zeros(C),
                })
            self.p["lnf.g"], self.p["lnf.b"] = ones(C), zeros(C)
    
        def n_params(self):
            return sum(t.data.size for t in self.p.values())
    
        def attention(self, x, l):
            B, T, C = x.shape
            H, hd = self.H, C // self.H
            p = self.p
    
            def heads(t):                   # (B, T, C) -> (B, H, T, hd)
                return transpose(reshape(t, (B, T, H, hd)), 1, 2)
            q = heads(x @ p[f"h{l}.attn.wq"])
            k = heads(x @ p[f"h{l}.attn.wk"])
            v = heads(x @ p[f"h{l}.attn.wv"])
            att = scale(q @ transpose(k, 2, 3), 1.0 / math.sqrt(hd))   # (B, H, T, T)
            att = causal_softmax(att)
            y = att @ v                                                 # (B, H, T, hd)
            y = reshape(transpose(y, 1, 2), (B, T, C))                  # heads side by side
            return y @ p[f"h{l}.attn.wo"] + p[f"h{l}.attn.bo"]
    
        def mlp(self, x, l):
            p = self.p
            h = gelu(x @ p[f"h{l}.mlp.w1"] + p[f"h{l}.mlp.b1"])
            return h @ p[f"h{l}.mlp.w2"] + p[f"h{l}.mlp.b2"]
    
        def forward(self, ids, targets=None):
            B, T = ids.shape
            assert T <= self.T, "sequence longer than the context window"
            p = self.p
            x = embedding(p["wte"], ids) + embedding(p["wpe"], np.arange(T))
            for l in range(self.L):         # pre-norm residual blocks
                x = x + self.attention(layer_norm(x, p[f"h{l}.ln1.g"], p[f"h{l}.ln1.b"]), l)
                x = x + self.mlp(layer_norm(x, p[f"h{l}.ln2.g"], p[f"h{l}.ln2.b"]), l)
            x = layer_norm(x, p["lnf.g"], p["lnf.b"])
            logits = x @ transpose(p["wte"], 0, 1)      # weight tying: reuse the embedding
            loss = None if targets is None else cross_entropy(logits, targets)
            return logits, loss
    
    
    # ---------------------------------------------------------------- checks
    def grad_check(model, ids, targets, rng, per_tensor=6, h=1e-5):
        """Compare backprop gradients with (f(w+h) - f(w-h)) / 2h on random entries."""
        for t in model.p.values():
            t.grad = None
        _, loss = model.forward(ids, targets)
        loss.backward()
        worst = 0.0
        for name, t in model.p.items():
            flat = t.data.reshape(-1)       # a view: editing it edits the weight
            for i in rng.choice(flat.size, size=min(per_tensor, flat.size), replace=False):
                old = flat[i]
                flat[i] = old + h
                plus = model.forward(ids, targets)[1].data
                flat[i] = old - h
                minus = model.forward(ids, targets)[1].data
                flat[i] = old
                num = (plus - minus) / (2 * h)
                ana = t.grad.reshape(-1)[i]
                rel = abs(num - ana) / max(1e-8, abs(num) + abs(ana))
                worst = max(worst, rel)
        return worst
    
    
    if __name__ == "__main__":
        V, T, C, H, L = 13, 8, 16, 4, 2
        model = GPT(V, T, C, H, L, seed=0)
        rng = np.random.default_rng(1)
        ids = rng.integers(0, V, size=(3, T))
        targets = rng.integers(0, V, size=(3, T))
    
        logits, loss = model.forward(ids, targets)
        print(f"config: vocab={V} context={T} d_model={C} heads={H} layers={L}")
        print(f"parameters: {model.n_params():,} in {len(model.p)} tensors")
        print("input ids shape:", ids.shape, "-> logits shape:", logits.shape)
        print(f"loss at init: {float(loss.data):.3f}   ln(vocab) = {math.log(V):.3f}")
    
        # causality: changing the LAST token must not change predictions at earlier positions
        ids2 = ids.copy()
        ids2[:, -1] = (ids2[:, -1] + 1) % V
        logits2, _ = model.forward(ids2)
        same = np.allclose(logits.data[:, :-1], logits2.data[:, :-1])
        print("earlier positions unaffected by a future token:", "yes" if same else "NO")
    
        # Fresh weights give tiny gradients (logits are almost uniform), which can hide bugs
        # under rounding noise. Shake every weight a little before checking.
        for t in model.p.values():
            t.data += rng.standard_normal(t.shape) * 0.3
        worst = grad_check(model, ids, targets, np.random.default_rng(2))
        n_checked = sum(min(6, t.data.size) for t in model.p.values())
        status = "PASS" if worst < 1e-5 else "FAIL"
        print(f"gradient check on {n_checked} weights: {status} (max relative error < 1e-5)")
    1. self.backward_fn = backward: each tensor carries the function that pushes its gradient to its parents; leaf tensors (the weights) have none.
    2. visit(t) inside backward: a depth-first search that appends each tensor after its parents, giving a topological order; walking it in reverse visits the loss first and the weights last.
    3. out.backward_fn = lambda g: (a.add_grad(...), b.add_grad(...)) in add: addition sends the incoming gradient unchanged to both inputs (after unbroadcasting).
    4. a2 = a.data.reshape(-1, K) in matmul: for weight matrices, all leading axes are folded into one, so NumPy does a single large matrix product (much faster than many small ones), and the weight's gradient is a2.T @ g2.
    5. np.add.at(dt, ids, g) in embedding: accumulates the gradient for repeated tokens correctly.
    6. future = np.triu(np.ones((T, T), dtype=bool), k=1) in causal_softmax: True above the diagonal, that is, for every key position later than the query; those scores are set to −109 before the softmax.
    7. p * (g - (g * p).sum(-1, keepdims=True)): the softmax backward rule. Masked entries have p = 0, so no gradient leaks into the future.
    8. proj_std = 0.02 / math.sqrt(2 * n_layers): the matrices that write into the residual stream start smaller, so that adding 2L contributions does not make the stream grow with depth (the GPT-2 initialisation).
    9. logits = x @ transpose(p["wte"], 0, 1): weight tying: the output layer is the embedding table, transposed.
    10. t.data += rng.standard_normal(t.shape) * 0.3 before the gradient check: fresh weights give almost uniform predictions and tiny gradients, which can hide bugs under rounding noise, so we shake the weights first.
    11. rel = abs(num - ana) / max(1e-8, abs(num) + abs(ana)): the relative error between the numerical and the backprop gradient; the worst one over 180 sampled weights must be below 10−5.
    config: vocab=13 context=8 d_model=16 heads=4 layers=2
    parameters: 6,832 in 30 tensors
    input ids shape: (3, 8) -> logits shape: (3, 8, 13)
    loss at init: 2.580   ln(vocab) = 2.565
    earlier positions unaffected by a future token: yes
    gradient check on 180 weights: PASS (max relative error < 1e-5)

    All four checks pass. The toy model has 6,832 parameters in 30 tensors; its initial loss of 2.580 is right next to ln 13 = 2.565; changing the last token leaves earlier positions untouched; and the gradients from our engine agree with the numerical slopes for 180 randomly chosen weights across every tensor. Only now is the model worth training. With the real configuration (V = 169, T = 32, C = 48, 2 layers, 4 heads) the same code has 66,000 parameters.

    What real GPT-style models do differently

    Our model is architecturally a small GPT-2. Large public models built since then keep the same skeleton (embeddings, a stack of pre-norm residual blocks with causal attention and an MLP, a final norm and an output layer) but change several parts, most of which you met in module 4:

    PartOur tiny GPTCommon in recent public models Industry practice
    PositionsLearned position tableRotary embeddings (RoPE) inside attention (lesson 4.4)
    NormalisationLayerNormRMSNorm (lesson 4.8)
    MLPGELU, 4× widthGated SwiGLU (lesson 4.7); sometimes a mixture of experts
    Attention4 heads, each with its own keys and valuesGrouped-query attention (several query heads share one key/value head) to shrink the KV cache
    BiasesBiases in projectionsOften no biases at all
    Size2 layers, width 48, 66 thousand parametersDozens to over a hundred layers, widths in the thousands, billions to hundreds of billions of parameters

    Anthropic has described Claude publicly as a transformer-based language model. Not public Its exact architecture (number of layers, width, attention variant, parameter count, whether it uses mixture of experts) has not been published, so we do not claim that any row of the right-hand column applies to Claude. Lesson 6.1 discusses what is and is not known.

    Why reverse mode, and what it costs in memory

    Our model maps 66,000 inputs (the weights) to one output (the loss). Reverse-mode differentiation computes the gradient with respect to all inputs in one backward pass that costs about twice the forward pass, which is why the usual estimate for a training step is "about three forward passes". Forward-mode differentiation would need one pass per weight: 66,000 passes. For functions with many inputs and one output, reverse mode is the only practical choice, and every deep learning framework uses it.

    The price is memory. The backward pass needs the intermediate values of the forward pass (our Tensor objects keep xhat, p, th and so on), so memory grows with batch size × context length × number of layers. The attention probabilities alone are B × H × T × T numbers per layer. Large-scale training reduces this with activation checkpointing (store only some activations and recompute the rest during the backward pass) and fused attention kernels such as FlashAttention that never materialise the full T × T matrix. You saw the inference-time counterpart of this memory problem, the KV cache, in lesson 4.9.

    One more subtlety: the gradient check uses float64. In float32 or 16-bit formats, finite differences are too noisy to verify gradients to 10−5, which is why gradient checks are always run in double precision on tiny models, exactly as here, before the real training run uses lower precision.

    Common mistakes and debugging tips

    Forgetting to reset gradients between steps

    add_grad accumulates (it must, because a tensor used twice receives two gradients). If you never reset p.grad, each step adds to the previous one, and updates grow until training diverges.

    Fix: set every parameter's grad to None before each forward pass, as the training loop in lesson 5.6 does (PyTorch's equivalent is optimizer.zero_grad()).

    A parameter that is never used

    If you remove a LayerNorm bias from the forward pass but leave it in the parameter dictionary, its gradient stays None and the optimizer or the gradient check crashes, or, in a framework, silently never updates it.

    Fix: after the first backward pass, assert that every parameter has a gradient, and remove parameters the forward pass does not use.

    The mask on the wrong side of the diagonal

    np.triu(..., k=0) also masks each token's view of itself, and np.tril masks the past instead of the future. Both still train; the second one lets the model read the answer, so the training loss collapses towards zero while generation is nonsense.

    Fix: run the causality test: change the last token and check that the earlier logits are unchanged. Also be suspicious of a training loss that falls far below a sensible value.

    Gradient check "fails" by a tiny amount

    Relative errors around 10−4 with float32, or with a step h that is too large or too small, are usually noise, not bugs.

    Fix: use float64 and h ≈ 10−5; a real bug typically gives a relative error near 1 for the affected tensor. Check tensors one by one to locate it.

    Key takeaways

    • A decoder-only GPT is: token + position embeddings, L pre-norm blocks (causal attention and MLP, each added to a residual stream), a final norm, and an output layer (here tied to the embeddings).
    • Reverse-mode autodiff records each operation with a local backward rule and applies the chain rule from the loss back to every weight.
    • Before training, check shapes, the ln V starting loss, causality and gradients against finite differences.
    • Large public models keep this skeleton but change positions, norms, MLPs, attention sharing and scale; Claude's specific architecture is not public.

    Exercise: swap in RMSNorm and prove it is correct

    Add an rms_norm(x, gain) operation to the autodiff engine in gpt_numpy.py (RMSNorm from lesson 4.8: divide by the root mean square, multiply by a gain, no mean subtraction and no bias). Use it for the first norm of every block, then run the file. The gradient check must still pass.

    Hint

    With inv = 1 / sqrt(mean(x²) + eps) and xhat = x * inv, the backward rule for the input is inv * (dxhat - xhat * mean(dxhat * xhat)), where dxhat = g * gain. Remember to remove the now-unused ln1.b parameters, or the gradient check will find a gradient of None.

    Show a solution
    def rms_norm(x, gain, eps=1e-5):
        inv = 1.0 / np.sqrt((x.data * x.data).mean(-1, keepdims=True) + eps)
        xhat = x.data * inv
        out = Tensor(xhat * gain.data, (x, gain))
    
        def back(g):
            gain.add_grad(unbroadcast(g * xhat, gain.shape))
            dxhat = g * gain.data
            x.add_grad(inv * (dxhat - xhat * (dxhat * xhat).mean(-1, keepdims=True)))
        out.backward_fn = back
        return out

    In __init__, replace f"h{l}.ln1.g": ones(C), f"h{l}.ln1.b": zeros(C), with f"h{l}.ln1.g": ones(C),, and in forward use rms_norm(x, p[f"h{l}.ln1.g"]) for the attention input. Running the file then reports a gradient check on 168 weights (two tensors fewer, six samples each) and PASS. The derivation: xhat depends on x directly and through inv; differentiating inv gives the second term, which removes the component of dxhat along xhat.

    Check your understanding

    What does "weight tying" mean in our GPT?

    1. All blocks share the same attention weights
    2. The query and key matrices are equal
    3. The output layer uses the transpose of the token embedding table instead of its own matrix
    Tying reuses the V × C embedding table to produce the V logits, saving V × C parameters. Blocks have separate weights, and queries and keys use separate matrices.

    Why does the embedding backward pass use np.add.at instead of dt[ids] += g?

    1. When a token id appears more than once, += with fancy indexing keeps only one of its gradients; add.at adds them all
    2. add.at is faster
    3. Embeddings have no gradient otherwise
    NumPy's buffered fancy-index assignment writes each repeated index once, losing contributions. np.add.at is unbuffered and accumulates every occurrence. It is actually slower, but correct.

    You change the last token of a sequence and the logits at position 0 change too. What is the most likely bug?

    1. The learning rate is too high
    2. The causal mask is wrong, so earlier positions can see later tokens
    3. The vocabulary is too small
    With a correct causal mask, position 0 depends only on token 0. Any dependence on later tokens means information leaks from the future, which also lets the model cheat during training. Learning rate and vocabulary size do not affect this test.

    Lesson 5.6Module 5: Build a GPT-like model

    Training a tiny language model

    • ⏱ 32 min read
    • Advanced

    Learning objectives

    • Write the training loop of a language model: batch, forward, loss, backward, gradient clipping, optimizer step.
    • Explain AdamW, learning-rate warmup with cosine decay, and gradient clipping, and why each is standard for transformers.
    • Train the tiny GPT on a real corpus and read its training and validation curves, including overfitting.
    • Estimate training compute with the 6 × parameters × tokens rule and compare it honestly with frontier-scale training.

    Everything is ready: a tokenizer and vocabulary (lessons 5.1 and 5.2), batches of shifted windows (5.3), a loss (5.4) and a model whose gradients we have verified (5.5). This lesson connects them in a training loop and runs it. On a laptop CPU the whole run takes about 20 seconds, and at the end you will have a real (if very small) language model that has learned something about the town of Lindale, and that also shows, in miniature, the main failure modes of training.

    Analogy: learning to drive a new car

    On the first morning you drive slowly in an empty car park (warmup), because you do not yet know how the car responds. Once you have a feel for it, you drive at normal speed, and as you get close to your destination you slow down to park precisely (decay). If the car suddenly lurches on ice, you do not turn the steering wheel as far as the lurch suggests; you cap your correction (clipping). And an experienced driver does not react to every bump on its own, but to the trend of the road over the last few seconds (momentum, in Adam). A good training schedule is exactly this kind of careful driving.

    The training loop

    One training step does six things, in this order. You wrote the same loop for a small network in lesson 3.6; only the model and the data are new.

    1. Pick the learning rate for this step from the schedule.
    2. Sample a batch of B = 8 random windows of T = 32 tokens, with their shifted targets.
    3. Reset every parameter's gradient.
    4. Run the forward pass to get the average loss over all 256 positions.
    5. Run the backward pass to fill in every gradient, then clip their overall size.
    6. Let the optimizer update every weight.
    for step in range(1, STEPS + 1):
        lr = lr_at(step - 1, MAX_LR, WARMUP, STEPS)
        x, y = get_batch("train", BATCH, CTX, rng)
        for p in model.p.values():
            p.grad = None                                  # forget last step's gradients
        _, loss = model.forward(x, y)
        loss.backward()
        norm = clip_grads(model.p, CLIP)
        opt.step(lr)

    Every 40 steps the script also measures the loss on 4 fixed batches from the training split and 4 from the validation split. The batch loss printed during training is noisy (it is one random batch), so these fixed evaluation batches give a steadier picture. The loop also remembers the weights from the step with the best validation loss, so you could keep the best model rather than the last one.

    The optimizer: AdamW

    Plain gradient descent moves every weight by the learning rate times its gradient. That works poorly for transformers: the gradients of different weights differ in scale by orders of magnitude (embedding rows of rare tokens versus attention matrices used at every position), and individual batches are noisy. Adam, which you met in lesson 3.5, fixes both: it keeps, for each weight, a running average of its gradients (momentum, which smooths the noise) and a running average of squared gradients (which measures the typical size of that weight's gradient), and divides one by the square root of the other. Every weight then moves by roughly the learning rate, whatever the raw scale of its gradient. AdamW adds weight decay, a gentle pull of every matrix towards zero, applied separately from the gradient:

    mt=β1mt−1+(1−β1)gt,vt=β2vt−1+(1−β2)gt2w←w−η(m^tv^t+ε+λw),m^t=mt1−β1t,v^t=vt1−β2t

    In words: m is a running average of the gradient and v a running average of its square. Because both start at zero, they are divided by (1 − βt) early on to remove the bias. Each weight moves against its averaged gradient divided by that gradient's typical size, plus a small decay λw. We use β₁ = 0.9, β₂ = 0.95, λ = 0.1, the values popularised by GPT-style training.

    class AdamW:
        """Adam with decoupled weight decay: a running mean (m) and a running mean of
        squares (v) of every gradient, per weight."""
    
        def __init__(self, params, betas=(0.9, 0.95), eps=1e-8, weight_decay=0.1):
            self.params = params
            self.b1, self.b2, self.eps, self.wd = betas[0], betas[1], eps, weight_decay
            self.m = {k: np.zeros_like(p.data) for k, p in params.items()}
            self.v = {k: np.zeros_like(p.data) for k, p in params.items()}
            self.t = 0
    
        def step(self, lr):
            self.t += 1
            for k, p in self.params.items():
                g = p.grad
                self.m[k] = self.b1 * self.m[k] + (1 - self.b1) * g
                self.v[k] = self.b2 * self.v[k] + (1 - self.b2) * g * g
                m_hat = self.m[k] / (1 - self.b1 ** self.t)     # bias correction: m, v start at 0
                v_hat = self.v[k] / (1 - self.b2 ** self.t)
                if p.data.ndim >= 2:                            # decay matrices, not gains/biases
                    p.data -= lr * self.wd * p.data
                p.data -= lr * m_hat / (np.sqrt(v_hat) + self.eps)

    Note if p.data.ndim >= 2: weight decay is applied only to matrices, not to LayerNorm gains and biases. Pulling a LayerNorm gain towards zero would just fight the normalisation, so it is standard to exclude them.

    Warmup, cosine decay and clipping

    At step 1, Adam's running averages are based on a single batch, and the randomly initialised network can produce large, unrepresentative gradients. A full-size learning rate at that moment can push the weights somewhere bad that takes a long time to recover from. So the learning rate warms up linearly from almost zero over the first 36 steps (10% of the run). After that it follows a cosine curve down to 10% of its peak: large steps while the loss is high, small careful steps at the end, when the model is fine-tuning details. Explore the shape:

    Learning-rate scheduleInteractive

    def lr_at(step, max_lr, warmup, total, min_ratio=0.1):
        """Linear warmup, then cosine decay down to min_ratio * max_lr."""
        if step < warmup:
            return max_lr * (step + 1) / warmup
        progress = (step - warmup) / max(1, total - warmup)
        return max_lr * (min_ratio + (1 - min_ratio) * 0.5 * (1 + math.cos(math.pi * progress)))
    
    
    def clip_grads(params, max_norm):
        """Scale all gradients down together if their global L2 norm exceeds max_norm."""
        norm = math.sqrt(sum(float((p.grad ** 2).sum()) for p in params.values()))
        if norm > max_norm:
            for p in params.values():
                p.grad *= max_norm / norm
        return norm

    Gradient clipping handles the occasional bad batch. All gradients are treated as one long vector; if its length (the global L2 norm) exceeds 1.0, every gradient is scaled down by the same factor, so the direction is kept but the step is capped. The script prints the norm before clipping; in our run it hovers between 1.1 and 1.9, so clipping is active on most steps, gently limiting the update size. You met clipping as the fix for exploding gradients in lesson 4.1.

    The run

    train_gpt.py is one self-contained file: it repeats the tokenizer, vocabulary, engine and model code from the previous lessons (so you can run it on its own), then adds the optimizer, data loading, sampling and the loop. It reads corpus.txt, so run it locally: python train_gpt.py with NumPy installed. It took about 20 seconds on our test machine; your numbers may differ in the last digits on a different CPU or NumPy build, because floating-point sums can be computed in a different order.

    Show the complete train_gpt.py
    # @run
    # train_gpt.py: train the tiny GPT from lesson 5.5 on corpus.txt (about 9 KB of simple English).
    # One file on purpose, so it runs on its own: the BPE tokenizer (same code as bpe.py), the
    # vocabulary (vocab.py), the autodiff engine and model (gpt_numpy.py), then data, AdamW, the
    # training loop and sampling. NumPy only, CPU only, well under a minute on a laptop.
    import math
    import os
    import re
    from collections import Counter
    
    import numpy as np
    
    # =============================================================== 1. tokenizer (lesson 5.1)
    CHUNK = re.compile(r" ?[A-Za-z]+| ?[0-9]+| ?[^\sA-Za-z0-9]+|\s+")
    
    
    def pair_counts(chunks):
        counts = Counter()
        for ids, freq in chunks.items():
            for a, b in zip(ids, ids[1:]):
                counts[(a, b)] += freq
        return counts
    
    
    def merge(ids, pair, new_id):
        out, i = [], 0
        while i < len(ids):
            if i < len(ids) - 1 and (ids[i], ids[i + 1]) == pair:
                out.append(new_id)
                i += 2
            else:
                out.append(ids[i])
                i += 1
        return tuple(out)
    
    
    def train_bpe(text, n_merges):
        words = Counter(CHUNK.findall(text))
        chunks = {tuple(w.encode("utf-8")): f for w, f in words.items()}
        vocab = {i: bytes([i]) for i in range(256)}
        merges = {}
        for _ in range(n_merges):
            counts = pair_counts(chunks)
            if not counts:
                break
            pair, n = max(counts.items(), key=lambda kv: kv[1])
            if n < 2:
                break
            new_id = 256 + len(merges)
            merges[pair] = new_id
            vocab[new_id] = vocab[pair[0]] + vocab[pair[1]]
            chunks = {merge(ids, pair, new_id): f for ids, f in chunks.items()}
        return merges, vocab
    
    
    def bpe_encode(text, merges):
        out = []
        for chunk in CHUNK.findall(text):
            ids = tuple(chunk.encode("utf-8"))
            while len(ids) >= 2:
                pair = min(zip(ids, ids[1:]), key=lambda p: merges.get(p, float("inf")))
                if pair not in merges:
                    break
                ids = merge(ids, pair, merges[pair])
            out.extend(ids)
        return out
    
    
    # =============================================================== 2. vocabulary (lesson 5.2)
    SPECIALS = ["<|eos|>", "<|unk|>"]
    
    
    def build_vocab(text, merges, bpe_vocab):
        """Specials first, then every byte the corpus uses, then every merge (as in vocab.py)."""
        keep = sorted(set(text.encode("utf-8"))) + list(range(256, 256 + len(merges)))
        itos = [s.encode("utf-8") for s in SPECIALS] + [bpe_vocab[i] for i in keep]
        to_model = {b: len(SPECIALS) + k for k, b in enumerate(keep)}
        return itos, to_model
    
    
    def encode(text):
        return [to_model.get(i, UNK) for i in bpe_encode(text, merges)]
    
    
    def decode(ids):
        return b"".join(itos[i] for i in ids).decode("utf-8", errors="replace")
    
    
    # =============================================================== 3. autodiff engine + model (lesson 5.5)
    class Tensor:
        """A NumPy array that remembers how it was made, so it can send gradients back."""
    
        def __init__(self, data, parents=(), backward=None):
            self.data = np.asarray(data, dtype=np.float64)
            self.grad = None
            self.parents = parents          # tensors this one was computed from
            self.backward_fn = backward     # pushes self.grad into the parents
    
        @property
        def shape(self):
            return self.data.shape
    
        def add_grad(self, g):
            self.grad = g if self.grad is None else self.grad + g
    
        def backward(self):
            order, seen = [], set()
    
            def visit(t):                   # topological order: parents before children
                if id(t) not in seen:
                    seen.add(id(t))
                    for p in t.parents:
                        visit(p)
                    order.append(t)
            visit(self)
            self.grad = np.ones_like(self.data)
            for t in reversed(order):       # walk from the loss back to the weights
                if t.backward_fn is not None:
                    t.backward_fn(t.grad)
    
        def __add__(self, other):
            return add(self, other)
    
        def __matmul__(self, other):
            return matmul(self, other)
    
    
    def unbroadcast(g, shape):
        """Sum a gradient back down to `shape` (undo NumPy broadcasting)."""
        while g.ndim > len(shape):
            g = g.sum(axis=0)
        for i, n in enumerate(shape):
            if n == 1 and g.shape[i] != 1:
                g = g.sum(axis=i, keepdims=True)
        return g
    
    
    def add(a, b):
        out = Tensor(a.data + b.data, (a, b))
        out.backward_fn = lambda g: (a.add_grad(unbroadcast(g, a.shape)),
                                     b.add_grad(unbroadcast(g, b.shape)))
        return out
    
    
    def scale(a, c):
        out = Tensor(a.data * c, (a,))
        out.backward_fn = lambda g: a.add_grad(g * c)
        return out
    
    
    def matmul(a, b):
        if b.data.ndim == 2:
            # (..., K) @ (K, N): fold every leading axis into one so NumPy uses one big BLAS call
            K = a.shape[-1]
            a2 = a.data.reshape(-1, K)
            out = Tensor((a2 @ b.data).reshape(a.shape[:-1] + (b.shape[1],)), (a, b))
    
            def back(g):
                g2 = g.reshape(-1, b.shape[1])
                a.add_grad((g2 @ b.data.T).reshape(a.shape))
                b.add_grad(a2.T @ g2)
            out.backward_fn = back
            return out
        out = Tensor(a.data @ b.data, (a, b))        # batched (B, H, T, T) style products
    
        def back(g):
            a.add_grad(unbroadcast(g @ np.swapaxes(b.data, -1, -2), a.shape))
            b.add_grad(unbroadcast(np.swapaxes(a.data, -1, -2) @ g, b.shape))
        out.backward_fn = back
        return out
    
    
    def reshape(a, shape):
        out = Tensor(a.data.reshape(shape), (a,))
        out.backward_fn = lambda g: a.add_grad(g.reshape(a.shape))
        return out
    
    
    def transpose(a, ax1, ax2):
        out = Tensor(np.swapaxes(a.data, ax1, ax2), (a,))
        out.backward_fn = lambda g: a.add_grad(np.swapaxes(g, ax1, ax2))
        return out
    
    
    def embedding(table, ids):
        """Row lookup: out[b, t] = table[ids[b, t]]."""
        out = Tensor(table.data[ids], (table,))
    
        def back(g):
            dt = np.zeros_like(table.data)
            np.add.at(dt, ids, g)           # a row used twice gets both gradients
            table.add_grad(dt)
        out.backward_fn = back
        return out
    
    
    def layer_norm(x, gain, bias, eps=1e-5):
        mu = x.data.mean(axis=-1, keepdims=True)
        var = x.data.var(axis=-1, keepdims=True)
        inv = 1.0 / np.sqrt(var + eps)
        xhat = (x.data - mu) * inv
        out = Tensor(xhat * gain.data + bias.data, (x, gain, bias))
    
        def back(g):
            gain.add_grad(unbroadcast(g * xhat, gain.shape))
            bias.add_grad(unbroadcast(g, bias.shape))
            dxhat = g * gain.data
            n = x.shape[-1]
            dx = inv / n * (n * dxhat - dxhat.sum(-1, keepdims=True)
                            - xhat * (dxhat * xhat).sum(-1, keepdims=True))
            x.add_grad(dx)
        out.backward_fn = back
        return out
    
    
    def gelu(x):
        """GELU, tanh approximation (as in GPT-2)."""
        c = math.sqrt(2.0 / math.pi)
        x2 = x.data * x.data                # x*x is much faster than x**2 in NumPy
        th = np.tanh(c * (x.data + 0.044715 * x2 * x.data))
        out = Tensor(0.5 * x.data * (1.0 + th), (x,))
    
        def back(g):
            du = c * (1.0 + 3 * 0.044715 * x2)
            x.add_grad(g * (0.5 * (1.0 + th) + 0.5 * x.data * (1.0 - th * th) * du))
        out.backward_fn = back
        return out
    
    
    def causal_softmax(scores):
        """Softmax over the last axis where position t may only look at positions <= t."""
        T = scores.shape[-1]
        future = np.triu(np.ones((T, T), dtype=bool), k=1)
        s = np.where(future, -1e9, scores.data)
        s = s - s.max(axis=-1, keepdims=True)
        e = np.exp(s)
        p = e / e.sum(axis=-1, keepdims=True)
        out = Tensor(p, (scores,))
        # softmax backward: dS = P * (dP - sum(dP * P)); masked entries have P = 0
        out.backward_fn = lambda g: scores.add_grad(p * (g - (g * p).sum(-1, keepdims=True)))
        return out
    
    
    def cross_entropy(logits, targets):
        """Mean of -log softmax(logits)[target] over every position."""
        z = logits.data - logits.data.max(axis=-1, keepdims=True)
        logp = z - np.log(np.exp(z).sum(axis=-1, keepdims=True))
        flat = logp.reshape(-1, logp.shape[-1])
        t = targets.reshape(-1)
        n = t.shape[0]
        out = Tensor(-flat[np.arange(n), t].mean(), (logits,))
    
        def back(g):
            d = np.exp(flat)                # softmax probabilities
            d[np.arange(n), t] -= 1.0       # minus the one-hot target
            logits.add_grad(g * (d / n).reshape(logits.shape))
        out.backward_fn = back
        return out
    
    
    # ---- the model: same code as gpt_numpy.py
    class GPT:
        def __init__(self, vocab_size, ctx, d_model, n_heads, n_layers, seed=0):
            assert d_model % n_heads == 0
            rng = np.random.default_rng(seed)
            self.V, self.T, self.C, self.H, self.L = vocab_size, ctx, d_model, n_heads, n_layers
    
            def w(*shape, std=0.02):
                return Tensor(rng.standard_normal(shape) * std)
            zeros = lambda n: Tensor(np.zeros(n))
            ones = lambda n: Tensor(np.ones(n))
            C, proj_std = d_model, 0.02 / math.sqrt(2 * n_layers)
            self.p = {"wte": w(vocab_size, C), "wpe": w(ctx, C)}
            for l in range(n_layers):
                self.p.update({
                    f"h{l}.ln1.g": ones(C), f"h{l}.ln1.b": zeros(C),
                    f"h{l}.attn.wq": w(C, C), f"h{l}.attn.wk": w(C, C), f"h{l}.attn.wv": w(C, C),
                    f"h{l}.attn.wo": w(C, C, std=proj_std), f"h{l}.attn.bo": zeros(C),
                    f"h{l}.ln2.g": ones(C), f"h{l}.ln2.b": zeros(C),
                    f"h{l}.mlp.w1": w(C, 4 * C), f"h{l}.mlp.b1": zeros(4 * C),
                    f"h{l}.mlp.w2": w(4 * C, C, std=proj_std), f"h{l}.mlp.b2": zeros(C),
                })
            self.p["lnf.g"], self.p["lnf.b"] = ones(C), zeros(C)
    
        def n_params(self):
            return sum(t.data.size for t in self.p.values())
    
        def attention(self, x, l):
            B, T, C = x.shape
            H, hd = self.H, C // self.H
            p = self.p
    
            def heads(t):                   # (B, T, C) -> (B, H, T, hd)
                return transpose(reshape(t, (B, T, H, hd)), 1, 2)
            q = heads(x @ p[f"h{l}.attn.wq"])
            k = heads(x @ p[f"h{l}.attn.wk"])
            v = heads(x @ p[f"h{l}.attn.wv"])
            att = scale(q @ transpose(k, 2, 3), 1.0 / math.sqrt(hd))   # (B, H, T, T)
            att = causal_softmax(att)
            y = att @ v                                                 # (B, H, T, hd)
            y = reshape(transpose(y, 1, 2), (B, T, C))                  # heads side by side
            return y @ p[f"h{l}.attn.wo"] + p[f"h{l}.attn.bo"]
    
        def mlp(self, x, l):
            p = self.p
            h = gelu(x @ p[f"h{l}.mlp.w1"] + p[f"h{l}.mlp.b1"])
            return h @ p[f"h{l}.mlp.w2"] + p[f"h{l}.mlp.b2"]
    
        def forward(self, ids, targets=None):
            B, T = ids.shape
            assert T <= self.T, "sequence longer than the context window"
            p = self.p
            x = embedding(p["wte"], ids) + embedding(p["wpe"], np.arange(T))
            for l in range(self.L):         # pre-norm residual blocks
                x = x + self.attention(layer_norm(x, p[f"h{l}.ln1.g"], p[f"h{l}.ln1.b"]), l)
                x = x + self.mlp(layer_norm(x, p[f"h{l}.ln2.g"], p[f"h{l}.ln2.b"]), l)
            x = layer_norm(x, p["lnf.g"], p["lnf.b"])
            logits = x @ transpose(p["wte"], 0, 1)      # weight tying: reuse the embedding
            loss = None if targets is None else cross_entropy(logits, targets)
            return logits, loss
    
    
    # =============================================================== 4. optimizer (lesson 5.6)
    class AdamW:
        """Adam with decoupled weight decay: a running mean (m) and a running mean of
        squares (v) of every gradient, per weight."""
    
        def __init__(self, params, betas=(0.9, 0.95), eps=1e-8, weight_decay=0.1):
            self.params = params
            self.b1, self.b2, self.eps, self.wd = betas[0], betas[1], eps, weight_decay
            self.m = {k: np.zeros_like(p.data) for k, p in params.items()}
            self.v = {k: np.zeros_like(p.data) for k, p in params.items()}
            self.t = 0
    
        def step(self, lr):
            self.t += 1
            for k, p in self.params.items():
                g = p.grad
                self.m[k] = self.b1 * self.m[k] + (1 - self.b1) * g
                self.v[k] = self.b2 * self.v[k] + (1 - self.b2) * g * g
                m_hat = self.m[k] / (1 - self.b1 ** self.t)     # bias correction: m, v start at 0
                v_hat = self.v[k] / (1 - self.b2 ** self.t)
                if p.data.ndim >= 2:                            # decay matrices, not gains/biases
                    p.data -= lr * self.wd * p.data
                p.data -= lr * m_hat / (np.sqrt(v_hat) + self.eps)
    
    
    def lr_at(step, max_lr, warmup, total, min_ratio=0.1):
        """Linear warmup, then cosine decay down to min_ratio * max_lr."""
        if step < warmup:
            return max_lr * (step + 1) / warmup
        progress = (step - warmup) / max(1, total - warmup)
        return max_lr * (min_ratio + (1 - min_ratio) * 0.5 * (1 + math.cos(math.pi * progress)))
    
    
    def clip_grads(params, max_norm):
        """Scale all gradients down together if their global L2 norm exceeds max_norm."""
        norm = math.sqrt(sum(float((p.grad ** 2).sum()) for p in params.values()))
        if norm > max_norm:
            for p in params.values():
                p.grad *= max_norm / norm
        return norm
    
    
    # =============================================================== 5. data (lessons 5.2-5.3)
    HERE = os.path.dirname(os.path.abspath(__file__))
    with open(os.path.join(HERE, "corpus.txt"), encoding="utf-8") as f:
        raw = f.read()
    paragraphs = [" ".join(p.split()) for p in raw.split("\n\n") if p.strip()]   # tidy whitespace
    
    N_MERGES = 120
    merges, bpe_vocab = train_bpe(" ".join(paragraphs), N_MERGES)
    itos, to_model = build_vocab(" ".join(paragraphs), merges, bpe_vocab)
    EOS, UNK = 0, 1
    ids = []
    for p in paragraphs:
        ids += encode(p) + [EOS]           # <|eos|> marks where one paragraph ends
    data = np.array(ids)
    n_val = len(data) // 10                # last 10% of tokens = validation text
    train_data, val_data = data[:-n_val], data[-n_val:]
    
    
    def get_batch(split, batch_size, ctx, rng):
        d = train_data if split == "train" else val_data
        starts = rng.integers(0, len(d) - ctx - 1, size=batch_size)
        x = np.stack([d[s:s + ctx] for s in starts])
        y = np.stack([d[s + 1:s + ctx + 1] for s in starts])   # the same window, shifted by one
        return x, y
    
    
    def estimate_loss(model, batch_size, ctx, n_batches=4):
        out = {}
        for split in ("train", "val"):
            rng = np.random.default_rng(1234)                   # same eval batches every time
            losses = [float(model.forward(*get_batch(split, batch_size, ctx, rng))[1].data)
                      for _ in range(n_batches)]
            out[split] = sum(losses) / len(losses)
        return out
    
    
    # =============================================================== 6. sampling (lessons 5.7-5.8)
    def next_token_probs(model, ids, temperature=1.0, top_k=None, top_p=None):
        window = np.array([ids[-model.T:]])                    # crop to the context window
        logits, _ = model.forward(window)
        z = logits.data[0, -1].copy()                          # scores for the NEXT token only
        if temperature == 0:                                   # greedy: all mass on the best token
            p = np.zeros_like(z)
            p[int(z.argmax())] = 1.0
            return p
        z = z / temperature
        if top_k is not None:                                  # keep the k highest scores
            z[z < np.sort(z)[-top_k]] = -np.inf
        p = np.exp(z - z.max())
        p /= p.sum()
        if top_p is not None:                                  # keep the smallest set with mass >= top_p
            order = np.argsort(-p, kind="stable")
            keep = order[:int(np.searchsorted(np.cumsum(p[order]), top_p)) + 1]
            mask = np.zeros_like(p)
            mask[keep] = 1.0
            p = p * mask / (p * mask).sum()
        return p
    
    
    def generate(model, prompt, max_new, rng, **sampling):
        ids = encode(prompt)
        for _ in range(max_new):
            p = next_token_probs(model, ids, **sampling)
            nxt = int(rng.choice(len(p), p=p))
            if nxt == EOS:                                     # the model chose to end the paragraph
                break
            ids.append(nxt)
        return decode(ids)
    
    
    # =============================================================== 7. training (lesson 5.6)
    if __name__ == "__main__":
        CTX, D_MODEL, N_HEADS, N_LAYERS = 32, 48, 4, 2
        BATCH, STEPS, MAX_LR, WARMUP, CLIP, EVAL_EVERY = 8, 360, 6e-3, 36, 1.0, 40
        model = GPT(len(itos), CTX, D_MODEL, N_HEADS, N_LAYERS, seed=0)
        opt = AdamW(model.p)
        rng = np.random.default_rng(0)
        print(f"corpus: {len(raw):,} characters -> {len(data):,} tokens")
        print(f"vocab: {len(itos)} = {len(SPECIALS)} special + {len(itos) - len(SPECIALS) - len(merges)} bytes "
              f"+ {len(merges)} merges")
        print(f"train tokens: {len(train_data):,}   val tokens: {len(val_data):,}")
        print(f"model: {N_LAYERS} layers, {N_HEADS} heads, d_model {D_MODEL}, context {CTX}, "
              f"{model.n_params():,} parameters")
        ev = estimate_loss(model, BATCH, CTX)
        print(f"step   0 | train {ev['train']:.3f} | val {ev['val']:.3f} | ln(vocab) = {math.log(len(itos)):.3f}")
    
        best = (ev["val"], 0, {k: t.data.copy() for k, t in model.p.items()})
        for step in range(1, STEPS + 1):
            lr = lr_at(step - 1, MAX_LR, WARMUP, STEPS)
            x, y = get_batch("train", BATCH, CTX, rng)
            for p in model.p.values():
                p.grad = None                                  # forget last step's gradients
            _, loss = model.forward(x, y)
            loss.backward()
            norm = clip_grads(model.p, CLIP)
            opt.step(lr)
            if step % EVAL_EVERY == 0:
                ev = estimate_loss(model, BATCH, CTX)
                print(f"step {step:3d} | lr {lr:.4f} | batch {float(loss.data):.3f} "
                      f"| train {ev['train']:.3f} | val {ev['val']:.3f} | grad norm {norm:.2f}")
                if ev["val"] < best[0]:                        # remember the best weights so far
                    best = (ev["val"], step, {k: t.data.copy() for k, t in model.p.items()})
                if step in (120, STEPS):
                    s = generate(model, "Tom", 24, np.random.default_rng(7), temperature=0.8)
                    print(f"    sample: {s}")
    
        print(f"\nbest val loss {best[0]:.3f} at step {best[1]} (perplexity {math.exp(best[0]):.1f})")
        print("\n--- samples from the final model (temperature 0.8, top-k 20) ---")
        for prompt in ("Mira", "In winter", "The library"):
            print(">", generate(model, prompt, 32, np.random.default_rng(3), temperature=0.8, top_k=20))
    
        print("\n--- probes: what does the model believe comes next? ---")
        for prompt in ("The library opens at", "The doctor of Lindale is", "Captain Zorn"):
            p = next_token_probs(model, encode(prompt))
            top = np.argsort(-p, kind="stable")[:3]
            guesses = ", ".join(f"{decode([int(i)])!r} {float(p[i]):.2f}" for i in top)
            print(f"> {generate(model, prompt, 12, rng, temperature=0)}")
            print(f"    top guesses: {guesses}")
    1. paragraphs = [" ".join(p.split()) for p in raw.split("\n\n") if p.strip()]: one document per paragraph, with whitespace tidied (lesson 5.3).
    2. merges, bpe_vocab = train_bpe(...) and build_vocab(...): the 120-merge tokenizer and the 169-token vocabulary from lesson 5.2.
    3. ids += encode(p) + [EOS] and train_data, val_data = data[:-n_val], data[-n_val:]: one stream, last 10% held out.
    4. CTX, D_MODEL, N_HEADS, N_LAYERS = 32, 48, 4, 2: the model size; BATCH, STEPS, MAX_LR, WARMUP, CLIP, EVAL_EVERY = 8, 360, 6e-3, 36, 1.0, 40: the training settings. A peak learning rate of 0.006 is high by large-model standards but normal for a model this small.
    5. for p in model.p.values(): p.grad = None: resets gradients, because our engine accumulates them.
    6. norm = clip_grads(model.p, CLIP): clips and returns the norm before clipping, which is worth logging: sudden spikes are an early warning of instability.
    7. best = (ev["val"], step, {k: t.data.copy() ...}): keeps a copy of the weights whenever validation loss improves (the basis of early stopping).
    8. generate(model, "Tom", 24, ...): prints a short sample at step 120 and at the end, so you can watch the text improve. Sampling is the subject of lessons 5.7 and 5.8.
    corpus: 9,082 characters -> 4,421 tokens
    vocab: 169 = 2 special + 47 bytes + 120 merges
    train tokens: 3,979   val tokens: 442
    model: 2 layers, 4 heads, d_model 48, context 32, 66,000 parameters
    step   0 | train 5.136 | val 5.131 | ln(vocab) = 5.130
    step  40 | lr 0.0060 | batch 4.145 | train 4.112 | val 4.288 | grad norm 1.85
    step  80 | lr 0.0058 | batch 3.352 | train 3.365 | val 3.817 | grad norm 1.13
    step 120 | lr 0.0052 | batch 3.087 | train 3.201 | val 3.748 | grad norm 1.29
        sample: Tometetesep lOrarmmlks the cains bute. Tom.
    step 160 | lr 0.0043 | batch 3.021 | train 2.965 | val 3.721 | grad norm 1.26
    step 200 | lr 0.0033 | batch 2.960 | train 2.870 | val 3.606 | grad norm 1.29
    step 240 | lr 0.0023 | batch 2.824 | train 2.798 | val 3.474 | grad norm 1.43
    step 280 | lr 0.0014 | batch 2.577 | train 2.664 | val 3.537 | grad norm 1.38
    step 320 | lr 0.0008 | batch 2.470 | train 2.581 | val 3.514 | grad norm 1.20
    step 360 | lr 0.0006 | batch 2.516 | train 2.541 | val 3.488 | grad norm 1.43
        sample: Tomleoplelked ity. The beld She children to a fishoes,
    
    best val loss 3.474 at step 240 (perplexity 32.3)
    
    --- samples from the final model (temperature 0.8, top-k 20) ---
    > Mirace to abrts and the old. The fast come. On flounday sheeoplea
    > In wintern. Peles the site sun the river near the river and quiies the com. Tom sh
    > The library. ity teareople sum in the children the oldt quilow the roue every
    
    --- probes: what does the model believe comes next? ---
    > The library opens at the mill. The cace.
        top guesses: ' the' 0.65, ' n' 0.11, ' s' 0.03
    > The doctor of Lindale is the river. The carmall beople
        top guesses: ' the' 0.31, ' a' 0.12, ' ' 0.10
    > Captain <|unk|>orns the river. The farmall baker
        top guesses: 's' 0.15, ' the' 0.11, 'a' 0.09

    Reading the curves

    The first evaluation is 5.136, almost exactly ln 169 = 5.130: the untrained model guesses uniformly, as it should. The loss then falls fast: by step 80 the model has learned which tokens are common and which tend to follow which, and the sample at step 120 already has English-like pieces ("the", "Tom.") among invented spellings. By step 360 the training loss is 2.54 and the validation loss 3.49, a validation perplexity of about 33: from 169 equally likely choices down to the uncertainty of about 33. The final samples show what the model has learned: common words (the river, the children, the old), the names of the town's characters, capital letters and full stops, and the habit of starting a new sentence with "The" or "On". They also show what it has not learned: many words are invented blends ("flounday", "teareople"), and the sentences do not mean anything.

    The gap between the two curves is the most important thing on the chart. The training loss keeps falling, but the validation loss stops improving after about step 240. That is the start of overfitting: the model is getting better at the specific paragraphs it trains on, not at English in general. We ran the same script for longer (2,000 steps instead of 360, about two minutes; change the settings line to 8, 2000, 6e-3, 100, 1.0, 200). Switch between the two runs:

    Training and validation lossInteractive

    train lossvalidation lossln(vocab) = 5.13

    In the longer run, the training loss falls all the way to 0.30 while the validation loss climbs from 3.68 to 5.86, worse than at step 200. The model has memorised the training paragraphs: with temperature 0.8 it reproduces them almost word for word ("In winter the river is cold and grey. Sometimes the snow falls on Lindale, and the roof…"). A model with 66,000 parameters and only 4,000 training tokens has far more capacity than data, so memorisation is the easiest way to lower the training loss. The remedies are the ones from lesson 3.7: more data (by far the best), a smaller model, regularisation such as dropout or stronger weight decay, or stopping at the best validation step (early stopping), which our loop already records.

    How much compute was that, and how much does a frontier model need?

    A widely used estimate for transformer training is that each token costs about 6 floating-point operations per parameter: 2 for the forward pass and about 4 for the backward pass. For N parameters trained on D tokens:

    C≈6×N×D=6×66,000×92,160≈3.6×1010FLOPs

    In words: training compute is about six times the number of parameters times the number of tokens processed. Our run processes 360 steps × 8 windows × 32 tokens = 92,160 tokens with 66,000 parameters: about 36 billion operations, which a laptop does in seconds.

    At real scale

    Public estimates for frontier language models in general put training compute somewhere around 1024 to 1026 operations: a billion billion times more than our run, or more. Such runs use thousands to tens of thousands of GPUs or other accelerators for weeks to months, trillions of training tokens, and budgets that public estimates put in the tens to hundreds of millions of dollars. These are general public estimates, not figures for Claude: Not public Anthropic has not published Claude's parameter count, training tokens, hardware or training cost. Our model is useful for understanding the mechanism; it is in no way comparable to Claude. If you want to train or adapt real models yourself, the realistic routes are using an API, running open-weight models (for example from the Llama, Mistral, Qwen or Gemma families) locally, and fine-tuning them with LoRA or QLoRA on a single GPU, all covered in modules 10 and 11.

    What changes when training runs on thousands of accelerators

    Precision. Industry practice Large runs compute in 16-bit (bfloat16) or even 8-bit formats on tensor cores, keeping a 32-bit master copy of the weights and optimizer state. Our float64 run is about as far from this as possible, chosen for exact gradient checks rather than speed.

    Parallelism. A model too large for one device is split: data parallelism gives each device different batches and averages the gradients; tensor parallelism splits each matrix multiplication across devices; pipeline parallelism places different layers on different devices; and sharded optimizers (ZeRO/FSDP style) spread the Adam state, which alone is twice the size of the weights. Batch sizes reach millions of tokens per step, often built with gradient accumulation (several forward/backward passes before one optimizer step).

    Stability and operations. Long runs monitor the loss and gradient norm continuously, because loss spikes can appear after weeks of smooth training; teams restart from a recent checkpoint, skip bad data, or lower the learning rate. Checkpoints are saved regularly because hardware failures are routine at this scale. Hyperparameters (learning rate, batch size, warmup) are usually chosen from many small-scale experiments and scaling-law fits rather than tried at full size.

    Learning-rate schedules. Cosine decay is the classic choice; some recent public recipes use "warmup-stable-decay" schedules that hold the peak rate and decay only at the end, which makes it easier to continue training later. The underlying ideas (warm up, then decay) are the same.

    Common mistakes and debugging tips

    Watching only the training loss

    A falling training loss looks like progress even when the model is memorising (as in our 2,000-step run, where the training loss reaches 0.30 while validation gets steadily worse).

    Fix: always evaluate on held-out text at fixed intervals, plot both curves, and keep the checkpoint with the best validation loss.

    Loss becomes nan or jumps up and never recovers

    Usually the learning rate is too high for this model, there is no warmup, or clipping is missing, so one large update pushes the weights into a region where activations overflow.

    Fix: lower the peak learning rate (try halving it), add warmup, clip the gradient norm at 1.0, and log the norm every step to see the spike coming.

    Loss stuck at ln V

    If the loss does not move from about 5.13 for many steps, the weights are not changing in a useful way: gradients are not reaching them, the optimizer step is not applied, or the targets do not match the inputs.

    Fix: overfit a single batch first. Train repeatedly on one fixed batch; a correct setup drives that loss far below ln V within a few hundred steps. If it does not, the bug is in the model or the loop, not the data.

    Applying weight decay to everything

    Decaying LayerNorm gains and biases pulls them towards zero and fights normalisation, which can slow or destabilise training.

    Fix: decay only 2-D weight matrices (and usually not embeddings in very small models), as the ndim >= 2 test does.

    Key takeaways

    • Each step: learning rate from the schedule, random batch, reset gradients, forward, backward, clip, AdamW update.
    • AdamW normalises each weight's step by its gradient's typical size and adds decoupled weight decay; warmup and cosine decay control the step size over time; clipping caps bad updates.
    • Our 66,000-parameter model goes from ln V = 5.13 to a validation loss of about 3.5 in 20 seconds, then starts to overfit; trained longer it memorises the corpus.
    • Compute ≈ 6 × parameters × tokens: about 1010 operations here, versus public estimates of 1024–1026 for frontier models.

    Exercise: restore the best checkpoint

    The training loop records the best validation weights in best but then samples from the final weights. After the loop, copy the best weights back into the model and compare the validation loss and samples before and after. Then try the 2,000-step setting: how much does early stopping matter there?

    Hint

    best[2] is a dictionary from parameter name to a NumPy array. Assign model.p[k].data = w.copy() for each entry, then call estimate_loss again.

    Show a solution
    final = estimate_loss(model, BATCH, CTX)
    for k, w in best[2].items():
        model.p[k].data = w.copy()            # roll back to the best step
    restored = estimate_loss(model, BATCH, CTX)
    print(f"val loss: final {final['val']:.3f} -> best checkpoint {restored['val']:.3f} (step {best[1]})")

    In the 360-step run the difference is small (the best validation loss was 3.474 at step 240 and the final one 3.488), so samples look similar. In the 2,000-step run it is large: the best checkpoint is at step 200 with validation loss 3.68, against 5.86 at the end. The restored model writes less fluent copies of the training text but handles new text much better. Whether you prefer it depends on the goal: for a model that must generalise, always keep the best validation checkpoint.

    Check your understanding

    Why does a transformer's learning rate usually warm up from near zero?

    1. To save compute in the first steps
    2. Early gradients and Adam's running averages are unreliable, and a full-size step then can push the weights somewhere bad
    3. Because the vocabulary is not ready yet
    At the start, Adam's statistics come from very few batches and the random network's gradients are unrepresentative. Small early steps avoid an unstable start. Warmup saves no compute and has nothing to do with the vocabulary.

    Training loss keeps falling while validation loss rises. What is happening?

    1. The model is overfitting: memorising the training text instead of learning patterns that generalise
    2. The learning rate is too low
    3. The validation set is too easy
    Diverging curves are the classic sign of overfitting. A too-low learning rate makes both losses fall slowly; an easy validation set would make validation loss low, not rising.

    Using C ≈ 6ND, roughly how many operations does it take to train a 1-billion-parameter model on 20 billion tokens?

    1. 1.2 × 1012
    2. 1.2 × 1015
    3. 1.2 × 1020
    6 × 109 × 2 × 1010 = 1.2 × 1020. That is millions of times more than our run, and still several orders of magnitude below public estimates for frontier models.

    Lesson 5.7Module 5: Build a GPT-like model

    Text generation and temperature

    • ⏱ 16 min read
    • Intermediate

    Learning objectives

    • Write the autoregressive generation loop: run the model, turn the last position's logits into probabilities, pick a token, append it, repeat.
    • Compare greedy decoding with random sampling, and explain why greedy text often falls into loops.
    • Apply temperature by dividing the logits, and predict its effect on the distribution, its entropy and the generated text.
    • Explain how generation stops, and why the KV cache makes each new token cheap.

    Training gave us a model that, for any prefix, outputs a probability for every possible next token. That is all a language model ever does. Generating text is a small loop wrapped around it, and lesson 4.9 already described it in one sentence: run the model, pick a token from the last position's probabilities, append it, repeat. This lesson writes that loop properly and studies the first and most important choice inside it: how to pick the token. Lesson 2.4 introduced temperature as a way to reshape softmax; here you will use it to control a real generator.

    Analogy: a jazz musician improvising

    An improvising musician chooses one note at a time, guided by everything played so far. Always playing the single most expected note gives a safe but dull tune that soon repeats itself. Picking notes completely at random gives noise. Good improvisers sit in between: mostly the expected notes, sometimes a surprising one that still fits. Temperature is the dial between "always the expected note" and "anything goes".

    The generation loop

    Generation is autoregressive: each new token is predicted from the prompt plus all tokens generated so far, and then becomes part of the input for the next prediction. Here is the loop from train_gpt.py with its helper that computes the next-token distribution:

    def next_token_probs(model, ids, temperature=1.0, top_k=None, top_p=None):
        window = np.array([ids[-model.T:]])                    # crop to the context window
        logits, _ = model.forward(window)
        z = logits.data[0, -1].copy()                          # scores for the NEXT token only
        if temperature == 0:                                   # greedy: all mass on the best token
            p = np.zeros_like(z)
            p[int(z.argmax())] = 1.0
            return p
        z = z / temperature
        if top_k is not None:                                  # keep the k highest scores
            z[z < np.sort(z)[-top_k]] = -np.inf
        p = np.exp(z - z.max())
        p /= p.sum()
        if top_p is not None:                                  # keep the smallest set with mass >= top_p
            order = np.argsort(-p, kind="stable")
            keep = order[:int(np.searchsorted(np.cumsum(p[order]), top_p)) + 1]
            mask = np.zeros_like(p)
            mask[keep] = 1.0
            p = p * mask / (p * mask).sum()
        return p
    
    
    def generate(model, prompt, max_new, rng, **sampling):
        ids = encode(prompt)
        for _ in range(max_new):
            p = next_token_probs(model, ids, **sampling)
            nxt = int(rng.choice(len(p), p=p))
            if nxt == EOS:                                     # the model chose to end the paragraph
                break
            ids.append(nxt)
        return decode(ids)

    Four details are worth noticing. First, ids[-model.T:] crops the input to the last T = 32 tokens, because the model has learned position embeddings only for positions 0 to 31; anything older is simply forgotten. That is the context window, the same limit that, at a much larger size, decides how much of a conversation a chat model can see. Second, only logits.data[0, -1] is used: the model computes predictions at every position, but during generation only the last one is new. Third, the token is chosen with rng.choice(len(p), p=p), a weighted random draw. Fourth, the loop stops early if the model picks <|eos|>, the token it learned to place at the end of every paragraph (lesson 5.3).

    Greedy decoding versus sampling

    The simplest rule is greedy decoding: always take the most probable token. It is deterministic, which is useful for tests, but it has a well-known flaw: it falls into loops. Once the text reaches a state it has been in before, greedy decoding makes the same choices again, forever. The bigram model in the script below shows this in its purest form, "the dog . the dog . the dog …", but large models do it too, especially on long outputs: they repeat a phrase or a paragraph because each repetition makes the next one more likely.

    The alternative is sampling: draw the next token at random in proportion to its probability. If "mat" has probability 0.56 and "floor" 0.25, about 56% of runs continue with "mat" and 25% with "floor". Sampled text is more varied and more natural, but every token has a chance, including the very unlikely ones, and one bad pick can derail the rest of the text. Lesson 5.8 deals with that tail. First, the dial that controls how adventurous sampling is.

    Temperature

    Temperature divides every logit by a number T before the softmax:

    pi(T)=ezi/T∑j=1Vezj/T

    In words: divide all the scores by T, then apply the usual softmax. T = 1 leaves the model's distribution unchanged. T below 1 stretches the gaps between scores, so the favourite gets even more probability. T above 1 shrinks the gaps, flattening the distribution towards uniform. As T approaches 0 all probability goes to the top token, which is greedy decoding.

    Temperature never changes the order of the tokens; the favourite stays the favourite. It changes how much the favourite dominates. A useful number to watch is the entropy of the distribution, H=−∑ipilnpi: 0 when one token is certain, and ln V when all are equally likely. Move the slider and draw samples.

    Temperature playground: "The cat sat on the …"Interactive

    Which temperature is right depends on the task. For extracting facts, writing code or answering questions with one correct answer, low temperatures (0 to about 0.5) keep the model on its most confident path. For brainstorming, stories or varied phrasings, values around 0.7 to 1.0 give more diversity. Very high temperatures quickly produce nonsense, because the flattened distribution gives real probability to tokens the model considers wrong. Temperature 0 is often described as "deterministic", but in production systems small numerical differences between runs (batching, parallel hardware) can still occasionally change the top choice when two tokens are almost tied.

    Hosted APIs differ here, and they change over time. Many APIs and local runners (Ollama, llama.cpp and most open-weight model servers) still let you set temperature, top_k and top_p per request. The Claude API has moved away from them: on its current models and API version (as of late 2026), a request that includes these sampling parameters is rejected, and you shape the output with the prompt and other settings instead. Always check the current documentation for the model you call rather than assuming. Sampling still happens inside every model; the knobs are just not always yours to turn. You will call real APIs yourself in module 7.

    Temperature and the loop in NumPy

    The script below has two parts. Part 1 applies five temperatures to one fixed set of logits (the scores a model might give after "The cat sat on the") and draws 1,000 samples from each. Part 2 runs the full generation loop with a tiny word-bigram "model", so you can compare greedy decoding and sampling over 14 steps without waiting for a neural network.

    # @run
    # temperature.py: the generation loop and what temperature does to it.
    # Part 1 reshapes one next-token distribution; part 2 runs a full autoregressive loop
    # with a tiny word-bigram "model" so you can compare greedy decoding with sampling.
    import math
    import re
    from collections import Counter, defaultdict
    import numpy as np
    
    # ---- 1. one distribution, five temperatures
    words = ["mat", "floor", "sofa", "roof", "moon", "banana"]
    logits = np.array([3.0, 2.2, 1.6, 0.4, -0.8, -2.0])          # scores after "The cat sat on the"
    
    
    def softmax_t(z, temperature):
        if temperature == 0:                                     # the limit T -> 0: greedy
            p = np.zeros_like(z)
            p[int(np.argmax(z))] = 1.0
            return p
        z = z / temperature
        e = np.exp(z - z.max())
        return e / e.sum()
    
    
    def entropy(p):
        h = 0.0
        for q in p:
            if q > 0:
                h -= float(q) * math.log(float(q))
        return h
    
    
    rng = np.random.default_rng(0)
    print(f"{'T':>4} " + " ".join(f"{w:>7}" for w in words) + f" {'entropy':>8}  1000 draws: top word, distinct")
    for T in (0, 0.5, 1.0, 1.5, 3.0):
        p = softmax_t(logits, T)
        draws = rng.choice(len(words), size=1000, p=p)
        counts = np.bincount(draws, minlength=len(words))
        print(f"{T:>4} " + " ".join(f"{float(q):>7.3f}" for q in p)
              + f" {entropy(p):>8.3f}  {int(counts[0]):>4} x mat, {int((counts > 0).sum())} words")
    
    # ---- 2. the generation loop with a tiny bigram model
    TEXT = ("the cat sat on the mat . the cat saw the dog . the dog sat on the log . "
            "the dog ran to the river . the cat ran to the dog . a bird sat on the roof .")
    toks = re.findall(r"\S+", TEXT)
    vocab = sorted(set(toks))
    counts = defaultdict(Counter)
    for a, b in zip(toks, toks[1:]):
        counts[a][b] += 1
    
    
    def model(context):
        """Return logits over the vocabulary for the next token (this 'model' only reads the last token)."""
        c = counts[context[-1]]
        return np.array([math.log(c[w]) if c[w] else -1e9 for w in vocab])
    
    
    def generate(prompt, n, temperature, rng):
        out = prompt.split()
        for _ in range(n):
            p = softmax_t(model(out), temperature)               # 1. run the model, 2. turn scores into probabilities
            out.append(vocab[int(rng.choice(len(vocab), p=p))])  # 3. pick one token, 4. append it
        return " ".join(out)                                     # 5. repeat (the loop)
    
    
    print()
    print("greedy :", generate("the", 14, 0, np.random.default_rng(1)))
    for seed in (1, 2):
        print(f"T=1.0 #{seed}:", generate("the", 14, 1.0, np.random.default_rng(seed)))
    print("T=3.0  :", generate("the", 14, 3.0, np.random.default_rng(1)))
    1. if temperature == 0: greedy decoding as the limit of T → 0: all probability on the arg-max token. Dividing by zero is avoided by handling it separately.
    2. z = z / temperature, then the usual stable softmax: the whole of temperature sampling is this one division.
    3. entropy(p): −Σ p ln p, skipping zero probabilities (their contribution is 0).
    4. rng.choice(len(words), size=1000, p=p) and np.bincount: 1,000 weighted draws and their counts per word.
    5. model(context): the bigram "model" returns logits: the log of how often each word followed the last word in the training text, and −109 (impossible) for words that never did.
    6. generate: the loop in five steps, labelled in the comments: run the model, convert to probabilities, pick, append, repeat.
       T     mat   floor    sofa    roof    moon  banana  entropy  1000 draws: top word, distinct
       0   1.000   0.000   0.000   0.000   0.000   0.000    0.000  1000 x mat, 1 words
     0.5   0.788   0.159   0.048   0.004   0.000   0.000    0.653   793 x mat, 4 words
     1.0   0.556   0.250   0.137   0.041   0.012   0.004    1.152   578 x mat, 6 words
     1.5   0.440   0.258   0.173   0.078   0.035   0.016    1.396   454 x mat, 6 words
     3.0   0.305   0.233   0.191   0.128   0.086   0.058    1.656   305 x mat, 6 words
    
    greedy : the dog . the dog . the dog . the dog . the dog .
    T=1.0 #1: the dog sat on the dog . the dog ran to the dog . the
    T=1.0 #2: the cat ran to the dog ran to the dog ran to the dog ran
    T=3.0  : the log . a bird sat on the dog ran to the log . the

    The table shows temperature's effect numerically. At T = 0.5 "mat" gets 0.788 of the probability and only 4 different words appear in 1,000 draws; at T = 1 (the model's own distribution) it gets 0.556 and all 6 words appear; at T = 3 the distribution is nearly flat (entropy 1.656, close to the maximum ln 6 = 1.79) and even "banana" gets almost 6%. In the generation loop, greedy decoding locks into "the dog . the dog . …" after two tokens. Sampling at T = 1 produces different text for each seed, though a bigram model has so little context that sample #2 also falls into a loop by chance ("ran to the dog ran to the dog"). At T = 3 the text wanders to rarer words such as "log" and "bird".

    You can try the same on the tiny GPT: generate(model, "Tom", 30, rng, temperature=0) versus temperature=1.0. The probe lines at the end of the output in lesson 5.6 are greedy generations: notice how often they fall back to the corpus's most common phrases, such as "the river" and "the mill".

    When does generation stop, and what does each token cost?

    A generator needs a stopping rule. There are three common ones, usually combined: the model produces the end-of-sequence token (here <|eos|>; chat models have an end-of-turn token), a maximum number of new tokens is reached (max_new here, max_tokens in most APIs), or the text contains a stop sequence chosen by the caller (see lesson 1.5).

    Our loop is simple but wasteful: for every new token it runs the model over the whole window again, recomputing keys and values for tokens whose keys and values have not changed. Real inference engines keep a KV cache: the keys and values of every earlier token, for every layer and head, are stored after they are first computed, so each new token only computes its own query, key and value and attends to the cached ones. You built and verified one in the module 4 mini-project; lesson 4.9 explains why it gives exactly the same results. The first pass over the prompt (the prefill) is done in parallel; after that, generation is one token per step (decoding), and the cache grows with every token. For long contexts the KV cache becomes one of the main memory costs of serving a model, which is why techniques such as grouped-query attention exist.

    Beyond temperature: beam search, penalties and why greedy loops happen

    Why loops are self-reinforcing. Attention can copy from the context, and models learn during training that text often repeats itself (names, phrases, list formats). Once a phrase has appeared twice, the model sees the repetition in its context and predicts a third copy with even higher probability. Greedy decoding has no randomness to break out of this, so the loop is stable.

    Beam search keeps the k most probable partial sequences at each step instead of one, and returns the sequence with the highest total probability. It works well when there is one best answer, as in translation or speech recognition, but for open-ended text it tends to produce bland and repetitive output, because the most probable text overall is often generic. Chat assistants generally sample instead. Industry practice

    Repetition penalties. Some inference engines and APIs offer penalties that lower the logits of tokens that have already appeared (frequency or presence penalties, or a multiplicative repetition penalty). They reduce loops but can also block legitimate repetition, such as a variable name in code.

    Temperature and calibration. At T = 1 sampling follows the model's own beliefs. Post-trained chat models are often more confident than their base models, so the "right" temperature for one model is not right for another, and the same number can behave differently across model versions. Treat temperature as a setting to test on your own task, not a universal constant.

    Common mistakes and debugging tips

    Sampling from all positions' logits instead of the last one

    The model returns logits for every position in the window. Using position 0 (or averaging) gives the prediction for the wrong prefix, and the output looks random.

    Fix: use logits[0, -1] (batch 0, last position) during generation. Check by generating greedily from a training sentence: a trained model should continue it plausibly.

    Forgetting to crop to the context window

    With learned position embeddings, a sequence longer than the context length has no embedding for position T and the code crashes (our forward asserts on it). Models with relative positions may run but degrade badly beyond their trained length.

    Fix: always pass at most the last T tokens, as ids[-model.T:] does, and remember that the model then cannot see anything older.

    Dividing by a temperature of exactly zero

    z / 0 gives infinities and nan probabilities, and rng.choice raises an error.

    Fix: treat T = 0 as a special case meaning greedy (arg-max), as both next_token_probs and softmax_t do.

    Expecting a high temperature to make the model more creative in a useful way

    Temperature only flattens the existing distribution; it does not add new ideas. Above about 1.2, most of the extra variety is tokens the model itself considers wrong.

    Fix: for diversity, keep the temperature moderate and combine it with top-p (lesson 5.8), or change the prompt to ask for variety.

    Key takeaways

    • Generation loops: model → last-position logits → probabilities → pick → append, until an end token, a length limit or a stop sequence.
    • Greedy decoding is deterministic but loops; sampling is varied but can pick bad tail tokens.
    • Temperature divides logits by T: below 1 sharpens, above 1 flattens, 0 means greedy; the order of tokens never changes.
    • The KV cache stores earlier keys and values so that each new token costs one small step instead of a full re-run.

    Exercise: measure repetition

    Write a function distinct_2(text) that returns the fraction of distinct word pairs (bigrams) among all word pairs in a generated text: 1.0 means no pair repeats, low values mean loops. Use it on the bigram generator in temperature.py at T = 0, 0.5, 1.0 and 2.0, averaging over seeds 0 to 19 with 30 generated tokens each. Plot or print the curve. What does it suggest about choosing a temperature?

    Hint

    w = text.split(); pairs = list(zip(w, w[1:])); return len(set(pairs)) / len(pairs). Greedy decoding gives the same text for every seed.

    Show a solution
    def distinct_2(text):
        w = text.split()
        pairs = list(zip(w, w[1:]))
        return len(set(pairs)) / len(pairs)
    
    for T in (0, 0.5, 1.0, 2.0):
        scores = [distinct_2(generate("the", 30, T, np.random.default_rng(s))) for s in range(20)]
        print(f"T={T}: distinct-2 = {sum(scores) / len(scores):.2f}")

    On our machine the averages were 0.10 for greedy decoding (three pairs repeated over and over), 0.49 at T = 0.5, 0.54 at T = 1.0 and 0.55 at T = 2.0. The big jump is from greedy to any sampling at all; after that, more temperature adds little diversity. But higher diversity is not the same as better text: at T = 2 the pairs are varied partly because rare, odd continuations are picked. The usual practice is to choose the lowest temperature that avoids visible repetition for your task, and to judge quality by reading samples, not by diversity alone.

    Check your understanding

    What does setting the temperature to 0.5 do to the next-token distribution?

    1. Removes all tokens with probability below 0.5
    2. Doubles the gaps between logits, so likely tokens become even more likely
    3. Changes which token is ranked first
    Dividing logits by 0.5 multiplies them by 2, widening every gap before the softmax, so the distribution becomes sharper. It removes no tokens (that is top-k/top-p) and never changes the ranking.

    Why does greedy decoding often produce repeated phrases?

    1. The model is trained to repeat itself
    2. Greedy decoding uses a smaller context window
    3. It is deterministic: once the context makes a repetition the top choice, nothing can break the cycle, and each repetition makes the next more likely
    Greedy decoding always takes the arg-max, so a context that favours repeating leads to a repeat, which strengthens the pattern. The context window is the same; models are not trained specifically to repeat, though they do learn that text sometimes repeats.

    During generation, which logits are used to choose the next token?

    1. Those at the last position of the input
    2. The average over all positions
    3. Those at the first position
    Position t predicts token t + 1, so the last position predicts the token that comes after everything so far. Earlier positions predict tokens we already have.

    Lesson 5.8Module 5: Build a GPT-like model

    Top-k and top-p sampling

    • ⏱ 13 min read
    • Intermediate

    Learning objectives

    • Explain the "long tail" problem: why plain sampling eventually picks tokens the model itself considers wrong.
    • Implement top-k and top-p (nucleus) filtering and renormalise what is left.
    • Compare how each filter behaves when the model is confident and when it is unsure, and see why top-p adapts while top-k does not.
    • Combine temperature, top-k and top-p in the usual order, and know newer variants such as min-p.

    In lesson 5.7 you saw that sampling makes text varied but gives every token a chance, and that temperature can only sharpen or flatten the whole distribution. A real vocabulary has tens of thousands of tokens, and after any prefix most of them are nonsense. Each nonsense token has a tiny probability, but there are so many of them that together they can hold a noticeable share. Lesson 1.5 introduced the two standard fixes, top-k and top-p; this lesson implements them and shows exactly when they differ.

    Analogy: choosing a restaurant with friends

    A group picking a restaurant could list every place in the city and draw one at random, weighted by how much people like it. With hundreds of places, there is a real chance of landing somewhere nobody wanted. So groups cut the list first. One rule is "only the top 3, whatever happens" (top-k). Another is "keep adding favourites until they cover 90% of the group's enthusiasm" (top-p): if everyone loves one place, that alone may be enough; if opinions are split, the list stays long. Then you draw from the shortlist.

    The long tail

    Suppose that after some prefix the model gives the right kind of next token a total probability of 0.97, and the remaining 0.03 is spread over 50,000 tokens that do not fit at all. Any single bad token is negligible. But in a 500-token answer, sampling makes 500 draws, and the chance that none of them lands in that 3% tail is 0.97500≈2×10−7. In practice the tail mass varies from token to token, but the lesson stands: over long outputs, plain sampling almost certainly picks some tokens the model itself rated as very unlikely, and because generation is autoregressive, one bad token can derail everything after it. Holtzman et al. (2019, "The Curious Case of Neural Text Degeneration", arXiv:1904.09751) studied this and proposed nucleus sampling.

    Temperature below 1 shrinks the tail, but it also changes the balance between the good candidates, making the text more conservative everywhere. What we want is different: keep the model's relative preferences among plausible tokens, but cut off the implausible ones completely. That is what truncation sampling does.

    Top-k: keep a fixed number

    Top-k sampling keeps the k tokens with the highest probability, sets all others to zero, and renormalises the survivors so they sum to 1 again. With k = 1 it is greedy decoding; with k = V it is plain sampling. It is simple and fast, and it was used in early GPT-2 demos with k = 40. Its weakness is that k is the same at every step, whatever the model's confidence. After "The capital of France is", one token deserves almost all the probability, and k = 40 still keeps 39 unnecessary candidates. After "She painted the door", dozens of colours and adjectives are reasonable, and a small k cuts good options.

    Top-p: keep a fixed amount of probability

    Top-p sampling, also called nucleus sampling, sorts tokens from most to least likely and keeps the smallest prefix of that list whose probabilities add up to at least p:

    S=smallest set of top tokens with∑i∈Spi≥p,pi′=pi∑j∈Spjfori∈S

    In words: walk down the tokens from most to least probable, adding up their probabilities, and stop as soon as the total reaches p (for example 0.9). Keep those tokens, drop the rest, and divide the kept probabilities by their total so they sum to 1.

    Because the cut is defined by probability mass, the number of kept tokens adapts automatically. When the model is confident, a single token may already exceed p and the nucleus has size 1; when it is unsure, the nucleus contains many tokens. Typical values are p = 0.9 to 0.95. Try both filters on a confident and an unsure distribution:

    Sampling playground: temperature, top-k and top-pInteractive

    Putting the pieces together

    Most inference engines apply the steps in this order: divide the logits by the temperature, apply softmax, apply top-k, apply top-p, renormalise, draw. The order matters. Temperature changes the probabilities that top-p adds up, so a high temperature makes the nucleus larger (more tokens are needed to reach 90%), and a low temperature makes it smaller. Top-k first and top-p second means top-p works only within the k survivors. Some engines differ in details, so if exact behaviour matters, check the documentation of the one you use. Our next_token_probs in train_gpt.py follows this order (temperature, then top-k, then top-p), and the final samples in lesson 5.6 used temperature 0.8 with top-k 20.

    Common starting points are temperature around 0.7 with top-p 0.9 for chat-style text, or temperature near 0 for tasks with one right answer, where truncation hardly matters. Where an API or local runner exposes both, the usual advice is to adjust either temperature or top-p, not both at once, because their effects overlap. Some hosted APIs, including the current Claude API, no longer accept these parameters at all (see lesson 5.7), so check the documentation for the model you use.

    Top-k and top-p in NumPy

    # @run
    # topk_topp.py: top-k and top-p (nucleus) filtering, step by step.
    # Two situations: the model is confident, or the model is unsure. Watch which filter adapts.
    import numpy as np
    
    
    def softmax(z):
        e = np.exp(z - z.max())
        return e / e.sum()
    
    
    def top_k_filter(p, k):
        """Keep the k most likely tokens, renormalise."""
        keep = np.argsort(-p, kind="stable")[:k]
        q = np.zeros_like(p)
        q[keep] = p[keep]
        return q / q.sum()
    
    
    def top_p_filter(p, top_p):
        """Keep the smallest set of most likely tokens whose total probability reaches top_p."""
        order = np.argsort(-p, kind="stable")
        cum = np.cumsum(p[order])
        n_keep = int(np.searchsorted(cum, top_p)) + 1          # first position where cum >= top_p
        keep = order[:n_keep]
        q = np.zeros_like(p)
        q[keep] = p[keep]
        return q / q.sum()
    
    
    def sample(logits, rng, temperature=1.0, top_k=None, top_p=None):
        """The usual order: temperature, then top-k, then top-p, then draw."""
        p = softmax(logits / temperature)
        if top_k is not None:
            p = top_k_filter(p, top_k)
        if top_p is not None:
            p = top_p_filter(p, top_p)
        return int(rng.choice(len(p), p=p))
    
    
    def show(name, words, p):
        kept = [(w, float(q)) for w, q in zip(words, p) if q > 0]
        print(f"  {name:<11} keeps {len(kept)}: " + "  ".join(f"{w} {q:.2f}" for w, q in kept))
    
    
    cases = {
        "confident": (["Paris", "the", "a", "Lyon", "France", "Rome", "banana", "purple"],
                      np.array([6.0, 2.5, 2.0, 1.0, 0.8, 0.5, -1.0, -1.5])),    # "The capital of France is"
        "unsure": (["red", "blue", "green", "old", "small", "big", "wooden", "quiet"],
                   np.array([1.2, 1.1, 1.0, 0.9, 0.8, 0.7, 0.2, -0.5])),        # "She painted the door"
    }
    for name, (words, logits) in cases.items():
        p = softmax(logits)
        print(f"{name}: " + "  ".join(f"{w} {float(q):.2f}" for w, q in zip(words, p)))
        show("top-k k=3", words, top_k_filter(p, 3))
        show("top-p 0.9", words, top_p_filter(p, 0.9))
    
    # How often does sampling pick a token from the far tail (the last two in each list)?
    rng = np.random.default_rng(0)
    print("\ntail picks in 2000 draws (confident case):")
    words, logits = cases["confident"]
    for label, kw in (("plain T=1", {}), ("top-k 3", {"top_k": 3}), ("top-p 0.9", {"top_p": 0.9}),
                      ("T=1.5, top-p 0.9", {"temperature": 1.5, "top_p": 0.9})):
        picks = [sample(logits, rng, **kw) for _ in range(2000)]
        tail = sum(1 for i in picks if i >= 6)
        print(f"  {label:<17} tail tokens: {tail:>3}   distinct tokens used: {len(set(picks))}")
    1. keep = np.argsort(-p, kind="stable")[:k]: indices of the k largest probabilities. kind="stable" makes ties resolve the same way every time.
    2. q[keep] = p[keep]; return q / q.sum(): zero everything else and renormalise. Both filters end this way.
    3. cum = np.cumsum(p[order]): running total of the sorted probabilities.
    4. n_keep = int(np.searchsorted(cum, top_p)) + 1: searchsorted finds the first index where the running total reaches top_p; we keep everything up to and including it. This "+ 1" is the classic off-by-one: without it, the token that crosses the threshold would be dropped and, when the top token alone exceeds p, nothing would be kept.
    5. sample(...): the standard order: temperature, softmax, top-k, top-p, then one weighted draw.
    6. tail = sum(1 for i in picks if i >= 6): counts how often the two absurd candidates ("banana", "purple") are chosen in 2,000 draws.
    confident: Paris 0.94  the 0.03  a 0.02  Lyon 0.01  France 0.01  Rome 0.00  banana 0.00  purple 0.00
      top-k k=3   keeps 3: Paris 0.95  the 0.03  a 0.02
      top-p 0.9   keeps 1: Paris 1.00
    unsure: red 0.19  blue 0.17  green 0.15  old 0.14  small 0.13  big 0.11  wooden 0.07  quiet 0.03
      top-k k=3   keeps 3: red 0.37  blue 0.33  green 0.30
      top-p 0.9   keeps 7: red 0.20  blue 0.18  green 0.16  old 0.14  small 0.13  big 0.12  wooden 0.07
    
    tail picks in 2000 draws (confident case):
      plain T=1         tail tokens:   1   distinct tokens used: 7
      top-k 3           tail tokens:   0   distinct tokens used: 3
      top-p 0.9         tail tokens:   0   distinct tokens used: 1
      T=1.5, top-p 0.9  tail tokens:   0   distinct tokens used: 3

    The two cases show the difference. When the model is confident, "Paris" has 0.94: top-p 0.9 keeps only "Paris", while top-k 3 still keeps "the" and "a". When the model is unsure, the probabilities are spread out: top-k 3 keeps only red, blue and green and inflates each to over 0.3, throwing away plausible options such as "old" and "small"; top-p 0.9 keeps seven candidates and drops only the least likely one. In the 2,000-draw experiment, plain sampling picked an absurd token once, and both filters removed that risk entirely. Raising the temperature to 1.5 with top-p 0.9 widened the nucleus to three tokens, showing how the two settings interact.

    Min-p, typical sampling and constrained decoding

    Min-p sampling keeps every token whose probability is at least a fraction of the top token's probability (for example 0.1 × pmax). Like top-p it adapts to confidence, but it is defined relative to the favourite, which makes it more robust at high temperatures (Nguyen et al., 2024, arXiv:2407.01082). It is available in several open-source inference engines. Industry practice

    Typical sampling (Meister et al., 2022) keeps tokens whose surprise (−ln p) is close to the distribution's entropy, on the theory that human text is "typically" surprising rather than maximally likely. Mirostat adjusts truncation on the fly to keep the text's average surprise at a target value. Both are less common than top-p in practice.

    Constrained decoding is truncation with hard rules: at each step, tokens that would break a required format (valid JSON, a grammar, a list of allowed labels) get their probability set to zero before sampling. It is how some systems guarantee machine-readable output; tool use in module 9 relies on structured outputs. Note that none of these methods can make the model know something it does not know: they only choose among the continuations it already rates as likely, which is the topic of the next lesson.

    Common mistakes and debugging tips

    Forgetting to renormalise after filtering

    If the kept probabilities do not sum to 1, np.random.Generator.choice raises "probabilities do not sum to 1", or a hand-written sampler silently picks the last token too often.

    Fix: always divide the kept probabilities by their sum, or filter in logit space (set dropped logits to −∞) and apply softmax afterwards, which renormalises automatically.

    The top-p off-by-one

    Keeping only tokens whose cumulative probability is strictly below p drops the token that crosses the threshold. When the top token alone is above p, the kept set is empty and you divide by zero.

    Fix: always keep at least one token, and include the token at which the running total first reaches p (the + 1 in the code). Test with a distribution like [0.95, 0.05] and p = 0.9: exactly one token must survive.

    Applying top-k to unsorted or tied logits inconsistently

    A threshold such as z < np.sort(z)[-k] keeps more than k tokens when several logits tie at the threshold, and an unstable sort can give different results across runs.

    Fix: select indices with a stable sort (np.argsort(-p, kind="stable")[:k]) when the exact count matters, and test with ties.

    Key takeaways

    • Plain sampling eventually picks from the long tail of unlikely tokens, and one bad token can derail the rest.
    • Top-k keeps a fixed number of candidates; top-p keeps the smallest set covering probability p, so it adapts to the model's confidence.
    • The usual order is temperature → softmax → top-k → top-p → renormalise → draw.
    • Truncation only chooses among continuations the model already likes; it cannot add knowledge.

    Exercise: implement min-p

    Add a function min_p_filter(p, min_p) to topk_topp.py that keeps every token whose probability is at least min_p times the largest probability, then renormalises. Run it with min_p = 0.1 on both cases and compare the kept sets with top-p 0.9. Then apply temperature 2.0 before filtering and compare again.

    Hint

    One line does the selection: keep = p >= min_p * p.max(). Multiply p by this boolean mask and divide by the sum.

    Show a solution
    def min_p_filter(p, min_p):
        q = p * (p >= min_p * p.max())
        return q / q.sum()
    
    for name, (words, logits) in cases.items():
        for T in (1.0, 2.0):
            show(f"min-p T={T}", words, min_p_filter(softmax(logits / T), 0.1))

    At T = 1 the confident case keeps only "Paris" (every other token is below 0.094), exactly like top-p 0.9. The unsure case keeps all eight tokens (all are above 0.019), one more than top-p's seven. At T = 2 the confident distribution flattens: top-p 0.9 now needs five tokens (Paris, the, a, Lyon, France) to reach 90%, while min-p keeps only the three within a factor of 10 of the leader (Paris 0.76, the 0.13, a 0.10). That robustness at high temperature is min-p's main selling point.

    Check your understanding

    The probabilities are [0.6, 0.25, 0.1, 0.05]. Which tokens does top-p = 0.8 keep?

    1. Only the first
    2. The first three
    3. The first two
    Running totals are 0.6, 0.85, 0.95, 1.0. The first total to reach 0.8 is 0.85, at the second token, so the nucleus is the first two tokens. The first alone (0.6) is not enough, and the third is not needed.

    Why is top-p usually preferred over top-k?

    1. The number of kept tokens adapts to the model's confidence at each step
    2. It is faster to compute
    3. It never changes the probabilities of the kept tokens
    Top-p keeps few tokens when the model is sure and many when it is unsure; top-k keeps the same number every time. Top-p needs a sort and a cumulative sum, so it is not faster, and both filters renormalise the kept probabilities.

    A model confidently states a wrong fact (probability 0.9 on the wrong token). Will top-p = 0.9 prevent this?

    1. Yes, top-p removes wrong tokens
    2. No, top-p keeps the most likely tokens, which here includes the wrong one
    3. Only if the temperature is above 1
    Truncation removes unlikely tokens, not wrong ones. If the model is confidently wrong, the wrong token is at the top and survives every filter. A higher temperature would only make other tokens more likely at random. Lesson 5.9 looks at this problem.

    Lesson 5.9Module 5: Build a GPT-like model

    Understanding hallucinations and limitations

    • ⏱ 17 min read
    • Intermediate

    Learning objectives

    • Explain, from the training objective, why language models produce fluent but false statements (hallucinations).
    • Probe our tiny GPT and read its next-token beliefs for known facts, unknown facts and unseen characters.
    • List the structural limits of a pretrained language model: frozen knowledge, a finite context, no built-in access to sources, imperfect calibration, tokenization quirks.
    • Describe the main mitigations (retrieval, tools, post-training to abstain, verification) and which later modules cover them, and be honest about the scale gap between our model and Claude.

    You have now built every stage of a GPT-style language model and watched it learn. This last lesson looks at what it gets wrong and why. Some of its failures are just because it is tiny. Others are built into the way every language model is trained, and they survive, in milder form, all the way up to the largest systems. Module 1 promised an in-depth look at where hallucinations come from; our own model is the clearest place to see it, because you know exactly what it was trained on.

    Analogy: the confident improviser at a quiz night

    Imagine someone who has spent years learning to sound exactly like a quiz-show expert: the rhythm, the vocabulary, the confident tone. Ask them a question they know, and they answer well. Ask them one they do not know, and they still answer in the same confident style, because sounding like an expert is what they practised, not saying "I don't know". A pretrained language model is that improviser. Its training rewarded text that sounds like the training data, and confident answers are what most text contains.

    Why next-token training produces hallucinations

    Recall the objective from lesson 5.4: make the real next token as probable as possible. Nothing in that loss checks whether a sentence is true. A model learns facts only indirectly, because text that states facts is easier to predict once the facts are absorbed. That has three consequences.

    • There is always an answer. At every step the model must output a probability distribution that sums to 1 over its vocabulary. There is no special "I don't know" outcome unless training taught it to produce words that say so. Given "The doctor of Lindale is", the probability must go somewhere, and it goes to whatever continuations look like the training text.
    • Form is learned faster and better than facts. The pattern "The X of Lindale is the Y" appears many times in our corpus with different X and Y, so the model learns the shape of such sentences long before it reliably learns which Y goes with which X. Shape without content is exactly what a hallucination is.
    • Rare facts are weakly learned. A fact that appears once in the training data contributes a tiny part of the total loss. The model may half-remember it, blend it with similar facts, or attach it to the wrong subject.

    The word hallucination is used for output that is fluent and plausible but not supported by the training data, the context or reality: invented citations, wrong dates, non-existent functions in code, a confident answer to an unanswerable question. It is not lying (the model has no intent), and it is not random noise: it is the model doing exactly what it was trained to do, producing likely-looking text, in a situation where likely-looking and true have come apart.

    Probing our tiny GPT

    At the end of training, train_gpt.py asks the model three questions and prints its greedy continuation together with its top three guesses for the very next token. The corpus says the library "opens at nine". It never mentions a doctor. And it contains no capital "Z", so "Captain Zorn" includes a character our vocabulary maps to <|unk|>.

    --- probes: what does the model believe comes next? ---
    > The library opens at the mill. The cace.
        top guesses: ' the' 0.65, ' n' 0.11, ' s' 0.03
    > The doctor of Lindale is the river. The carmall beople
        top guesses: ' the' 0.31, ' a' 0.12, ' ' 0.10
    > Captain <|unk|>orns the river. The farmall baker
        top guesses: 's' 0.15, ' the' 0.11, 'a' 0.09

    Each line tells a story.

    • "The library opens at": the right continuation starts with ␣n (for "nine"), and the model gives it 0.11. But it gives 0.65 to ␣the, because "at the …" is far more common in the corpus than "at nine". Greedy decoding therefore says the library "opens at the mill", which is fluent, grammatical and false. The fact is in the training data; the model has not learned it strongly enough to beat a common pattern.
    • "The doctor of Lindale is": there is no right answer, because the corpus has no doctor. The model is not confused or hesitant in any visible way: it continues with "the river." The probability simply goes to the most typical continuation of "… is".
    • "Captain Zorn": the "Z" became <|unk|> before the model even saw it (our simplification from lesson 5.2), so the model is continuing "Captain ?orn" and produces "orns the river". Information lost by the tokenizer cannot be recovered by the model.

    Training longer changes the picture in an instructive way. In the 2,000-step run from lesson 5.6, which memorised the corpus, the probes gave:

    PromptGreedy continuation (2,000 steps)Top next-token guessesVerdict
    The library opens atnine and closes at fi…␣n 0.98, ␣s 0.01, ␣the 0.01Correct, memorised
    The doctor of Lindale issoft and white. The c…␣s 0.80, ␣m 0.12, e 0.02Confident fabrication
    Captain Zorn<|unk|>ornings. The fles the river…ing 0.73, ␣by 0.12, , 0.06Garbled

    The memorised fact is now right, with probability 0.98. But look at the doctor: "soft and white" comes from the corpus sentence "The cheese from Lindale is soft and white". The model has stitched the end of a real sentence onto a subject that never appeared, and it is more confident (0.80) than the short run was about anything. Memorising more of the training text did not teach the model when it does not know something; it gave it more fragments to recombine. This is a toy version of a real phenomenon: large models can attach real-sounding details (a real journal, a plausible author, a believable year) to a citation that does not exist.

    Use the demo to see why sampling does not rescue the situation: ask the same question many times and count the answers.

    Ask the tiny GPT the same question 20 timesInteractive

    Probabilities are the model's top three next-token guesses from the runs above; "other" is everything else (169 − 3 tokens). Green marks the start of the true answer, where one exists. The temperature slider treats "other" as one block, a simplification.

    The structural limits of a language model

    Hallucination is the most visible limit, but not the only one. These follow from what a pretrained model is, at any size:

    LimitWhere it comes fromIn our tiny GPT
    Frozen knowledgeWeights stop changing after training; anything after the training data was collected is unknown (the knowledge cutoff).It knows only the 35 paragraphs about Lindale.
    Finite contextThe model attends only to the tokens in its context window; older text is invisible.32 tokens, about 65 characters.
    No access to sourcesThe model generates from its weights; it cannot look anything up or say where a fact came from unless the source is placed in its context.It cannot "check" the corpus, only recall it imperfectly.
    Imperfect calibrationProbabilities reflect patterns in text, not verified truth; confident and correct are different things.0.80 on a fabricated doctor.
    Tokenization effectsThe model sees tokens, not letters, so tasks such as counting letters or reversing words are harder than they look."Z" is invisible; "river" is split into pieces.
    Sampling randomnessEach answer is one draw from a distribution; the same question can get different answers.Try the demo above.

    What reduces hallucinations

    No published method eliminates hallucinations, but several reduce them a great deal, and the rest of this course covers them:

    • Put the facts in the context. If the relevant document is in the prompt, the model can copy from it instead of recalling from its weights. This is retrieval-augmented generation (RAG), built in lesson 8.5, with source citations in lesson 8.8.
    • Give the model tools. A calculator, a search engine or a database query returns verified results that the model then reports (module 9).
    • Post-training for honesty. Fine-tuning and reinforcement learning can teach a model to say when it is unsure, to decline unanswerable questions and to separate what it knows from what it guesses. Anthropic has published research on training helpful, honest and harmless assistants with human and AI feedback (Bai et al., 2022), and its published constitution for Claude includes honesty principles. Module 6 covers these methods; Public the general approaches are published, while Not public the exact data and recipes used for current Claude models are not.
    • Decoding choices. Lower temperature and top-p (lessons 5.7 and 5.8) reduce random derailments, but, as the quiz in 5.8 showed, they cannot fix a model that is confidently wrong.
    • Verification by the application. Check generated code by running tests, check citations against the source, ask for quotes, and design products so that a human reviews important outputs. Lesson 10.8 covers evaluation.

    Keep the scale gap in mind

    Our model has 66,000 parameters, a vocabulary of 169 tokens, a context of 32 tokens, and was trained on 4,000 tokens for 20 seconds on one CPU. Claude is a transformer-based model trained and post-trained by Anthropic at a scale that is many orders of magnitude larger, with a context window of hundreds of thousands of tokens (some models offer more; check the current documentation). Its parameter count, data and training details are not public. The mechanisms you built here (tokens, next-token prediction, attention, sampling) are the publicly described foundation of models like Claude, and the reasons for hallucination are shared; the quality, knowledge and reliability are not remotely comparable. Do not draw conclusions about Claude's behaviour from our toy beyond those principles.

    Calibration, knowing what you know, and interpretability

    Calibration. A model is calibrated if, among all answers it gives with 70% confidence, about 70% are right. Research on pretrained language models (for example Kadavath et al., 2022, "Language Models (Mostly) Know What They Know", an Anthropic paper, arXiv:2207.05221) found that large pretrained models are often reasonably calibrated on multiple-choice questions and can be trained to predict whether they know an answer. That suggests hallucination is partly a problem of using internal uncertainty, not only of lacking it, which is what post-training for honesty tries to address. The same paper and others note that calibration can change after fine-tuning for chat, so a model's expressed confidence should not be taken at face value.

    Why bigger helps but does not solve it. Larger models trained on more data memorise more facts and learn better when a question is unanswerable, so they hallucinate less on common knowledge. But the long tail of rare facts is effectively endless, and the training objective still rewards plausible text, so errors move to rarer topics rather than disappearing.

    Interpretability. Anthropic has published interpretability research that looks for internal features in language models, including features related to recognising known versus unknown entities. This line of work aims to understand, mechanistically, when and why a model produces an answer it does not know. It is an active research area, and the findings are about specific studied models, not guarantees about any product. Public research

    Common mistakes and debugging tips

    Treating a confident tone (or a high probability) as evidence of truth

    Our model put 0.80 on a fabricated continuation. Fluency and confidence come from the training objective, not from checking facts.

    Fix: verify claims that matter against a source, and design applications to show sources (RAG with citations) rather than relying on the model's confidence.

    Testing only questions the training data answers

    A model evaluated only on facts it has seen looks reliable. The failures appear on unanswerable or out-of-distribution questions, like our doctor.

    Fix: always include probes with no correct answer, questions about events after the training data, and inputs with unusual characters, and check that the system declines or says it is unsure.

    Expecting decoding settings to fix hallucinations

    Temperature 0 makes the model repeat its single most likely answer; if that answer is wrong, it is wrong every time.

    Fix: use decoding settings to control randomness, and grounding (context, tools, verification) to control truth.

    Key takeaways

    • The next-token objective rewards likely text, not true text; a model must always put its probability somewhere, so it produces a plausible answer even when it has none.
    • Our tiny GPT shows it directly: a common pattern beats a weakly learned fact, an unknown subject gets a fluent invented answer, and memorisation makes fabrications more confident, not less.
    • Other built-in limits: frozen knowledge, a finite context, no access to sources, imperfect calibration, tokenization effects and sampling randomness.
    • Retrieval, tools, post-training for honesty and verification reduce hallucinations; none removes them, and our toy is in no way comparable to Claude in scale or quality.

    Exercise: design a hallucination test set

    Write ten probe prompts for the tiny GPT in three groups: (a) four facts stated clearly in corpus.txt, (b) three questions about things that do not exist in Lindale, (c) three prompts with characters outside the vocabulary. For each group, say what an ideal model would do, predict what our model will do, and explain how you would score the results automatically.

    Hint

    For group (a), a good automatic score is the probability the model gives to the first token of the true answer, which you can read with next_token_probs. For group (b) there is no true answer: ask what the model should have done, and whether a 66,000-parameter model trained only on next-token prediction could ever do it.

    Show a solution

    (a) Facts: "The bakery opens at" (six), "Tom has a small" (blue boat), "The teacher is" (Mr Hale), "The bus to the city leaves at" (seven; this paragraph is in the validation part, so the model never trained on it, a useful extra test). Ideal: the true continuation. Score: the probability of the true first token, and whether greedy decoding produces it. Prediction: the short run gets some of the training-set facts partly right and the validation fact wrong; the long run gets the training facts right with high probability and the validation fact wrong, with confidence.

    (b) Non-existent things: "The doctor of Lindale is", "The castle on the hill has", "Mira's brother is called". Ideal: say there is no such thing in Lindale. Our model cannot: it was never shown text that declines a question, so it will invent. Score: you cannot score by a correct token; instead, measure confidence (the top probability, or the entropy) and check whether it is lower than on group (a). Often it is not, which is the point.

    (c) Unknown characters: "Zara sells", "Café Lindale is", "The 😀 cat". Ideal: handle the characters exactly. Ours maps them to <|unk|>. Score: check whether the decoded prompt still matches the input (it will not), which tests the tokenizer rather than the model. Real byte-level tokenizers pass this test, as lesson 5.1 showed.

    Mini-project: train and audit your own tiny GPT

    Put the whole module together on text you choose: train a tiny GPT on it, generate with different sampling settings, and write a short, honest audit of what it learned and where it makes things up.

    1. Pick 10 to 50 KB of plain text you are allowed to use (your own notes, a public-domain book from a source such as Project Gutenberg, or the documentation of a project you know). Save it as corpus.txt next to a copy of train_gpt.py, with paragraphs separated by blank lines.
    2. Run vocab.py-style measurements on it (lesson 5.2) and choose N_MERGES. Write down the vocabulary size, the characters per token and how many characters fall back to <|unk|>.
    3. Train with the default settings. Then train longer (for example 1,500 steps) and record the step with the best validation loss. Restore the best checkpoint before sampling (the exercise in lesson 5.6).
    4. Add a top_p option to the final samples and generate from the same three prompts with (temperature 0), (0.8, top-k 20) and (0.8, top-p 0.9). Note which settings loop, which derail and which read best.
    5. Write ten probes as in the exercise above (facts from training text, facts from validation text, non-existent things). For each, record the greedy continuation, the probability of the true first token (if one exists) and the top probability.
    6. Write a half-page audit: what the model learned (spelling, words, names, phrases), where it overfits, three example hallucinations and why each happened, and one sentence on why none of this tells you how a production model like Claude behaves beyond the shared principles.
    Hints / reference solution

    Keep it fast. Training time grows with batch × context × width², so if your text is larger, keep D_MODEL = 48 and CTX = 32 and only increase STEPS. On a typical laptop each 100 steps takes a few seconds.

    Top-p in the samples. next_token_probs already supports it: call generate(model, prompt, 40, np.random.default_rng(3), temperature=0.8, top_p=0.9).

    Probability of the true answer:

    def p_true(prompt, answer):
        """Probability the model gives to the first token of `answer` after `prompt`."""
        p = next_token_probs(model, encode(prompt))
        first = encode(prompt + answer)[len(encode(prompt))]
        return float(p[first]), decode([first])
    
    for prompt, answer in [("The bakery opens at", " six"), ("Tom has a small", " blue")]:
        prob, tok = p_true(prompt, answer)
        print(f"{prompt!r}: P({tok!r}) = {prob:.2f}")

    Encoding prompt + answer and taking the first new token handles the fact that the answer's first token usually includes its leading space. (If the prompt's last chunk merges differently once the answer is added, the token boundary can shift; print tok to make sure it is the piece you expect.)

    What a good audit looks like. Typical findings: the model learns frequent words, names and sentence shapes within a few hundred steps; validation loss bottoms out early and then rises as it memorises; greedy decoding loops on the corpus's most common phrase; facts that appear once are rarely retrieved, while the long run reproduces training sentences verbatim; questions about non-existent things get fluent answers stitched together from real sentences, often with high probability. The honest conclusion is that the model is a compressed, error-prone echo of its training text, which is the right mental starting point for understanding what post-training (module 6), retrieval (module 8) and tools (module 9) add.

    Check your understanding

    Why does a pretrained language model answer "The doctor of Lindale is…" even though its training data mentions no doctor?

    1. It has a bug in its attention mask
    2. It must output a probability distribution over next tokens, and nothing in next-token training taught it to decline, so it continues with likely-looking text
    3. Temperature was set too high
    The objective rewards plausible continuations; there is no built-in "I don't know" outcome. The mask is fine (we tested causality), and the greedy probe used temperature 0.

    After training for 2,000 steps, our model fabricates the doctor answer with probability 0.80, more confidently than the 360-step model. What does that show?

    1. Longer training always reduces hallucinations
    2. The model has learned that Lindale has a doctor
    3. Memorising more training text gives the model more fragments to recombine; it does not teach it to recognise what it does not know
    The continuation "soft and white" is copied from a sentence about cheese. Memorisation increased confidence without adding knowledge about doctors. Training longer helped on a fact it had seen (the library) but not on the unanswerable question.

    Which approach most directly lets a model answer questions about a document it was never trained on?

    1. Retrieval: put the relevant text into the model's context (RAG)
    2. Lowering the temperature to 0
    3. Using top-k sampling with k = 1
    A model can only use information that is in its weights or in its context. Retrieval puts the document in the context. Temperature 0 and top-k = 1 are both greedy decoding: they only choose among what the model already believes.