Module 4 of 129 lessons

Understanding Transformers

The architecture behind every modern LLM, taken apart piece by piece, with attention you can poke at and a working transformer block in NumPy.

Course contents · Module 4 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 4.1Module 4: Understanding transformers

Why traditional RNNs have limitations

  • ⏱ 16 min read
  • Intermediate

Learning objectives

  • Explain how a recurrent neural network (RNN) reads a sequence one token at a time through a single hidden state.
  • Describe the three problems that limited RNNs: the fixed-size memory bottleneck, vanishing and exploding gradients, and sequential computation.
  • Measure gradient decay in a real (tiny) RNN with NumPy and read the numbers.
  • Say what LSTMs, gradient clipping and early attention fixed, and why transformers replaced recurrence for large language models.

Every large language model you will meet in this course, Claude included, is built on the transformer. To understand why that design won, it helps to look at what came before it. From roughly 2014 to 2017 the best systems for translation, speech and text generation were recurrent neural networks (RNNs), and especially their improved cousin, the LSTM. They worked, sometimes impressively, but they hit walls that more data and bigger computers could not get past. The transformer was designed to knock down exactly those walls, so knowing them makes every later lesson in this module easier to follow.

Analogy: reading a book through a sticky note

Imagine reading a novel one word at a time, and after every word you may only keep one sticky note of notes. Each new word, you rewrite the note from the old note plus the new word, then throw the old one away. By chapter ten, what is left of chapter one? Only what survived dozens of rewrites. An RNN reads exactly like this: its "sticky note" is the hidden state. A transformer, by contrast, keeps the whole book open on the desk and can glance back at any page whenever it needs to.

How an RNN reads text

An RNN processes a sequence of token vectors x1,x2,… in order. It keeps a vector called the hidden state, ht, that is meant to summarise everything read so far. At every step it does the same small calculation: mix the previous summary with the new input, squash the result, and that becomes the new summary. The same weights are reused at every step, which is why it is called recurrent.

In words first: "new memory = squash(old memory transformed by one matrix + new word transformed by another matrix)". Written as an equation:

ht=tanh(Whhht−1+Wxhxt+b)

In words: the hidden state at step t is the hyperbolic tangent (a squashing function that keeps values between −1 and 1) of the previous hidden state times a square matrix, plus the current input times another matrix, plus a bias. The output at each step is usually read off ht with one more matrix.

For a language model, the output at step t is a guess at the next token. Reading "The cat sat", the RNN computes h1 from "The", then h2 from h1 and "cat", then h3 from h2 and "sat", and from h3 predicts what comes next. The figure contrasts this chain with the attention picture you will build later in the module.

RNN: information travels along a chain h₁ h₂ h₃ h₄ "The" "cat" "sat" "down" "The" reaches h₄ only after 3 rewrites of the memory Attention: every token can look straight back "The" "cat" "sat" "down"
Chain versus direct links. In an RNN the first word influences the fourth only through every hidden state in between. With attention (lessons 4.5 and 4.6) any token reads any earlier token in one step, so the "distance" between any two words is always one.

Problem 1: everything must fit in one vector

The hidden state has a fixed size, for example 512 or 1,024 numbers. Whether the input is 5 tokens or 5,000, everything the network wants to remember has to be packed into that same vector, and every new token partly overwrites it. Early neural translation systems made this painfully visible: they read the whole source sentence into one final hidden state and then generated the translation from that single vector. Quality dropped sharply on long sentences, because one vector cannot hold every detail of 50 words.

This is the information bottleneck. Think about what a language model really needs. To continue "The keys that I left on the kitchen table next to the old radio are…", it must remember that the subject, "keys", was plural, many words ago. To answer a question about a document, it may need a detail from the first page. An RNN can learn to keep important facts in its memory, but it has to decide at reading time what to keep, before it knows what will be asked. A transformer postpones that decision: every token's representation stays available, and later tokens choose what to look at when they need it.

Problem 2: vanishing and exploding gradients

The second wall is about training. In module 3 you saw that a network learns by backpropagation: the error signal (the gradient) flows backwards through every operation, and the chain rule multiplies together the local slopes along the way. In an RNN, the path from the loss at step 60 back to the hidden state at step 1 passes through 59 copies of the same recurrent step. So the gradient gets multiplied by roughly the same factor 59 times.

Multiply any number by itself many times and it either shrinks towards zero or blows up: 0.950≈0.005, while 1.150≈117. Only a factor of exactly 1 is stable, and a network cannot hold that balance across all directions while also learning useful things. With matrices the "factor" is the matrix of local derivatives, the Jacobian, and the result is the same:

∂hT∂hT−k=∏t=T−k+1Tdiag(tanh′(zt))Whh

In words: how much the hidden state k steps ago affects the current one is a product of k matrices, one per step. Each is the recurrent matrix scaled by the slope of tanh at that step (a number between 0 and 1). A product of many such matrices usually shrinks to almost nothing (vanishing) or grows enormously (exploding).

Vanishing gradients mean the network barely learns long-range connections: the signal saying "you should have remembered that the subject was plural" arrives at the early steps a million times weaker than the signal from nearby words, so the weights mostly learn short patterns. Exploding gradients are the opposite: a few huge updates knock the weights into nonsense and the loss shows sudden spikes or becomes NaN. Explosion is easy to patch with gradient clipping (cap the gradient's size before each update), and clipping is still used in transformer training today. Vanishing is harder, because there is nothing to clip; the information is simply gone.

Try the idealised version yourself. Each step multiplies the gradient by the same factor; the bars show how much signal is left for a token k steps back, on a logarithmic scale.

Gradient through timeInteractive

k = 1 (recent)far back

This demo is a deliberate simplification: one number per step instead of a matrix. The next code measures the real thing.

Problem 3: one step at a time is slow

The third wall is speed. To compute h100 you must first compute h99, which needs h98, and so on. During training you already know the whole sentence, yet the RNN still has to walk through it in 100 dependent steps. GPUs and other accelerators are fast because they do thousands of independent multiplications at once; a long chain of dependent steps leaves most of the chip idle. You can batch many sentences side by side, but within a sentence the work stays serial.

A transformer computes the representations of all positions in a layer at once with a few large matrix multiplications. That single property is a big part of why it became practical to train models on trillions of tokens: the hardware can be kept busy. (Generation is still one token at a time for both designs, because each new token depends on the previous one; lesson 4.9 shows the KV cache trick that makes that step cheap for transformers.)

What was tried before transformers

  • LSTM and GRU cells. The Long Short-Term Memory cell (Hochreiter and Schmidhuber, 1997) adds a separate "cell state" that is updated mostly by adding to it, controlled by learned gates that decide what to forget, what to write and what to read. Addition passes gradients through almost unchanged, so LSTMs remember across hundreds of steps instead of tens. The GRU is a simpler variant. They were the workhorses of 2014–2017.
  • Gradient clipping for explosions, and careful initialisation of the recurrent matrix.
  • Attention on top of RNNs. Bahdanau, Cho and Bengio (2014) let the translation decoder look back at all encoder hidden states and take a weighted average of them, instead of relying on one final vector. This removed the bottleneck and improved long sentences dramatically. It is the direct ancestor of self-attention.
  • Attention without recurrence. The 2017 paper "Attention Is All You Need" (Vaswani et al.) asked: if attention does the heavy lifting, why keep the slow recurrent chain at all? The result was the transformer, the subject of the next lesson.

Measure it: gradients in a real RNN

The script builds a small RNN with 32 hidden units, runs 60 random input vectors through it, and then computes the exact Jacobian product from the equation above for 1, 5, 10, 20, 40 and 59 steps back. It does this for four settings: with and without the tanh, and with the recurrent matrix scaled so that its largest eigenvalue magnitude (its spectral radius) is below or above 1. Finally it changes only the very first input and checks how much the hidden state still differs later on.

# @run
# How the gradient flowing back through a vanilla RNN shrinks (or grows) with every time step.
# Lesson 4.1 of "How to Build Claude from Scratch". Needs only NumPy.
import numpy as np

rng = np.random.default_rng(0)
H, X, T = 32, 8, 60                     # hidden size, input size, sequence length


def make_rnn(radius):
    """Random RNN weights; W_hh is rescaled so its largest |eigenvalue| equals `radius`."""
    W_hh = rng.normal(0, 1, (H, H))
    W_hh *= radius / np.max(np.abs(np.linalg.eigvals(W_hh)))
    W_xh = rng.normal(0, 0.5, (H, X))
    return W_hh, W_xh


def run_rnn(W_hh, W_xh, xs, act):
    """Forward pass. Returns the hidden states and the pre-activations."""
    h = np.zeros(H)
    hs, zs = [], []
    for x in xs:
        z = W_hh @ h + W_xh @ x         # mix the old memory with the new input
        h = np.tanh(z) if act == "tanh" else z
        hs.append(h)
        zs.append(z)
    return hs, zs


def grad_norms(W_hh, zs, act):
    """Norm of d h_T / d h_{T-k} for k = 0..T-1 (chain rule, one Jacobian per step)."""
    J = np.eye(H)                       # d h_T / d h_T
    norms = [1.0]
    for z in reversed(zs[1:]):          # walk backwards in time
        d_act = 1 - np.tanh(z) ** 2 if act == "tanh" else np.ones(H)
        J = J @ (d_act[:, None] * W_hh) # d h_t / d h_{t-1} = diag(act'(z_t)) @ W_hh
        norms.append(float(np.linalg.norm(J, 2)))
    return norms


xs = rng.normal(0, 1, (T, X))
steps = [1, 5, 10, 20, 40, 59]
print("gradient norm ||d h_60 / d h_(60-k)||  (H = 32 hidden units)")
print(f"{'setting':<22}" + "".join(f"{'k=' + str(k):>11}" for k in steps))
for act, radius in [("tanh", 0.9), ("tanh", 1.5), ("linear", 0.9), ("linear", 1.1)]:
    W_hh, W_xh = make_rnn(radius)
    hs, zs = run_rnn(W_hh, W_xh, xs, act)
    n = grad_norms(W_hh, zs, act)
    label = f"{act}, radius {radius}"
    print(f"{label:<22}" + "".join(f"{n[k]:>11.2e}" for k in steps))

# Information bottleneck: everything the RNN knows about the first word must survive in one vector.
W_hh, W_xh = make_rnn(0.9)
xs2 = xs.copy()
xs2[0] += 3.0                           # change only the very first input
h_a = run_rnn(W_hh, W_xh, xs, "tanh")[0]
h_b = run_rnn(W_hh, W_xh, xs2, "tanh")[0]
print("\neffect of changing token 1 on the hidden state at step t")
for t in [1, 5, 10, 20, 30]:
    print(f"  t={t:>2}: ||h_a - h_b|| = {float(np.linalg.norm(h_a[t - 1] - h_b[t - 1])):.2e}")

The important lines:

  1. W_hh *= radius / np.max(np.abs(np.linalg.eigvals(W_hh))): rescales the random recurrent matrix so its spectral radius is exactly radius. The spectral radius decides whether repeated multiplication shrinks or grows in the long run.
  2. z = W_hh @ h + W_xh @ x: the RNN step, mixing old memory with the new input. With act == "tanh" the result is squashed.
  3. J = np.eye(H): starts the chain rule at "the last hidden state with respect to itself", the identity matrix.
  4. d_act = 1 - np.tanh(z) ** 2: the slope of tanh at each unit, always between 0 and 1. Saturated units (large |z|) have a slope near 0 and block the gradient.
  5. J = J @ (d_act[:, None] * W_hh): multiplies in one more step's Jacobian, diag(tanh'(z)) @ W_hh, walking backwards in time.
  6. np.linalg.norm(J, 2): the largest amount the product can stretch any vector: a single number for "how strong is the gradient path k steps back".
  7. xs2[0] += 3.0: the bottleneck experiment. Change only token 1, run both sequences, and compare hidden states at later steps.
gradient norm ||d h_60 / d h_(60-k)||  (H = 32 hidden units)
setting                       k=1        k=5       k=10       k=20       k=40       k=59
tanh, radius 0.9         9.24e-01   7.05e-02   1.38e-03   1.21e-06   4.03e-14   4.90e-21
tanh, radius 1.5         1.62e+00   1.19e+00   1.93e-01   2.63e-02   5.49e-05   5.39e-08
linear, radius 0.9       1.64e+00   1.31e+00   8.43e-01   2.15e-01   2.78e-02   3.46e-03
linear, radius 1.1       1.90e+00   3.15e+00   3.99e+00   1.07e+01   6.94e+01   4.09e+02

effect of changing token 1 on the hidden state at step t
  t= 1: ||h_a - h_b|| = 4.18e+00
  t= 5: ||h_a - h_b|| = 2.88e-01
  t=10: ||h_a - h_b|| = 1.76e-02
  t=20: ||h_a - h_b|| = 1.71e-05
  t=30: ||h_a - h_b|| = 1.49e-08

Read the table row by row. With tanh and radius 0.9, the gradient from 59 steps back is about 5e-21: for learning purposes, token 1 does not exist. Even with radius 1.5, the tanh saturates and the signal still decays to about 5e-08. Without the squashing (the linear rows), radius 1.1 explodes to over 400. Notice also that the linear radius-0.9 row starts above 1: a non-symmetric matrix can stretch vectors for a while before the eigenvalues win, a reminder that "factor per step" in the demo is only an approximation. The last block shows the forward-pass version of the same problem: a big change to the first input has faded to 1.5e-08 by step 30.

Why LSTMs and residual connections share one idea

An LSTM's cell state is updated as ct=ft⊙ct−1+it⊙c~t, where ft is the forget gate. The derivative of ct with respect to ct−1 is (mostly) just the gate value. If the network learns gates near 1, the gradient passes through many steps almost untouched. There is no repeated matrix multiplication on that path.

Transformers use the same trick in depth rather than time: each layer computes x+f(x), so the derivative contains an identity term and gradients always have a direct route (lesson 4.8). In both cases the lesson is: add to a stream of information instead of repeatedly transforming it.

Two more technical points. First, the bound that matters is the product of Jacobians, not the eigenvalues of Whh alone; non-normal matrices can amplify transiently, which is what the linear radius-0.9 row shows. Pascanu, Mikolov and Bengio (2013) analysed these conditions and popularised clipping by norm. Second, recurrence is not dead: research architectures such as state-space models and linear-attention RNNs revisit it with designs that can be trained in parallel and run in constant memory per token. They are an active research area Industry practice, but the dominant public LLM architecture remains the transformer, and Anthropic has publicly described Claude as transformer-based.

Attention has its own cost, which you should keep in mind: comparing every token with every other token takes time and memory proportional to the square of the sequence length. Long-context models rely on engineering such as fused attention kernels and KV caches to make that affordable. Exactly how any particular frontier model does this is mostly not public.

Common mistakes and debugging tips

Thinking "vanishing gradient" means the loss is zero

The loss can be large while the gradient for long-range connections is tiny. The model trains fine on short patterns and quietly fails on long ones, so the overall loss curve may look healthy.

Fix: test long-range behaviour directly (for example, subject-verb agreement across a long clause, or copying a token from far back) instead of trusting the average loss.

Fixing exploding gradients with a smaller learning rate only

A lower learning rate makes every update smaller, so normal training also slows down, and a single huge gradient can still wreck the weights.

Fix: clip the gradient norm (a cap such as 1.0 is common) and keep a sensible learning rate. Log the gradient norm every step; spikes are an early warning.

Assuming the spectral radius tells the whole story

As the output shows, a matrix with radius 0.9 can still stretch vectors for several steps, and tanh slopes change the picture again.

Fix: measure the actual Jacobian product (as the script does) or the gradient norms during training, rather than reasoning from eigenvalues alone.

Key takeaways

  • An RNN squeezes everything it has read into one fixed-size hidden state that is rewritten at every token.
  • Backpropagation through time multiplies many Jacobians, so long-range gradients vanish or explode.
  • Recurrence forces sequential computation, which wastes parallel hardware during training.
  • LSTMs, clipping and attention-over-RNNs helped; the transformer dropped recurrence and kept attention.

Exercise: find the edge of stability

Copy rnn_gradients.py and add the rows ("tanh", 1.0), ("tanh", 3.0) and ("linear", 1.0) to the list of settings. Before running, predict for each row whether the gradient 59 steps back will be larger or smaller than for ("tanh", 1.5). Then run it and explain any surprise in one or two sentences.

Hint

A larger radius makes Whh stretch more, but it also pushes the pre-activations z to larger values, where tanh is flatter and its slope 1 - tanh(z)² is smaller. Which effect wins? Do not trust your intuition: run it.

Show a solution

Change the loop header to for act, radius in [("tanh", 0.9), ("tanh", 1.0), ("tanh", 1.5), ("tanh", 3.0), ("linear", 0.9), ("linear", 1.0), ("linear", 1.1)]:. Each setting draws new random weights from the shared generator, so rows after the first change slightly. On our machine the k = 59 column read:

Settingk = 59What happened
tanh, 1.04.8e-18Still vanishes: the tanh slopes (all below 1) pull a "neutral" matrix below 1.
tanh, 1.52.5e-08Vanishes more slowly.
tanh, 3.03.3e+03Explodes, even with the squashing function.
linear, 1.02.7e+00Roughly stable: the only setting that neither vanishes nor explodes.

The lesson: tanh makes the effective factor per step smaller than the matrix alone, so a radius of 1 is not enough to keep the gradient alive, while a large enough radius overpowers the saturation and explodes. Stability sits on a narrow ridge that depends on the data flowing through the network, and a plain RNN cannot learn useful behaviour while staying on it. That is why gating (LSTM) and later attention were needed.

Check your understanding

Why does a plain RNN struggle to learn that a word 50 tokens back matters?

  1. It has no weights connecting distant tokens at all
  2. Its vocabulary is too small
  3. The gradient to that word is a product of about 50 Jacobians and usually shrinks to almost nothing
The connection exists, through the chain of hidden states, but the learning signal along it is a long product that vanishes (or explodes). Vocabulary size is unrelated.

Which problem does gradient clipping solve?

  1. Exploding gradients
  2. Vanishing gradients
  3. The fixed-size hidden state
Clipping caps the size of a too-large gradient. It cannot recover a gradient that has already shrunk to almost zero, and it does nothing about the memory bottleneck.

Why do transformers train faster than RNNs on parallel hardware?

  1. They have fewer parameters
  2. All positions in a layer are computed at once instead of in a chain of dependent steps
  3. They do not use backpropagation
Removing recurrence removes the step-by-step dependency during training, so large matrix multiplications keep the accelerator busy. Transformers are trained with backpropagation, and they are often larger, not smaller.

Lesson 4.2Module 4: Understanding transformers

The transformer architecture

  • ⏱ 14 min read
  • Intermediate

Learning objectives

  • Trace a sequence of tokens through a decoder-only transformer, from token ids to next-token probabilities.
  • Name the parts of a transformer block (LayerNorm, multi-head attention, feed-forward network, residual connections) and what each one is for.
  • Tell apart encoder-only, encoder-decoder and decoder-only transformers, and say which one modern chat LLMs generally use.
  • Follow the tensor shapes and count the parameters of a model from its configuration.

In lesson 4.1 we saw why recurrence held language models back. This lesson gives you the map of what replaced it. We stay at the level of boxes and arrows and tensor shapes; each box gets its own lesson afterwards, and in lesson 4.9 you assemble all of them into working NumPy code. If you only remember one picture from this module, make it the stack below.

Analogy: a meeting with a shared notebook

Picture a row of people, one per word of the sentence, each holding a notebook page about their own word. The meeting runs in rounds. In each round, everyone first listens: each person asks a question, looks around the room, and copies useful notes from whoever answers best (that is attention). Then everyone thinks alone for a moment, turning what they now know into new notes (that is the feed-forward network). Nobody erases their page; they only add to it (the residual connection). After a few dozen rounds, the last person's page holds enough to guess the next word. A transformer is that meeting, made of matrix multiplications.

The big picture: tokens in, probabilities out

A language model is a function. Its input is a list of token ids (integers from the tokenizer, lesson 4.3). Its output, for every position in the list, is a vector of scores over the whole vocabulary, one score per possible next token. Turning those scores (logits) into probabilities with softmax gives "what comes next" at each position. Generating text is just: run the model, pick a token from the last position's probabilities, append it, repeat (lesson 5.7).

Between input and output, a decoder-only transformer does four things:

  1. Embed. Look up a learned vector of size d_model for every token id, and add information about its position. Now the sentence is a matrix of shape (T, d_model), one row per token.
  2. Transform, many times. Pass that matrix through a stack of identical transformer blocks (each with its own weights). Every block keeps the shape (T, d_model) and refines each row using information from the other rows.
  3. Normalise. Apply a final layer normalisation.
  4. Project to the vocabulary. Multiply every row by a (d_model, V) matrix (the language-model head) to get V logits per position.

Click through the steps of the diagram, or click any box to read what it does.

  1. The tokenizer turns text into T integer ids. Each id selects one row of the embedding table, and position information is added: a matrix of shape (T, d_model).
  2. Inside a block, each row is normalised, then multi-head attention lets every token gather information from the earlier tokens.
  3. Attention's output is added to the input rows (the residual connection) instead of replacing them.
  4. Each row is normalised again and passed through the feed-forward network on its own, then added back to the stream.
  5. The block repeats N times with different weights (GPT-2 small: 12 blocks). Then a final LayerNorm.
  6. The LM head turns each row into V logits; softmax over the last row gives the probabilities of the next token.
Token ids
Integers produced by the tokenizer: "the cat" might become [1, 3]. The model never sees characters. Lesson 4.3.
Embedding + positions
A learned table with one vector per vocabulary entry, plus position information so the model knows word order. Lessons 4.3 and 4.4.
LayerNorm
Rescales each token's vector to a standard mean and spread before a sub-layer reads it, keeping deep stacks numerically stable. Lesson 4.8.
Multi-head attention
The only place where tokens exchange information. Each token builds a query, compares it with every earlier token's key, and takes a weighted average of their values. Lessons 4.5 and 4.6.
LayerNorm
The second normalisation of the block, in front of the feed-forward network.
Feed-forward network
A two-layer MLP applied to every token separately: expand to about 4 × d_model, apply a non-linearity, compress back. Most of the parameters live here. Lesson 4.7.
Residual stream
The running (T, d_model) matrix that every sub-layer reads from and adds to. It gives gradients a direct path through the whole stack. Lesson 4.8.
Final LayerNorm
One last normalisation after the final block, before projecting to the vocabulary.
LM head
A (d_model, V) matrix that scores every vocabulary entry. Many models reuse (tie) the embedding table here to save parameters.
Softmax
Turns the logits of a position into probabilities that sum to 1. During generation only the last position matters. Module 5 samples from it.
A decoder-only transformer. The block in the middle is repeated N times. Shapes stay (T, d_model) until the very end, which is what makes stacking so easy.

Inside one block

Each block does two things, in this order. First, communication: multi-head self-attention lets every position look at other positions and pull in what it needs ("it" looks back for the noun it refers to). Second, computation: a feed-forward network processes each position on its own, turning the gathered information into new features. Both sub-layers are wrapped the same way: normalise the input, apply the sub-layer, add the result back. In the "pre-norm" arrangement used by GPT-2 and most later models:

x←x+Attention(LayerNorm(x))x←x+FFN(LayerNorm(x))

In words: take the current token vectors, normalise a copy, let attention compute an update from it, and add that update to the vectors; then do the same with the feed-forward network. The arrow means "replace x with".

Because every block maps (T, d_model) to (T, d_model), you can stack as many as you like. Making a model "bigger" mostly means three knobs: more blocks (depth), wider vectors (d_model, and with it d_ff and the number of heads), and a longer context (T). The block design itself barely changes.

Here is the block as it appears in the NumPy model you will run in lesson 4.9. It is four lines, and they are exactly the two equations above:

def block(x, p, cfg):
    x = x + causal_self_attention(layer_norm(x, p["ln1_g"], p["ln1_b"]), p, cfg["n_heads"])  # pre-norm
    x = x + ffn(layer_norm(x, p["ln2_g"], p["ln2_b"]), p)
    return x
  1. def block(x, p, cfg): x is the residual stream, shape (T, d_model); p is a dictionary with this block's own weights; cfg holds sizes such as the number of heads.
  2. layer_norm(x, p["ln1_g"], p["ln1_b"]): normalises each row, with a learned gain and bias per feature.
  3. causal_self_attention(…): lets each token gather information from itself and the tokens before it, returns a (T, d_model) update.
  4. x = x + …: the residual connection. The update is added; nothing is overwritten.
  5. x = x + ffn(layer_norm(x, …), p): the same pattern with the feed-forward network.
  6. return x: same shape as the input, ready for the next block.

And here is the whole forward pass that stacks the blocks, with a print of the shape after every stage:

def forward(ids, params, cfg, verbose=False):
    T, d = len(ids), cfg["d_model"]
    say = print if verbose else (lambda *a: None)
    say(f"token ids                {str(tuple(np.shape(ids))):>10}")
    x = params["tok_emb"][ids] * np.sqrt(d)                  # lookup (scaled as in the original paper)
    say(f"token embeddings         {str(x.shape):>10}")
    x = x + sinusoidal_positions(T, d)                       # add position information
    say(f"+ positions              {str(x.shape):>10}")
    for i, p in enumerate(params["blocks"]):
        x = block(x, p, cfg)
        say(f"after block {i + 1}            {str(x.shape):>10}")
    x = layer_norm(x, params["lnf_g"], params["lnf_b"])      # final norm
    say(f"final LayerNorm          {str(x.shape):>10}")
    logits = x @ params["tok_emb"].T                         # LM head, tied to the embedding table
    say(f"logits                   {str(logits.shape):>10}")
    return logits
  1. params["tok_emb"][ids] * np.sqrt(d): the embedding lookup (one row per id), scaled by dmodel as in the original paper so that the token signal is not drowned out by the position signal.
  2. x + sinusoidal_positions(T, d): adds a fixed position pattern (lesson 4.4).
  3. for i, p in enumerate(params["blocks"]): runs the blocks in order; each has its own weights.
  4. layer_norm(x, params["lnf_g"], params["lnf_b"]): the final normalisation.
  5. x @ params["tok_emb"].T: the LM head. It reuses the embedding table, transposed (weight tying), so a token's output score is the dot product of the final vector with that token's embedding.
prompt: the cat sat on the -> [1, 3, 6, 9, 1]
config: {'vocab_size': 17, 'd_model': 32, 'n_heads': 4, 'n_layers': 2, 'd_ff': 128, 'max_len': 64}

token ids                      (5,)
token embeddings            (5, 32)
+ positions                 (5, 32)
after block 1               (5, 32)
after block 2               (5, 32)
final LayerNorm             (5, 32)
logits                      (5, 17)

next-token distribution after 'the cat sat on the' (top 5):
  mat      0.0755
  the      0.0735
  log      0.0655
  cat      0.0648
  sat      0.0637
entropy 2.824 nats vs uniform 2.833: random weights -> almost a uniform guess
logits for positions 0-3 unchanged when token 4 changes: True

parameters: formula 26,016, actual arrays 26,016
GPT-2 small (public config, learned positions, tied head): 124,439,808
GPT-2 medium:  354.8 M
GPT-2 large:   774.0 M
GPT-2 XL:      1,557.6 M

The shape trace in the middle of the output is the whole story of this lesson: (5,) ids become (5, 32) vectors, keep that shape through both blocks, and become (5, 17) logits, one score per vocabulary word at each of the 5 positions. The rest of the output (random-weight predictions, causality check and parameter counts) is explained in lesson 4.9.

Explore the shapes and the parameters

Step through a block for two configurations: the tiny model from this module and a model with the publicly documented shape of GPT-2 small (2019). Notice which stages hold parameters and which only compute.

Transformer block explorerInteractive

Two things to notice. First, the attention score matrix is the only object whose size grows with T2: at T = 1,024 with 12 heads it has over 12 million entries per layer. Second, with the GPT-2 shape, the embedding table alone is almost a third of the parameters; in very large models the blocks dominate instead, because block parameters grow with dmodel2.

Three families of transformers

The 2017 transformer was built for translation and had two halves: an encoder that reads the source sentence with attention in both directions, and a decoder that writes the translation one token at a time, attending to its own previous output (causally) and to the encoder's output (cross-attention). Later work kept only one half or both:

FamilyAttentionTrained toTypical uses and examples
Encoder-onlyEvery token sees every tokenFill in masked wordsClassification, search embeddings (BERT and its descendants)
Encoder-decoderEncoder: both ways; decoder: causal + cross-attentionMap an input text to an output textTranslation, summarisation (the original transformer, T5)
Decoder-onlyCausal: each token sees only earlier tokensPredict the next tokenGeneral text generation and chat (GPT family, Llama, Mistral, Qwen, Gemma)

Open-weight chat models are overwhelmingly decoder-only, and that is the design this course builds. Anthropic has said publicly that Claude is a transformer-based language model Public; the exact variant, layer count, width and other architecture details have not been published Not public. When this course says "a model like Claude" it means the general decoder-only recipe Industry practice, not a description of Claude's internals.

Why decoder-only training is efficient

Because of the causal mask, position 3's output depends only on tokens 1 to 3. So a single forward pass over a 1,000-token training text produces 1,000 next-token predictions at once, each one using only the tokens before it, and the loss averages over all of them. This is called teacher forcing: the model is always shown the true previous tokens during training. Combined with the parallel computation from lesson 4.1, it means every token of training text provides a learning signal, and all of them are computed together. Module 5 trains exactly this way.

Post-norm vs pre-norm, and what modern models change

The 2017 paper placed LayerNorm after each residual addition ("post-norm": x←LN(x+f(x))). That works for 6 layers but needs a careful learning-rate warm-up and becomes unstable for deep stacks. GPT-2 moved the norm to the input of each sub-layer and added a final LayerNorm ("pre-norm"); the residual stream is then never normalised in place, which keeps a clean gradient path (analysed by Xiong et al., 2020). Almost all large models since use pre-norm.

Publicly documented open-weight models (for example the Llama family) also swap several parts while keeping the overall shape: RMSNorm instead of LayerNorm (lesson 4.8), rotary position embeddings (RoPE) instead of added sinusoids (lesson 4.4), SwiGLU feed-forward layers (lesson 4.7), grouped-query attention to shrink the KV cache (lesson 4.5), no bias terms, and sometimes mixture-of-experts layers in which each token uses only a few of many FFNs. These are Industry practice; whether and how any of them are used in Claude is Not public.

A handy rule of thumb for the size of a standard block: attention has 4d2 weights (Q, K, V and output projections) and the FFN has 2d·4d=8d2, so one block is about 12d2 and the model is about 12Ld2 plus embeddings. For GPT-2 small that is 12·12·7682≈85 million in the blocks plus about 39 million in the embedding table. The compute for a forward pass is roughly 2 floating-point operations per parameter per token, plus the attention term that grows with context length.

Common mistakes and debugging tips

Thinking the model outputs one token per forward pass

A forward pass produces logits for every position. During generation you only read the last row; during training you use all of them.

Fix: when your logits have shape (T, V), take logits[-1] for the next token, and compare all rows with the shifted targets for the loss.

Replacing x instead of adding to it

Writing x = attention(layer_norm(x)) instead of x = x + … silently removes the residual connection. A deep model built that way trains badly or not at all (lesson 4.8 shows why).

Fix: check every sub-layer call has the x = x + … shape, and test a 1-block model first: it should still train, just worse.

Mixing up the three families

Bidirectional attention (encoder-style) lets position 3 see position 4. If you use it in a model trained to predict the next token, the model learns to copy the answer from the future and appears perfect in training, then fails at generation.

Fix: always apply the causal mask in a decoder-only language model, and add a test that changing a later token leaves earlier outputs unchanged (transformer.py prints this check).

Key takeaways

  • A decoder-only transformer is: embed + positions, N identical blocks, a final norm, and a projection to vocabulary logits.
  • Each block is "communicate, then compute": attention, then a per-token FFN, each wrapped in LayerNorm and a residual addition.
  • Shapes stay (T, d_model) throughout, so models scale by stacking more and wider blocks.
  • Claude is publicly described as transformer-based; its specific architecture is not public.

Exercise: count the parameters

Using the same structure as our NumPy model (pre-norm blocks with biases, LayerNorm gain and bias, sinusoidal positions, LM head tied to the embedding), work out the number of parameters for d_model = 512, d_ff = 2048, 8 blocks and a vocabulary of 32,000 tokens. Do it by hand first, then check with count_params from transformer.py.

Hint

Per block: two LayerNorms (2d each), Q/K/V (3d2+3d), output projection (d2+d), FFN (2df+f+d). Then add the embedding table and the final LayerNorm. The number of heads does not matter.

Show a solution

Per block: 4d2+2df+9d+f = 1,048,576 + 2,097,152 + 4,608 + 2,048 = 3,152,384. Eight blocks: 25,219,072. Embedding table: 32,000 × 512 = 16,384,000. Final LayerNorm: 1,024. Total: 41,604,096, about 41.6 million.

cfg = dict(vocab_size=32000, d_model=512, n_heads=8, n_layers=8, d_ff=2048, max_len=1024)
print(f"{count_params(cfg):,}")   # 41,604,096

Notice the embedding table is about 40 % of this small model. Untie the head (tied_head=False) and you add another 16.4 million.

Check your understanding

In a transformer block, where do tokens exchange information with each other?

  1. In the feed-forward network
  2. In the self-attention sub-layer
  3. In LayerNorm
Attention is the only sub-layer that mixes rows. The FFN and LayerNorm act on each token's vector separately.

A decoder-only model receives 10 tokens. What shape are its logits (vocabulary size V)?

  1. (V,)
  2. (10,)
  3. (10, V)
One row of V scores per position. For generation you read the last row; for training you use all 10 rows at once.

What is publicly known about Claude's architecture?

  1. That it is a transformer-based language model; layer counts and widths are not published
  2. Its exact number of layers and heads
  3. That it is an LSTM
Anthropic describes Claude as transformer-based but has not published the detailed architecture. Any specific layer count you see quoted is a guess.

Lesson 4.3Module 4: Understanding transformers

Tokenization and embeddings

  • ⏱ 18 min read
  • Intermediate

Learning objectives

  • Explain why language models work on subword tokens instead of characters or whole words.
  • Train a byte-pair-encoding (BPE) tokenizer on a tiny corpus and encode new text with it, by hand and in Python.
  • Describe an embedding table as a learned matrix and an embedding lookup as selecting rows.
  • Estimate the memory cost of an embedding table and say what is (and is not) public about Claude's tokenizer.

Neural networks only do arithmetic on numbers, so before a transformer can read "The cat sat", the text has to become numbers. That happens in two steps. A tokenizer chops text into pieces from a fixed list (the vocabulary) and replaces each piece with its index, a token id. Then an embedding table turns each id into a vector of learned numbers. This lesson builds both, small enough to check by hand. Module 5 builds a fuller tokenizer for the tiny GPT (lesson 5.1).

Analogy: LEGO bricks and a parts catalogue

A tokenizer is like a LEGO set designer. With only 1×1 bricks (single characters) you can build anything, but every model needs thousands of pieces. With one custom brick per finished model (whole words) you need a warehouse of unique parts, and a new design is impossible. Real sets mix both: common shapes like "the" or "ing" get their own brick, rare things are built from small ones. The embedding table is the parts catalogue: for every brick number, a page describing that brick with a few hundred numbers, and those descriptions are learned during training.

Characters, words or something in between?

There are three obvious ways to split text, and the first two fail in instructive ways:

UnitVocabulary"unbelievably" becomesProblem
CharactersSmall (about 100 for English, more for all scripts)12 tokensSequences get very long; attention cost grows with the square of the length, and the model must learn spelling before meaning.
Whole wordsHuge (hundreds of thousands, still incomplete)1 token, if it was in the listNew words, typos, names and code identifiers become "unknown"; "run", "runs" and "running" share nothing.
SubwordsChosen size, typically tens of thousands to a few hundred thousandA few pieces, e.g. "un" "believ" "ably"A good compromise: common words are one token, rare words are spelled from parts, nothing is ever unknown with byte-level fallback.

Subword tokenizers are what essentially every modern LLM uses. The most common algorithm is byte-pair encoding (BPE), adapted for machine translation by Sennrich, Haddow and Birch (2015) from an older compression technique. The exact split depends on the training data of the tokenizer: the example split of "unbelievably" above is illustrative, not what any particular model does.

How BPE learns its vocabulary

The idea fits in one sentence: start from single characters and repeatedly glue together the pair of neighbours that occurs most often. Concretely:

  1. Split the training text into words (keeping each word's leading space, as GPT-2 does, so " cat" and "cat" are different tokens).
  2. Write every word as a list of characters and count every adjacent pair across the corpus, weighted by how often the word occurs.
  3. Take the most frequent pair, for example t + h, add th to the vocabulary, record the merge rule, and replace that pair everywhere.
  4. Repeat until the vocabulary reaches the size you want. Each repetition adds exactly one token.

To encode new text, split it into characters and replay the merge rules in the order they were learned. The list of merges is the tokenizer; it is deterministic, so the same text always produces the same ids. Try it below. The default corpus is the one in bpe.py, so at 12 merges you will see exactly the Python output further down.

BPE tokenizer playgroundInteractive

Learned merges, in order

    Things to try: set merges to 0 and you get plain characters; raise it and frequent words collapse into single tokens. Type a word that is not in the corpus ("dogma") and watch it get spelled from known pieces. A character that never appeared (like "!") gets id −1 here: our toy tokenizer has no way to represent it. Real tokenizers avoid this by starting from the 256 possible bytes of UTF-8 instead of characters, so any text, in any language, emoji included, can always be encoded.

    BPE in Python

    # @run
    # A tiny byte-pair-encoding (BPE) trainer and encoder, character level, for teaching.
    # Lesson 4.3 of "How to Build Claude from Scratch". Standard library only.
    from collections import Counter
    
    corpus = (
        "the cat sat on the mat. the dog sat on the log. "
        "the cat ran to the dog and the dog ran to the cat. "
        "then the other cat sat there with the other dog."
    )
    
    
    def pre_tokenize(text):
        """Split into words; keep the leading space as part of the word (like GPT-2's tokenizer)."""
        words, cur = [], ""
        for ch in text:
            if ch == " " and cur:
                words.append(cur)
                cur = ""
            cur += ch
        if cur:
            words.append(cur)
        return words
    
    
    def train_bpe(text, num_merges):
        word_freq = Counter(pre_tokenize(text))
        splits = {w: list(w) for w in word_freq}            # every word starts as characters
        merges = []
        for _ in range(num_merges):
            pairs = Counter()
            for w, f in word_freq.items():
                sym = splits[w]
                for a, b in zip(sym, sym[1:]):
                    pairs[(a, b)] += f
            if not pairs:
                break
            best = max(pairs, key=lambda p: (pairs[p], p))  # most frequent pair (ties: deterministic)
            merges.append(best)
            for w in splits:                                  # apply the merge everywhere
                sym, out, i = splits[w], [], 0
                while i < len(sym):
                    if i + 1 < len(sym) and (sym[i], sym[i + 1]) == best:
                        out.append(sym[i] + sym[i + 1])
                        i += 2
                    else:
                        out.append(sym[i])
                        i += 1
                splits[w] = out
        return merges
    
    
    def encode(text, merges):
        tokens = []
        for w in pre_tokenize(text):
            sym = list(w)
            for a, b in merges:                               # replay merges in the order learned
                i, out = 0, []
                while i < len(sym):
                    if i + 1 < len(sym) and sym[i] == a and sym[i + 1] == b:
                        out.append(a + b)
                        i += 2
                    else:
                        out.append(sym[i])
                        i += 1
                sym = out
            tokens += sym
        return tokens
    
    
    merges = train_bpe(corpus, 12)
    print("learned merges, in order:")
    for i, (a, b) in enumerate(merges, 1):
        print(f"  {i:>2}. {a!r} + {b!r} -> {a + b!r}")
    
    base = sorted(set(corpus))
    vocab = base + [a + b for a, b in merges]
    ids = {t: i for i, t in enumerate(vocab)}
    print(f"\nvocabulary: {len(base)} characters + {len(merges)} merges = {len(vocab)} tokens")
    
    for text in ["the cat sat", "the hat", "a dogma!"]:
        toks = encode(text, merges)
        print(f"\n{text!r} -> {len(toks)} tokens")
        print("  ", " | ".join(repr(t) for t in toks))
        print("   ids:", [ids.get(t, -1) for t in toks], "(-1 = character never seen in training)")
    1. pre_tokenize(text): splits on spaces but keeps the space at the start of each word, so " cat" (with its space) can become one token. Merges never cross word boundaries.
    2. word_freq = Counter(pre_tokenize(text)): counts each distinct word once with its frequency, so we don't re-scan repeated words.
    3. splits = {w: list(w) …}: every word starts as a list of single characters.
    4. pairs[(a, b)] += f: counts every adjacent pair, weighted by the word's frequency.
    5. best = max(pairs, key=lambda p: (pairs[p], p)): the most frequent pair; ties are broken by comparing the pair itself, so the result is deterministic.
    6. out.append(sym[i] + sym[i + 1]): applies the merge inside every word, left to right.
    7. encode: for new text, replays the merges in learned order. The order matters: 'th' + 'e' can only fire after 't' + 'h' created 'th'.
    8. vocab = base + [a + b for a, b in merges]: the vocabulary is the characters seen in training plus one token per merge; an id is just a position in this list.
    learned merges, in order:
       1. 't' + 'h' -> 'th'
       2. 'th' + 'e' -> 'the'
       3. ' ' + 'the' -> ' the'
       4. 'a' + 't' -> 'at'
       5. 'o' + 'g' -> 'og'
       6. 'd' + 'og' -> 'dog'
       7. 'c' + 'at' -> 'cat'
       8. ' ' + 'o' -> ' o'
       9. ' ' + 'dog' -> ' dog'
      10. ' ' + 'cat' -> ' cat'
      11. 's' + 'at' -> 'sat'
      12. 'a' + 'n' -> 'an'
    
    vocabulary: 17 characters + 12 merges = 29 tokens
    
    'the cat sat' -> 4 tokens
       'the' | ' cat' | ' ' | 'sat'
       ids: [18, 26, 0, 27] (-1 = character never seen in training)
    
    'the hat' -> 4 tokens
       'the' | ' ' | 'h' | 'at'
       ids: [18, 0, 7, 20] (-1 = character never seen in training)
    
    'a dogma!' -> 5 tokens
       'a' | ' dog' | 'm' | 'a' | '!'
       ids: [2, 25, 10, 2, -1] (-1 = character never seen in training)

    Look at the merges: "the" is learned by merge 2 because it is by far the most common word. In "the cat sat", the result is 'the' | ' cat' | ' ' | 'sat': " sat" did not become one token, because the merge ' ' + 'sat' was never learned in 12 steps (the space got merged with "the", "o", "dog" and "cat" first). This is typical of real tokenizers too: token boundaries often look odd to humans, which is why models can struggle with tasks like counting letters in a word.

    From ids to vectors: the embedding table

    A token id is just a name. Id 26 is not "bigger" than id 2 in any meaningful way, so we cannot feed raw ids into arithmetic. Instead, the model owns a matrix E with one row per vocabulary entry and d_model columns. Looking up a token means taking its row. These rows start random and are adjusted by training like every other weight, until tokens used in similar ways end up with similar vectors.

    xt=E[idt]=onehottE,E∈ℝV×dmodel

    In words: the vector for the token at position t is the row of E with that token's id. That is the same as multiplying a one-hot vector (all zeros except a 1 at the id) by E, which shows the lookup is an ordinary linear layer, just computed cheaply.

    # @run
    # An embedding table is just a matrix: looking up token ids means picking rows.
    # Lesson 4.3 of "How to Build Claude from Scratch". Needs only NumPy.
    import numpy as np
    
    rng = np.random.default_rng(0)
    
    vocab = ["<unk>", " the", " cat", " dog", " sat", " on", " mat", " ran", "."]
    token_to_id = {tok: i for i, tok in enumerate(vocab)}
    V, d_model = len(vocab), 6
    
    E = rng.normal(0, 0.02, (V, d_model))       # one learnable row per token (GPT-2 style init)
    print("embedding table E:", E.shape, "(vocab size x d_model)")
    
    tokens = [" the", " cat", " sat", " on", " the", " mat", "."]
    ids = np.array([token_to_id.get(t, 0) for t in tokens])
    print("token ids:", ids.tolist())
    
    x = E[ids]                                  # the lookup: fancy indexing picks rows
    print("x = E[ids]:", x.shape, "(sequence length x d_model)")
    
    # Same thing written as a matrix product with one-hot vectors (slow, but shows it is linear)
    one_hot = np.eye(V)[ids]                    # (7, 9), a single 1 per row
    print("one_hot @ E equals E[ids]:", bool(np.allclose(one_hot @ E, x)))
    
    # Both occurrences of " the" get exactly the same vector: no position information yet
    print("row 0 == row 4 (both ' the'):", bool(np.array_equal(x[0], x[4])))
    
    print("\nvector for ' cat' (rounded):")
    print(np.round(E[token_to_id[" cat"]] * 100, 2), "x 1e-2")
    
    # The original transformer multiplies embeddings by sqrt(d_model) before adding positions
    print("\nscaled by sqrt(d_model):", f"{np.sqrt(d_model):.3f}")
    
    # Gradients only touch the rows that were used: count how often each row was looked up
    grad_rows = np.bincount(ids, minlength=V)
    print("rows that receive a gradient this step:")
    for tok, n in zip(vocab, grad_rows):
        print(f"  {tok!r:8} used {int(n)} time(s)")
    
    # Memory cost of a realistic table
    for name, v, d in [("GPT-2 small", 50257, 768), ("a 100k vocab, d=4096 model", 100_000, 4096)]:
        params = v * d
        print(f"{name}: {params:,} parameters = {params * 2 / 1e6:,.0f} MB in 16-bit floats")
    1. E = rng.normal(0, 0.02, (V, d_model)): the table, 9 tokens × 6 numbers, initialised with small random values (GPT-2 used a standard deviation of 0.02).
    2. ids = np.array([token_to_id.get(t, 0) …]): tokens to ids; unknown tokens fall back to id 0, <unk>.
    3. x = E[ids]: NumPy "fancy indexing" picks rows; the result has one row per token, shape (7, 6).
    4. one_hot @ E: the slow but equivalent matrix product, printed as a check.
    5. np.array_equal(x[0], x[4]): both " the" tokens get identical vectors. The embedding knows what a token is, not where it is; lesson 4.4 fixes that.
    6. np.bincount(ids, minlength=V): in backpropagation only rows that were looked up get a gradient. Rare tokens are updated rarely, one reason they are learned poorly.
    7. params * 2 / 1e6: memory at 2 bytes per number (16-bit floats), for realistic table sizes.
    embedding table E: (9, 6) (vocab size x d_model)
    token ids: [1, 2, 4, 5, 1, 6, 8]
    x = E[ids]: (7, 6) (sequence length x d_model)
    one_hot @ E equals E[ids]: True
    row 0 == row 4 (both ' the'): True
    
    vector for ' cat' (rounded):
    [-4.65 -0.44 -2.49 -1.46 -1.09 -0.63] x 1e-2
    
    scaled by sqrt(d_model): 2.449
    rows that receive a gradient this step:
      '<unk>'  used 0 time(s)
      ' the'   used 2 time(s)
      ' cat'   used 1 time(s)
      ' dog'   used 0 time(s)
      ' sat'   used 1 time(s)
      ' on'    used 1 time(s)
      ' mat'   used 1 time(s)
      ' ran'   used 0 time(s)
      '.'      used 1 time(s)
    GPT-2 small: 38,597,376 parameters = 77 MB in 16-bit floats
    a 100k vocab, d=4096 model: 409,600,000 parameters = 819 MB in 16-bit floats

    The last two lines are worth a pause: GPT-2 small's embedding table is 38.6 million numbers, about 77 MB in 16-bit floats, and a model with a 100,000-token vocabulary and 4,096-wide vectors needs about 410 million parameters for the table alone. Vocabulary size is a real design trade-off: bigger vocabularies make sequences shorter (cheaper attention, more text per context window) but cost parameters and leave rare tokens under-trained.

    What do trained embeddings capture?

    After training, nearby vectors tend to belong to tokens that appear in similar contexts: " cat" and " dog" end up closer than " cat" and " of". Earlier word-vector methods such as word2vec made this famous with analogies like "king − man + woman ≈ queen". In a transformer the input embedding is only the starting point: the blocks rewrite each vector based on context, so by the middle layers the vector for "bank" in "river bank" and in "bank account" has moved apart. That contextual rewriting is what attention is for.

    In production: Claude's tokenizer

    Anthropic has not published Claude's tokenizer or its vocabulary size Not public. What is public is that usage is measured and billed in tokens, and that the API can count the tokens of a request for you before you send it Public. A common rough rule for English with most modern tokenizers is a few characters per token, but code, other languages and numbers can differ a lot, so measure instead of guessing. Open-weight models publish their tokenizers (for example on huggingface.co), which is how you can inspect real merge lists.

    Byte-level BPE, other tokenizers and tied embeddings

    Byte-level BPE. GPT-2 starts from the 256 byte values instead of Unicode characters, maps them to printable symbols, applies a regular-expression pre-tokenizer (separating letters, digits, punctuation and spaces) and learns about 50,000 merges for a vocabulary of 50,257. Since every string is a sequence of bytes, there is no unknown token. The cost is that a non-Latin character may take several tokens, so some languages "cost" more tokens per word than English.

    Other algorithms. WordPiece (BERT) picks merges that most increase the likelihood of the training data instead of raw frequency. The Unigram model (in the SentencePiece library) starts from a big vocabulary and prunes it, and can sample different segmentations for robustness. All of them produce a vocabulary of subword strings plus a deterministic way to encode.

    Weight tying. The output head that scores the next token is a dmodel×V matrix, the same shape as ET. Tying them (Press and Wolf, 2016) saves V·dmodel parameters and often helps small models; large models sometimes keep them separate. Our NumPy model ties them (lesson 4.9).

    Special tokens. Real vocabularies reserve ids for markers such as "end of text" or the boundaries between a system prompt, user turns and assistant turns in chat models. They are never produced by the merge rules; the application inserts them. Module 6 discusses chat formatting.

    Common mistakes and debugging tips

    Assuming tokens are words

    Budgets, context limits and prices are counted in tokens. A 1,000-word document can be anywhere from roughly 1,200 to several thousand tokens depending on language and content.

    Fix: count with the model's own tokenizer (or the provider's token-counting endpoint) instead of word counts.

    Using a different tokenizer at inference than in training

    If the merges or the id order change, every id means something else and the model produces garbage, often without an error.

    Fix: ship the tokenizer files together with the weights, version them together, and add a test that encodes a known string to known ids.

    Forgetting about leading spaces

    " cat" and "cat" are different tokens. A prompt that ends with a trailing space can push the model towards odd continuations, because the space is already a token of its own.

    Fix: inspect the actual token sequence of tricky prompts, and avoid trailing spaces at the end of a prompt you want continued.

    Key takeaways

    • LLMs read subword tokens: frequent strings become single tokens, rare ones are spelled from pieces.
    • BPE learns its vocabulary by repeatedly merging the most frequent adjacent pair; encoding replays the merges in order.
    • An embedding table is a learned (V, d_model) matrix; a lookup selects rows and carries no position information.
    • Claude's tokenizer is not public; token counts are, through the API.

    Exercise: decode and grow the tokenizer

    Add a decode(ids, vocab) function to bpe.py that turns ids back into text, and check that decode(encode(text)) returns the original for "the cat sat". Then train with 30 merges instead of 12 and report how many tokens "then the other cat sat there" needs with 12 and with 30 merges.

    Hint

    Each id is an index into vocab, and each token string already contains its own spaces, so decoding is just joining strings. For counting, call len(encode(text, merges)). You can check your counts in the playground above by setting the merge slider.

    Show a solution
    def decode(ids, vocab):
        return "".join(vocab[i] for i in ids)
    
    toks = encode("the cat sat", merges)
    assert decode([ids[t] for t in toks], vocab) == "the cat sat"
    
    for n in (12, 30):
        m = train_bpe(corpus, n)
        print(n, "merges:", len(encode("then the other cat sat there", m)), "tokens")

    The round trip works because BPE never loses characters, it only groups them (with the −1 ids of unseen characters it would fail, which is exactly why real tokenizers are byte-level). The count drops from 12 tokens ('the' | 'n' | ' the' | ' o' | 'the' | 'r' | ' cat' | ' ' | 'sat' | ' the' | 'r' | 'e') to 7 ('the' | 'n' | ' the' | ' other' | ' cat' | ' sat' | ' there'): " other", " sat" and " there" become single tokens once enough merges are allowed. "then" stays split because it occurs only once. The playground shows the same counts as Python because it implements the same rules, including the tie-break.

    Check your understanding

    Why do modern LLMs use subword tokens rather than whole words?

    1. Whole words would make sequences longer
    2. Subwords keep the vocabulary manageable while still encoding any new or rare word from pieces
    3. Subwords are easier for humans to read
    Whole-word vocabularies are huge and still miss new words; characters make sequences very long. Subwords sit in between. Whole words would make sequences shorter, not longer.

    The sentence contains " the" twice. Before positional information is added, how do their embedding vectors compare?

    1. They are identical
    2. They differ by a random amount
    3. The second one is the first one scaled by 2
    A lookup selects the same row for the same id. Distinguishing the two occurrences is the job of positional encoding (lesson 4.4) and, later, of attention.

    In BPE, what does one training step add to the vocabulary?

    1. Every word that appears more than once
    2. All character pairs at once
    3. Exactly one new token: the merge of the currently most frequent adjacent pair
    Each merge adds one token, which is why the number of merges controls the vocabulary size directly.

    Lesson 4.4Module 4: Understanding transformers

    Positional encoding

    • ⏱ 13 min read
    • Intermediate

    Learning objectives

    • Show why self-attention on its own ignores word order (it is permutation-equivariant).
    • Compute sinusoidal positional encodings and read their heat map.
    • Compare the main approaches: learned absolute positions, sinusoids, relative schemes and rotary embeddings (RoPE).
    • Verify in code that adding positions breaks the symmetry and that a fixed offset is a rotation.

    "Dog bites man" and "man bites dog" use the same three tokens. Their embeddings, from lesson 4.3, are the same three vectors. If a model cannot tell the orders apart, it cannot tell the news story from the everyday one. RNNs got order for free, because they read one token after another. A transformer reads all tokens at once, so order has to be added deliberately. That is what positional encoding does.

    Analogy: seat numbers and clock hands

    Imagine the tokens are guests at a round table, and attention lets every guest talk to every other guest. Without seat numbers, the conversation would go exactly the same however the guests were seated. Positional encoding gives each seat a badge. The sinusoidal version is like a badge showing a wall of clocks: a second hand that turns fast, a minute hand slower, an hour hand slower still. Read together, the hands identify every seat uniquely, and seats close together have hands in nearly the same places.

    Attention cannot see order

    You will build attention properly in the next lesson, but one fact matters now. Attention computes, for each token, a weighted average of all tokens, where the weights come from comparing vectors with dot products. Nothing in that computation looks at where a vector sits in the list. So if you shuffle the input rows, the output rows are shuffled in exactly the same way and are otherwise unchanged. Mathematicians call this permutation equivariance. It is a lovely property for sets (a bag of items with no order) and a disaster for sentences.

    The fix is simple: before the first block, add to each token's vector a second vector that depends only on its position. The token "dog" at position 0 then becomes a different vector from "dog" at position 2, and every later computation can tell them apart.

    xt=E[idt]+Pt

    In words: the input to the first block at position t is the token's embedding plus a position vector of the same length. Adding (rather than concatenating) keeps the width at d_model; the model learns to use different directions of the space for "what" and "where".

    The sinusoidal recipe

    Where should the position vectors come from? The 2017 transformer used a fixed formula, no learning involved. Each pair of dimensions is a point going round a circle at its own speed as the position increases: the first pair turns quickly (about one radian per position), and each following pair turns more slowly, until the last pairs barely move over thousands of positions. A position is described by where every one of those "clock hands" points. In symbols, for position p and dimension pair i:

    Pp,2i=sin(p100002i/d)Pp,2i+1=cos(p100002i/d)

    In words: even dimensions hold the sine and odd dimensions the cosine of the position divided by a number that grows from 1 (for the first pair) to almost 10,000 (for the last pair). Small i: fast-changing; large i: slow-changing. Every value lies between −1 and 1.

    Why this particular design? Three useful properties. Values are bounded, so the position never overwhelms the token embedding. Every position gets a distinct pattern, and nearby positions get similar patterns. And, most elegantly, moving by a fixed offset k is the same rotation of every (sin, cos) pair regardless of where you start, so "three tokens to the left" looks the same to the model at position 5 as at position 500. The heat map makes this visible: each row is a position, each column a dimension; fast stripes on the left, slow ones on the right.

    Positional encoding heat mapInteractive

    −1 0 +1 · rows: positions 0–63 · columns: dimensions

    Move the slider and watch the similarity numbers: the dot product between position p and p+k is the same for every p. It depends only on the distance.

    Proving it in NumPy

    # @run
    # Sinusoidal positional encoding (Vaswani et al., 2017) and why attention needs it.
    # Lesson 4.4 of "How to Build Claude from Scratch". Needs only NumPy.
    import numpy as np
    
    
    def sinusoidal_positions(seq_len, d_model, base=10000.0):
        """PE[pos, 2i] = sin(pos / base^(2i/d)),  PE[pos, 2i+1] = cos(pos / base^(2i/d))."""
        pos = np.arange(seq_len)[:, None]                  # (T, 1)
        i = np.arange(d_model // 2)[None, :]               # (1, d/2)
        freq = 1.0 / base ** (2 * i / d_model)             # one angular speed per pair of dims
        angles = pos * freq                                # (T, d/2)
        pe = np.zeros((seq_len, d_model))
        pe[:, 0::2] = np.sin(angles)                       # even dims
        pe[:, 1::2] = np.cos(angles)                       # odd dims
        return pe
    
    
    def softmax(z):
        z = z - z.max(axis=-1, keepdims=True)
        e = np.exp(z)
        return e / e.sum(axis=-1, keepdims=True)
    
    
    def attention(x):
        """Plain self-attention with identity projections (enough to show the symmetry)."""
        w = softmax(x @ x.T / np.sqrt(x.shape[1]))
        return w @ x
    
    
    rng = np.random.default_rng(0)
    T, d = 6, 8
    pe = sinusoidal_positions(50, d)
    print("PE shape:", pe.shape)
    print("first 4 positions (rounded):")
    print(np.round(pe[:4], 3))
    
    # 1. Attention without positions is permutation-equivariant: shuffle in, shuffle out
    x = rng.normal(0, 1, (T, d))
    perm = np.array([3, 0, 5, 1, 4, 2])
    out = attention(x)
    out_perm = attention(x[perm])
    print("\nno positions: attention(shuffled) == shuffled(attention):", bool(np.allclose(out_perm, out[perm])))
    
    # 2. Add positions and the symmetry is broken: the same word in a new place gets a new output
    xp = x + pe[:T]
    out_p = attention(xp)
    out_p_perm = attention(x[perm] + pe[:T])
    print("with positions:  attention(shuffled) == shuffled(attention):", bool(np.allclose(out_p_perm, out_p[perm])))
    
    # 3. Every value stays in [-1, 1] and every position has the same norm sqrt(d/2)
    print(f"\nmin {pe.min():.3f}, max {pe.max():.3f}, norm of every row = {np.linalg.norm(pe, axis=1).mean():.3f} (sqrt(d/2) = {np.sqrt(d / 2):.3f})")
    
    # 4. Similarity depends on distance, not on absolute position
    print("\ndot product PE[p] . PE[p+k]:")
    for k in [0, 1, 2, 4, 8, 16]:
        sims = [float(pe[p] @ pe[p + k]) for p in (0, 10, 30)]
        print(f"  k={k:>2}:  p=0 {sims[0]:6.3f}   p=10 {sims[1]:6.3f}   p=30 {sims[2]:6.3f}")
    
    # 5. A fixed offset k is a rotation: PE[p+k] = M_k @ PE[p] for the same M_k at every p
    k = 3
    freqs = 1.0 / 10000 ** (2 * np.arange(d // 2) / d)
    M = np.zeros((d, d))
    for j, w in enumerate(freqs):
        c, s = np.cos(w * k), np.sin(w * k)
        M[2 * j:2 * j + 2, 2 * j:2 * j + 2] = [[c, s], [-s, c]]   # rotates each (sin, cos) pair
    ok = all(np.allclose(M @ pe[p], pe[p + k]) for p in range(40))
    print(f"\nPE[p+{k}] == M_{k} @ PE[p] for p = 0..39:", ok)
    1. pos = np.arange(seq_len)[:, None] and i = np.arange(d_model // 2)[None, :]: a column of positions and a row of pair indices; multiplying them broadcasts into a (T, d/2) grid of angles.
    2. freq = 1.0 / base ** (2 * i / d_model): one angular speed per pair, from 1 down to almost 1/10000.
    3. pe[:, 0::2] = np.sin(angles), pe[:, 1::2] = np.cos(angles): sines in even columns, cosines in odd columns.
    4. attention(x): a bare self-attention with no learned weights, enough to test symmetry.
    5. np.allclose(out_perm, out[perm]): shuffling the input and then attending equals attending and then shuffling: no sense of order.
    6. xp = x + pe[:T]: add positions; the same test now fails, which is what we want.
    7. pe[p] @ pe[p + k]: similarity between two positions, at three different starting points.
    8. M[2 * j:2 * j + 2, 2 * j:2 * j + 2] = [[c, s], [-s, c]]: builds a block-diagonal rotation, one 2×2 rotation per (sin, cos) pair, and checks that it maps every position to the one 3 steps later.
    PE shape: (50, 8)
    first 4 positions (rounded):
    [[ 0.     1.     0.     1.     0.     1.     0.     1.   ]
     [ 0.841  0.54   0.1    0.995  0.01   1.     0.001  1.   ]
     [ 0.909 -0.416  0.199  0.98   0.02   1.     0.002  1.   ]
     [ 0.141 -0.99   0.296  0.955  0.03   1.     0.003  1.   ]]
    
    no positions: attention(shuffled) == shuffled(attention): True
    with positions:  attention(shuffled) == shuffled(attention): False
    
    min -1.000, max 1.000, norm of every row = 2.000 (sqrt(d/2) = 2.000)
    
    dot product PE[p] . PE[p+k]:
      k= 0:  p=0  4.000   p=10  4.000   p=30  4.000
      k= 1:  p=0  3.535   p=10  3.535   p=30  3.535
      k= 2:  p=0  2.564   p=10  2.564   p=30  2.564
      k= 4:  p=0  2.267   p=10  2.267   p=30  2.267
      k= 8:  p=0  2.548   p=10  2.548   p=30  2.548
      k=16:  p=0  1.000   p=10  1.000   p=30  1.000
    
    PE[p+3] == M_3 @ PE[p] for p = 0..39: True

    Every claim from the explanation shows up as a line of output: the symmetry is True without positions and False with them; every row has the same length, 2.000 (that is d/2, since each pair contributes sin2+cos2=1); the dot product at each distance is identical whether you start at position 0, 10 or 30; and one fixed matrix shifts every position by 3. Notice also that the similarity does not fall smoothly with distance (2.267 at k = 4 but 2.548 at k = 8): with only 8 dimensions the "clocks" line up again by coincidence. Bigger d_model smooths this out; try it in the demo.

    The main families of position methods

    MethodHowUsed by (publicly documented)Trade-off
    Sinusoidal, addedFixed formula above, added to embeddingsThe original 2017 transformerNo parameters; weak at lengths far beyond training
    Learned absolute, addedA trainable table, one vector per position up to a maximumGPT-2 (1,024 positions), BERTSimple and flexible; cannot go past the table's length at all
    Relative biasA learned or fixed bonus added to attention scores, based on the distance between query and key (e.g. ALiBi: a penalty proportional to distance)T5 (learned buckets), several models with ALiBiOrder enters where it matters, in the comparison; handles longer inputs more gracefully
    Rotary (RoPE)Rotate query and key vectors by an angle proportional to their positions, inside attentionLlama, Mistral, Qwen, Gemma and many other open modelsDot products depend only on relative distance; the most common choice in open LLMs

    Which method Claude uses has not been published Not public. Rotary embeddings are a strong default in open-weight models Industry practice. Our NumPy model keeps the original sinusoids because they are the easiest to see and test.

    Rotary position embeddings (RoPE) and long contexts

    The rotation property you just verified suggests a better idea, published by Su et al. (2021). Instead of adding a position vector to the input, rotate the query and key vectors of attention (lesson 4.6) inside every layer: split each into pairs and rotate pair i by angle p·θi. The attention score is a dot product, and a dot product of two rotated vectors only depends on the difference of their angles:

    (Rmq)T(Rnk)=qTRn−mk

    In words: rotating the query by its position m and the key by its position n gives the same score as rotating only the key by the distance n − m. Absolute positions cancel out; only the offset remains.

    Nothing is added to the residual stream, so the token's content is not mixed with a position signal, and the relative-distance behaviour is built in at every layer. Extending a model's context window beyond its training length is an active engineering area: published techniques rescale the rotation frequencies ("position interpolation" and related methods) and then fine-tune briefly on longer texts. Long-context behaviour also depends heavily on training data and attention efficiency. Claude's API offers very long context windows Public, but how that is achieved internally is not published.

    Common mistakes and debugging tips

    Forgetting positions entirely

    The model still trains, and the loss still falls (word frequencies alone help), so the bug hides. But it treats the context as a bag of words and cannot learn grammar that depends on order.

    Fix: add the permutation test from the script: shuffle the input tokens and check that the outputs are not just shuffled.

    Generating past the learned-position table

    With learned absolute positions (GPT-2 style), position 1,024 simply has no row. Code either crashes with an index error or, worse, wraps around silently.

    Fix: crop the context to the model's maximum length before each forward pass (module 5 does this), or use a relative method such as RoPE.

    Offsetting positions wrongly with a cache

    When generating with a KV cache (lesson 4.9), the new token is at position len(sequence) − 1, not position 0. Using 0 gives every new token the same position and quietly degrades the output.

    Fix: pass the start position explicitly, as embed(ids, start, …) does in kv_cache.py, and compare cached and uncached logits in a test.

    Key takeaways

    • Self-attention is permutation-equivariant: without position information, word order is invisible.
    • Sinusoidal encodings give every position a unique bounded pattern of sines and cosines at many speeds.
    • A fixed offset is a rotation, so relative distance is easy for the model to read; RoPE builds on exactly this.
    • Open models mostly use RoPE today; Claude's method is not public.

    Exercise: implement RoPE and test it

    Write a function rope(x, pos) that rotates each consecutive pair (x[2i], x[2i+1]) of a vector by the angle pos * freq[i], using the same frequencies as the sinusoidal encoding. Then show numerically that rope(q, m) @ rope(k, n) depends only on m - n, by trying three pairs of positions with the same difference.

    Hint

    Rotating a 2-D point (a,b) by angle θ gives (acosθ−bsinθ,asinθ+bcosθ). Use slices x[0::2] and x[1::2] to handle all pairs at once.

    Show a solution
    def rope(x, pos, base=10000.0):
        d = x.shape[-1]
        freq = 1.0 / base ** (np.arange(0, d, 2) / d)      # one speed per pair
        c, s = np.cos(pos * freq), np.sin(pos * freq)
        x1, x2 = x[0::2], x[1::2]
        out = np.empty_like(x)
        out[0::2], out[1::2] = x1 * c - x2 * s, x1 * s + x2 * c
        return out
    
    rng = np.random.default_rng(0)
    q, k = rng.normal(size=8), rng.normal(size=8)
    for m, n in [(3, 1), (10, 8), (52, 50)]:
        print(m - n, f"{rope(q, m) @ rope(k, n):.6f}")   # 2 -1.763129, three times

    All three lines print the same score, -1.763129, because the rotations of q and k cancel except for the difference. Try (3, 0) as well: a different distance gives a different score.

    Check your understanding

    Without positional information, what happens when you shuffle the tokens fed to self-attention?

    1. The output changes unpredictably
    2. The output is identical, in the original order
    3. The output rows are shuffled the same way, otherwise unchanged
    Attention is permutation-equivariant: it treats the input as a set. The rows follow their tokens, so a shuffle in gives the same shuffle out.

    In the sinusoidal encoding, what distinguishes the first dimension pairs from the last ones?

    1. The first pairs change quickly with position, the last pairs very slowly
    2. The first pairs are learned, the last pairs fixed
    3. The first pairs hold the token, the last pairs the position
    Each pair rotates at its own frequency, from about 1 radian per position down to about 1/10,000. Nothing in the formula is learned, and the token embedding is added on top of all dimensions.

    Why is RoPE popular in modern open models?

    1. It removes the need for attention
    2. Attention scores then depend on the relative distance between tokens, not their absolute positions
    3. It makes the embedding table smaller
    Rotating queries and keys by their positions makes their dot product depend only on the offset. It does not change the embedding table and it works inside attention, not instead of it.

    Lesson 4.5Module 4: Understanding transformers

    Self-attention and multi-head attention

    • ⏱ 17 min read
    • Advanced

    Learning objectives

    • Explain self-attention as "every token takes a weighted average of the tokens it is allowed to see".
    • Write scaled dot-product attention with a causal mask in NumPy and explain each operation, including the dk scaling.
    • Explain why models use several attention heads and implement multi-head attention with reshapes.
    • Recognise common attention patterns found in trained models and the cost of attention for long contexts.

    Self-attention is the heart of the transformer and the only place where tokens share information. In lesson 4.1 it was the "direct link" between any two words; in lesson 4.2 it was the "communicate" step of each block. Now we build it for real. This lesson covers the full mechanism and multi-head attention; lesson 4.6 then slows down on the query, key and value vectors with pictures you can drag.

    Analogy: a library search for every word

    Each token walks into a library where every earlier token has left a book. Each book has a label on the spine (the key) and contents inside (the value). The token carries a search query (the query). It compares its query with every label, gives each book a relevance score, and then, instead of picking one book, reads a blend of all of them, weighted by relevance. Multi-head attention is several librarians searching at once, each for a different kind of thing (one for grammar, one for names, one for "what came right before me"), with their findings combined at the end.

    The idea: a weighted average you can learn

    Take "The cat sat because it was tired". To build a good representation of "it", the model should mix in information from "cat". To represent "tired", it might use "it" and "cat" again. Self-attention gives every token a way to do this: its new vector is a weighted average of vectors from the other tokens, and the weights are computed on the fly from the content of the tokens themselves. Because the weights depend on the input, the same layer can link "it" to "cat" in one sentence and to "mat" in another.

    Four steps, for every token at once:

    1. Project. Multiply each token vector by three learned matrices to get a query q ("what am I looking for?"), a key k ("what do I contain?") and a value v ("what will I hand over?").
    2. Score. Compare each query with every key using a dot product: a big number means a good match. Divide by dk (explained below).
    3. Mask and normalise. In a language model a token may not look at future tokens, so those scores are set to −∞. Softmax then turns each row of scores into positive weights that add up to 1.
    4. Mix. Each token's output is the weighted sum of the value vectors.

    All four steps are matrix operations over the whole sequence, which is the whole formula:

    Attention(Q,K,V)=softmax(QKTdk+M)V

    In words: Q, K and V are matrices with one row per token. Q times K-transposed gives a T × T table of match scores (row = the token asking, column = the token being looked at). Divide by the square root of the key length, add the mask M (0 where allowed, minus infinity where not), apply softmax to each row, and use the resulting weights to average the rows of V.

    The causal mask

    A decoder-only model is trained to predict the next token at every position at the same time (lesson 4.2). If position 3 could look at position 4, it could simply read the answer. The causal mask prevents that: in the T × T score table, every entry above the diagonal is replaced by −∞, and since e−∞=0, those weights become exactly zero after softmax. The first token can only attend to itself, the second to the first two, and so on: the weight table is lower-triangular. Encoder models such as BERT leave the mask out because they are not predicting the next token.

    See attention patterns

    Trained models learn many different attention patterns. Interpretability research (including Anthropic's published work on "induction heads", Olsson et al., 2022) has found heads that reliably look at the previous token, heads that look back at earlier copies of the current token, heads that complete repeated patterns, and heads that park unused attention on the first token. The demo below draws hand-made versions of such patterns plus one head with random untrained weights, so you can see what the weight table looks like. It is an illustration, not the output of a trained model. Click a token on the left to see where it looks.

    Attention pattern explorerInteractive

    Turn the causal mask off and the upper triangle fills in: that is what an encoder's attention can look like. Set sharpness to 0 and every allowed token gets the same weight; raise it and each row approaches a single 1. The induction pattern is the interesting one: for the second "cat", it points at "sat", the token that followed the first "cat". Olsson et al. present evidence that heads like this drive much of a model's ability to continue patterns it has seen earlier in the same context, which is one mechanism behind "in-context learning".

    Scaled dot-product attention in NumPy

    # @run
    # Scaled dot-product self-attention with a causal mask, in plain NumPy.
    # Lesson 4.5 of "How to Build Claude from Scratch".
    import numpy as np
    
    
    def softmax(z, axis=-1):
        z = z - z.max(axis=axis, keepdims=True)            # subtract the max: same result, no overflow
        e = np.exp(z)
        return e / e.sum(axis=axis, keepdims=True)
    
    
    def causal_mask(T):
        """True where a query may NOT look: keys that come after it."""
        return np.triu(np.ones((T, T), dtype=bool), k=1)
    
    
    def attention(Q, K, V, mask=None):
        d_k = Q.shape[-1]
        scores = Q @ K.T / np.sqrt(d_k)                    # (T, T): how well each query matches each key
        if mask is not None:
            scores = np.where(mask, -np.inf, scores)       # forbidden positions get weight exactly 0
        weights = softmax(scores, axis=-1)                 # each row sums to 1
        return weights @ V, weights                        # weighted average of the value vectors
    
    
    rng = np.random.default_rng(0)
    tokens = ["The", "cat", "sat", "down"]
    T, d_model, d_k = len(tokens), 8, 4
    
    X = rng.normal(0, 1, (T, d_model))                     # stand-in for embeddings + positions
    W_q = rng.normal(0, d_model ** -0.5, (d_model, d_k))
    W_k = rng.normal(0, d_model ** -0.5, (d_model, d_k))
    W_v = rng.normal(0, d_model ** -0.5, (d_model, d_k))
    
    Q, K, V = X @ W_q, X @ W_k, X @ W_v                    # (4, 4) each
    out, w = attention(Q, K, V, mask=causal_mask(T))
    
    print("Q, K, V:", Q.shape, K.shape, V.shape, "  output:", out.shape)
    print("\ncausal attention weights (row = query, column = key):")
    print("        " + "".join(f"{t:>7}" for t in tokens))
    for t, row in zip(tokens, w):
        print(f"{t:>7} " + "".join(f"{float(v):7.3f}" for v in row))
    print("row sums:", [round(float(s), 6) for s in w.sum(axis=1)])
    
    # The first token can only attend to itself, so its output is exactly its own value vector
    print("output[0] == V[0]:", bool(np.allclose(out[0], V[0])))
    
    # Why divide by sqrt(d_k)? Dot products of random vectors grow with dimension.
    print("\nwhy scale by sqrt(d_k)?")
    for dk in [4, 64, 512]:
        q = rng.normal(0, 1, (500, 1, dk))                 # 500 random queries
        k = rng.normal(0, 1, (500, 16, dk))                # 16 random keys for each
        dots = (q * k).sum(axis=-1)                        # (500, 16) raw scores
        top_raw = softmax(dots).max(axis=-1).mean()        # average largest weight, unscaled
        top_scaled = softmax(dots / np.sqrt(dk)).max(axis=-1).mean()
        print(f"  d_k={dk:>3}: std of q.k = {dots.std():5.2f} (scaled {(dots / np.sqrt(dk)).std():.2f}),"
              f" mean top weight over 16 keys: raw {top_raw:.3f}, scaled {top_scaled:.3f}")
    1. z = z - z.max(axis=axis, keepdims=True): subtracting the row maximum before exp leaves softmax unchanged mathematically but prevents overflow. With masked rows the maximum is a real score, so the -inf entries become exp(-inf) = 0.
    2. np.triu(np.ones((T, T), dtype=bool), k=1): True strictly above the diagonal, i.e. "key is in the future".
    3. scores = Q @ K.T / np.sqrt(d_k): all query-key dot products in one matrix product, scaled.
    4. np.where(mask, -np.inf, scores): forbidden positions get minus infinity.
    5. weights @ V: each output row is the weighted average of value rows.
    6. Q, K, V = X @ W_q, X @ W_k, X @ W_v: the three projections. The weights here are random; in a trained model they are learned.
    7. The final loop: draws random queries and keys of growing length dk and measures how peaked softmax becomes with and without the scaling.
    Q, K, V: (4, 4) (4, 4) (4, 4)   output: (4, 4)
    
    causal attention weights (row = query, column = key):
                The    cat    sat   down
        The   1.000  0.000  0.000  0.000
        cat   0.607  0.393  0.000  0.000
        sat   0.482  0.161  0.358  0.000
       down   0.190  0.270  0.236  0.305
    row sums: [1.0, 1.0, 1.0, 1.0]
    output[0] == V[0]: True
    
    why scale by sqrt(d_k)?
      d_k=  4: std of q.k =  2.01 (scaled 1.01), mean top weight over 16 keys: raw 0.433, scaled 0.237
      d_k= 64: std of q.k =  7.99 (scaled 1.00), mean top weight over 16 keys: raw 0.847, scaled 0.242
      d_k=512: std of q.k = 22.78 (scaled 1.01), mean top weight over 16 keys: raw 0.942, scaled 0.247

    The weight table is lower-triangular with rows summing to 1, and the first token's output is exactly its own value vector, because it has nothing else to look at. The last block justifies the dk. The dot product of two random vectors with dk unit-variance entries has a standard deviation of about dk (2, 8, 22.6 in the output). Unscaled, at dk=512 the largest of 16 weights averages 0.94: softmax is nearly one-hot from the start, its gradient is close to zero, and learning stalls. Dividing by the square root brings the spread back to about 1 at every size, so the top weight stays near 0.24.

    Multi-head attention

    One attention operation produces one weight table per sentence, so each token can express one "kind" of looking. But a token often needs several things at once: "sat" might want its subject ("cat"), the previous word, and any time expression. Multi-head attention runs several attentions in parallel, each on its own smaller slice of the vector, then concatenates the results and mixes them with one more matrix:

    headi=Attention(XWQi,XWKi,XWVi)MultiHead(X)=Concat(head1,…,headh)WO

    In words: each of the h heads has its own query, key and value projections of width d_model / h and computes its own weight table. Their outputs are glued side by side back to width d_model, and an output matrix W_O lets the heads' findings combine.

    In code, you do not loop over heads. You compute Q, K and V for all heads with one big matrix, reshape (T, d_model) into (n_heads, T, d_head), and let NumPy batch the matrix products over the first axis:

    # @run
    # Multi-head causal self-attention: split d_model into heads, attend in parallel, concatenate, project.
    # Lesson 4.5 of "How to Build Claude from Scratch". Needs only NumPy.
    import numpy as np
    
    
    def softmax(z, axis=-1):
        z = z - z.max(axis=axis, keepdims=True)
        e = np.exp(z)
        return e / e.sum(axis=axis, keepdims=True)
    
    
    def multi_head_attention(x, W_qkv, W_o, n_heads, causal=True):
        T, d_model = x.shape
        d_head = d_model // n_heads
        qkv = x @ W_qkv                                        # (T, 3*d_model): one matmul for Q, K and V
        q, k, v = np.split(qkv, 3, axis=-1)                    # each (T, d_model)
        # (T, d_model) -> (n_heads, T, d_head): every head gets its own slice of the features
        split = lambda m: m.reshape(T, n_heads, d_head).transpose(1, 0, 2)
        q, k, v = split(q), split(k), split(v)
        scores = q @ k.transpose(0, 2, 1) / np.sqrt(d_head)    # (n_heads, T, T)
        if causal:
            scores = np.where(np.triu(np.ones((T, T), bool), 1), -np.inf, scores)
        weights = softmax(scores)                              # (n_heads, T, T)
        heads = weights @ v                                    # (n_heads, T, d_head)
        concat = heads.transpose(1, 0, 2).reshape(T, d_model)  # back to (T, d_model)
        return concat @ W_o, weights                           # mix the heads together
    
    
    rng = np.random.default_rng(0)
    T, d_model, n_heads = 5, 12, 3
    x = rng.normal(0, 1, (T, d_model))
    W_qkv = rng.normal(0, d_model ** -0.5, (d_model, 3 * d_model))
    W_o = rng.normal(0, d_model ** -0.5, (d_model, d_model))
    
    out, w = multi_head_attention(x, W_qkv, W_o, n_heads)
    print(f"x {x.shape} -> {n_heads} heads of size {d_model // n_heads} -> out {out.shape}")
    print("attention weights:", w.shape, "(heads, queries, keys)")
    for h in range(n_heads):
        print(f"head {h}, last query attends to:", np.round(w[h, -1], 3))
    
    # Check: the vectorised version equals a slow loop over heads
    d_head = d_model // n_heads
    q, k, v = np.split(x @ W_qkv, 3, axis=-1)
    mask = np.triu(np.ones((T, T), bool), 1)
    outs = []
    for h in range(n_heads):
        sl = slice(h * d_head, (h + 1) * d_head)
        s = q[:, sl] @ k[:, sl].T / np.sqrt(d_head)
        outs.append(softmax(np.where(mask, -np.inf, s)) @ v[:, sl])
    slow = np.concatenate(outs, axis=1) @ W_o
    print("\nvectorised == loop over heads:", bool(np.allclose(out, slow)))
    
    # Same parameter count as ONE big head: heads split the width, they do not add weights
    params = W_qkv.size + W_o.size
    print(f"parameters: {params} = 4 * d_model^2 = {4 * d_model ** 2} (independent of n_heads)")
    
    # Causality check: changing a future token must not change earlier outputs
    x2 = x.copy()
    x2[-1] += 10.0
    out2, _ = multi_head_attention(x2, W_qkv, W_o, n_heads)
    print("changing the last token leaves outputs 0..3 unchanged:", bool(np.allclose(out[:-1], out2[:-1])))
    1. qkv = x @ W_qkv: one matrix of shape (d_model, 3·d_model) computes queries, keys and values for every head; np.split cuts the result into three.
    2. m.reshape(T, n_heads, d_head).transpose(1, 0, 2): splits the feature axis into heads and moves heads to the front: (3, 5, 4) here.
    3. q @ k.transpose(0, 2, 1): a batched matrix product, giving one (T, T) score table per head.
    4. heads.transpose(1, 0, 2).reshape(T, d_model): undoes the split, concatenating the heads side by side.
    5. concat @ W_o: the output projection mixes information across heads.
    6. The slow loop over heads: recomputes the same result head by head with slices, a check that the reshapes are right.
    7. x2[-1] += 10.0: changes only the last token; the causal mask must leave all earlier outputs untouched.
    x (5, 12) -> 3 heads of size 4 -> out (5, 12)
    attention weights: (3, 5, 5) (heads, queries, keys)
    head 0, last query attends to: [0.26  0.087 0.179 0.29  0.184]
    head 1, last query attends to: [0.102 0.029 0.198 0.522 0.148]
    head 2, last query attends to: [0.269 0.202 0.262 0.142 0.126]
    
    vectorised == loop over heads: True
    parameters: 576 = 4 * d_model^2 = 576 (independent of n_heads)
    changing the last token leaves outputs 0..3 unchanged: True

    Three heads, three different weight rows for the same query, even with random weights. The parameter line deserves attention: 4dmodel2 = 576 whatever the number of heads. Heads do not add parameters; they split the same width into independent pieces, trading one broad view for several narrow ones. GPT-2 small uses 12 heads of size 64 in a width of 768.

    Cost of attention, KV-sharing heads and fused kernels

    Quadratic cost. The score table has T2 entries per head per layer. Doubling the context quadruples that work and, if materialised, that memory. For long contexts this term dominates. FlashAttention (Dao et al., 2022) computes exactly the same result in tiles that fit in the accelerator's fast on-chip memory, never storing the full table, which cuts memory traffic dramatically. It is an implementation trick, not an approximation.

    Sharing keys and values. During generation, every past token's keys and values are cached (lesson 4.9), and that cache, not the weights, often limits how many users or how much context fit on a GPU. Multi-query attention (Shazeer, 2019) gives all heads one shared key/value head; grouped-query attention (Ainslie et al., 2023) shares one key/value head per group of query heads, a middle ground used by many open models. Both shrink the cache by the sharing factor with a small quality cost.

    Approximations. Sliding-window attention (each token sees only the last W tokens in some layers), sparse patterns and linear-attention variants reduce the quadratic cost at some cost in what the model can look up. Which of these techniques Claude uses is not public Not public; all of them appear in published open models Industry practice.

    Interpretability. Because attention weights are explicit numbers, they are tempting to read as explanations. They help, but they are not the whole story: values and the output projection decide what is actually moved, and later layers can override it. Anthropic's interpretability team has published a framework for analysing attention heads as circuits (Elhage et al., 2021) and the induction-head paper cited above, both readable after this module.

    Common mistakes and debugging tips

    Applying softmax along the wrong axis

    Softmax must normalise each query's row (over keys, the last axis). Normalising columns gives weights that do not sum to 1 per token, and the masked zeros end up in the wrong places.

    Fix: use axis=-1 and assert np.allclose(weights.sum(-1), 1) in a test.

    Masking with a large negative number after softmax

    Setting weights to zero after softmax leaves rows that no longer sum to 1, and future information has already leaked into the normalisation.

    Fix: mask the scores with -inf (or a very large negative number in low precision) before softmax.

    Reshaping heads in the wrong order

    q.reshape(n_heads, T, d_head) runs without error but mixes features of different tokens into the same head. Shapes look right, results are nonsense.

    Fix: reshape to (T, n_heads, d_head) first, then transpose. Keep a slow per-head loop as a reference test, as multihead.py does.

    Forgetting the scale factor

    Without dividing by dk, a model with wide heads starts with near one-hot attention and trains slowly or unstably.

    Fix: include the scale, and check the spread of initial scores is around 1.

    Key takeaways

    • Self-attention: each token's output is a softmax-weighted average of value vectors, weighted by query-key matches.
    • The causal mask sets future scores to minus infinity so a decoder can be trained on all positions at once.
    • Scaling by dk keeps softmax from saturating as heads get wider.
    • Multi-head attention splits the width into independent heads; it costs no extra parameters.

    Exercise: a sliding-window mask

    Modify attention.py so each token can see itself and at most the 2 previous tokens (a window of 3). Write window_mask(T, w), run it on the 4-token example, and check: (a) every row still sums to 1, (b) the "down" row has weight exactly 0 on "The".

    Hint

    The mask must be True where the key is in the future or too far in the past. With query index i and key index j: forbidden if j > i or i - j >= w. Build index grids with np.arange(T)[:, None] and np.arange(T)[None, :].

    Show a solution
    def window_mask(T, w):
        i = np.arange(T)[:, None]          # query positions, as a column
        j = np.arange(T)[None, :]          # key positions, as a row
        return (j > i) | (i - j >= w)      # True = not allowed
    
    out, w = attention(Q, K, V, mask=window_mask(T, 3))
    print(np.round(w, 3))
    print("rows sum to 1:", bool(np.allclose(w.sum(axis=1), 1)))
    print("'down' -> 'The':", float(w[3, 0]))   # 0.0

    Rows 0 to 2 are unchanged (their windows already cover everything before them), and row 3 now spreads its weight over "cat", "sat" and "down" only. Real models that use windows usually mix windowed and full-attention layers so information can still travel far, hopping across layers.

    Check your understanding

    What does the causal mask do to the attention weights?

    1. It makes all weights equal
    2. It forces weights on future tokens to exactly zero
    3. It removes the first token
    Future scores are set to minus infinity before softmax, so their weights are exactly 0 and each row still sums to 1 over the allowed keys.

    Why divide the scores by dk?

    1. To make attention faster to compute
    2. To keep the weights positive
    3. Dot products grow with dimension; without scaling, softmax saturates and gradients vanish
    Random dot products have a spread of about the square root of their length. Scaling keeps the scores near unit spread so softmax stays soft at initialisation. Softmax is always positive anyway, and the division does not save time.

    A layer has d_model = 768. How does switching from 12 heads to 24 heads change its attention parameter count?

    1. It does not change; each head just gets a narrower slice (32 instead of 64)
    2. It doubles
    3. It halves
    The Q, K, V and output projections are still d_model × d_model matrices, 4·d² in total. Heads divide that width; they do not add to it.

    Lesson 4.6Module 4: Understanding transformers

    Query, Key and Value explained visually

    • ⏱ 14 min read
    • Intermediate

    Learning objectives

    • Explain the separate roles of the query, key and value vectors and why they come from three different matrices.
    • Read a dot product geometrically: direction decides which key matches, length decides how sharply.
    • Predict attention weights from hand-made Q, K and V matrices, then confirm them in NumPy.
    • Change one weight matrix to change what a token looks for, and explain the result.

    In lesson 4.5 the query, key and value vectors appeared as three projections in a formula. They are worth a lesson of their own, because almost everything interesting a transformer does happens through them, and they are easy to misunderstand. Here we make them small enough to see: two-dimensional arrows you can rotate, and a hand-made example in which every number was chosen by a person rather than learned, so you can predict each result before the code prints it.

    Analogy: a dating app for words

    Every token fills in a profile with two separate parts: "what I am looking for" (the query) and "what I am" (the key). The app compares one token's "looking for" with every other token's "what I am" to score matches. When matched, a token does not share its whole profile, it hands over a message (the value), and the message can be about something else entirely. Keeping the three separate is the point: a pronoun is looking for a noun but is a pronoun, and what a noun hands over (its meaning) is different from the label it is matched on.

    Three roles, three matrices

    Every token starts as one vector xt in the residual stream. Attention projects it three ways:

    qt=xtWQ,kt=xtWK,vt=xtWV

    In words: the same token vector is multiplied by three different learned matrices to produce its query, its key and its value.

    • Query qt: what token t is looking for right now. Only used when t is the one asking.
    • Key ks: how token s advertises itself to askers. Only used when s is being looked at.
    • Value vs: what token s contributes to anyone who attends to it.

    Why not just compare tokens directly, xt·xs? Because then every token would match itself best and similar tokens would match each other, which is the wrong question. "it" should match "cat", not other pronouns. Separate query and key matrices let the model learn asymmetric relationships: what pronouns look for, what verbs look for, what the previous position looks like. And a separate value matrix decides what information travels, independently of how the match was made.

    The geometry of a match

    The score between query q and key k is their dot product, which can be written with lengths and an angle:

    q·k=‖q‖‖k‖cosθ

    In words: the score is large when the two arrows point the same way (θ near 0), zero when they are at right angles, and negative when they point apart. Longer arrows make every score larger in size.

    That gives a clean mental model. The direction of a query picks which keys match. The length of the query sets how decisively: a long query makes the scores far apart, and softmax turns far-apart scores into nearly all-or-nothing weights; a short query makes scores close to each other and the weights nearly even. A model can therefore learn both "look exactly at the subject" and "take a broad average of the context". The demo shows this with 2-D arrows: rotate and stretch the query on the left, and watch the weights and the output on the right.

    Query, keys and values in 2-DInteractive
    Query (thick) vs keys
    Values and the output ◆

    Notice that the output diamond always stays inside the area spanned by the value points: attention can only blend what is there, never invent a value outside it. Also notice that the "mat" key can score high even when you were "aiming" at "cat", if the query is long and the angle in between: matching is soft.

    A hand-made example: who is "it"?

    Now the same thing with real matrices. The sentence is "the cat sat on the mat because it was tired". Instead of learned embeddings, each token gets a hand-made vector with four readable features: animal, object, pronoun, verb. Query and key space have two dimensions, which we also name: animal-ness and object-ness. We then choose the weight matrices so that:

    • WK turns the animal feature into the key "I am an animal" and the object feature into "I am an object";
    • WQ turns the pronoun feature into the query "where is an animal?", with strength 4;
    • WV passes on what the token is (animal or object).

    Before you look at the output, predict: which token will "it" attend to most, roughly how strongly, and what will happen if we change only WQ?

    # @run
    # Query, Key and Value with hand-made numbers: watch the pronoun "it" look up the noun it refers to.
    # Lesson 4.6 of "How to Build Claude from Scratch". Needs only NumPy. No training: every weight is chosen by hand.
    import numpy as np
    
    tokens = ["the", "cat", "sat", "on", "the", "mat", "because", "it", "was", "tired"]
    features = ["animal", "object", "pronoun", "verb"]
    X = np.array([                       # one hand-made 4-feature vector per token
        [0, 0, 0, 0],                    # the
        [1, 0, 0, 0],                    # cat     -> an animal
        [0, 0, 0, 1],                    # sat     -> a verb
        [0, 0, 0, 0],                    # on
        [0, 0, 0, 0],                    # the
        [0, 1, 0, 0],                    # mat     -> an object
        [0, 0, 0, 0],                    # because
        [0, 0, 1, 0],                    # it      -> a pronoun
        [0, 0, 0, 1],                    # was     -> a verb
        [0, 0, 0, 0.5],                  # tired
    ], dtype=float)
    
    # Query space and key space have 2 dimensions: [animal-ness, object-ness]
    W_k = np.array([[1, 0],              # animal feature -> key says "I am an animal"
                    [0, 1],              # object feature -> key says "I am an object"
                    [0, 0],
                    [0, 0]], dtype=float)
    W_q = np.array([[0, 0],
                    [0, 0],
                    [4, 0],              # pronoun feature -> query asks "where is an animal?"
                    [0, 0]], dtype=float)
    W_v = np.array([[1, 0],              # the value passes on what the token IS
                    [0, 1],
                    [0, 0],
                    [0, 0]], dtype=float)
    
    
    def softmax(z):
        z = z - z.max()
        e = np.exp(z)
        return e / e.sum()
    
    
    def attend(i, W_q, W_k, W_v):
        """Causal attention for the single query at position i."""
        q = X[i] @ W_q                   # what token i is looking for
        K = X[: i + 1] @ W_k             # what every earlier token offers as a label
        V = X[: i + 1] @ W_v             # what every earlier token would hand over
        scores = K @ q / np.sqrt(len(q))
        w = softmax(scores)
        return q, scores, w, w @ V
    
    
    def show(title, W_q):
        i = tokens.index("it")
        q, scores, w, out = attend(i, W_q, W_k, W_v)
        print(title)
        print(f"  query of 'it' = {np.round(q, 2)}")
        print(f"  {'key':<9}{'score':>7}{'weight':>8}")
        for t, s, a in zip(tokens[: i + 1], scores, w):
            bar = "#" * int(round(float(a) * 40))
            print(f"  {t:<9}{float(s):7.2f}{float(a):8.3f}  {bar}")
        print(f"  output for 'it' = {np.round(out, 3)}  ([animal, object] information it pulled in)\n")
    
    
    show("1. 'it' asks for an animal", W_q)
    
    W_q_object = W_q.copy()
    W_q_object[2] = [0, 4]               # same token, different question: "where is an object?"
    show("2. change W_q so 'it' asks for an object", W_q_object)
    
    show("3. a weak query (W_q / 4): scores shrink, attention spreads out", W_q / 4)
    
    # Keys only matter through dot products: a key the query never asks about gets score 0
    print("4. the query of 'cat' is zero (it is not a pronoun), so 'cat' attends evenly:")
    _, _, w_cat, _ = attend(tokens.index("cat"), W_q, W_k, W_v)
    print("  weights:", np.round(w_cat, 3))
    1. X = np.array([…]): ten tokens, four hand-made features each. Most tokens are zero vectors, so they offer no key and hand over no value.
    2. W_k: a 4 × 2 matrix. Row 0 (animal) maps to [1, 0], row 1 (object) to [0, 1]. Every other feature produces no key at all.
    3. W_q: only row 2 (pronoun) is non-zero, [4, 0]: pronouns ask strongly for animal-ness. Other tokens produce a zero query.
    4. q = X[i] @ W_q, K = X[: i + 1] @ W_k: the query of token i and the keys of tokens 0..i (the causal mask, written as a slice).
    5. scores = K @ q / np.sqrt(len(q)): one score per visible token, scaled by 2. "cat" scores 4/2≈2.83, everything else 0.
    6. w @ V: the output for "it", a 2-vector of [animal, object] information.
    7. W_q_object[2] = [0, 4]: the same pronoun now asks for object-ness instead; nothing else changes.
    8. W_q / 4: the same direction with a quarter of the length.
    1. 'it' asks for an animal
      query of 'it' = [4. 0.]
      key        score  weight
      the         0.00   0.042  ##
      cat         2.83   0.707  ############################
      sat         0.00   0.042  ##
      on          0.00   0.042  ##
      the         0.00   0.042  ##
      mat         0.00   0.042  ##
      because     0.00   0.042  ##
      it          0.00   0.042  ##
      output for 'it' = [0.707 0.042]  ([animal, object] information it pulled in)
    
    2. change W_q so 'it' asks for an object
      query of 'it' = [0. 4.]
      key        score  weight
      the         0.00   0.042  ##
      cat         0.00   0.042  ##
      sat         0.00   0.042  ##
      on          0.00   0.042  ##
      the         0.00   0.042  ##
      mat         2.83   0.707  ############################
      because     0.00   0.042  ##
      it          0.00   0.042  ##
      output for 'it' = [0.042 0.707]  ([animal, object] information it pulled in)
    
    3. a weak query (W_q / 4): scores shrink, attention spreads out
      query of 'it' = [1. 0.]
      key        score  weight
      the         0.00   0.111  ####
      cat         0.71   0.225  #########
      sat         0.00   0.111  ####
      on          0.00   0.111  ####
      the         0.00   0.111  ####
      mat         0.00   0.111  ####
      because     0.00   0.111  ####
      it          0.00   0.111  ####
      output for 'it' = [0.225 0.111]  ([animal, object] information it pulled in)
    
    4. the query of 'cat' is zero (it is not a pronoun), so 'cat' attends evenly:
      weights: [0.5 0.5]

    Check your predictions. With 8 visible tokens, one scoring 2.83 and seven scoring 0, softmax gives "cat" e2.83/(e2.83+7)≈0.707 and every other token 0.042. The output for "it" is [0.707, 0.042]: after this layer, the vector for "it" carries most of the "animal" signal from "cat". Changing one row of WQ redirects the same token to "mat" (experiment 2): what a token looks for lives entirely in the query weights. Shrinking the query (experiment 3) leaves "cat" as the favourite but with only 0.225 of the weight. And a token with a zero query (experiment 4, "cat" itself) scores every key 0 and simply averages everything it can see.

    Simplified implementation

    Real models learn every one of these numbers, the features are not neatly human-readable (a single direction usually mixes many concepts), heads are 64 to 128 dimensions instead of 2, and resolving "it" usually involves several heads across several layers. The mechanism, though, is exactly this one.

    Where the same trio shows up

    In self-attention all three come from the same sequence. In cross-attention (the encoder-decoder transformer of lesson 4.2, and many image-text models) the queries come from one sequence and the keys and values from another: the translation being written asks questions, and the source sentence answers. And in retrieval systems (module 8) the same pattern appears at a much larger scale: a question embedding is compared with document embeddings by dot product (similarity search), and the best-matching documents' contents are handed to the model. Query, key and value is a general idea: soft, learnable lookup.

    The QK and OV circuits: what the matrices really compute

    Multiply out the score: qt·ks=xtWQWKTxsT. Only the product WQWKT matters, a dmodel×dmodel matrix of rank at most dhead. It decides "which pairs of residual-stream directions attract each other". Similarly, what a head writes back is WVWO (the head's slice of the output projection), deciding "if I attend to a token, what do I copy into my own stream". Anthropic's "mathematical framework for transformer circuits" (Elhage et al., 2021) calls these the QK circuit and the OV circuit. Splitting a head this way is how interpretability researchers identified induction heads: their QK circuit matches "the token after a previous copy of me" and their OV circuit copies that token.

    Two practical consequences. First, the individual matrices are not unique: you can multiply WQ by any invertible matrix and WK by its inverse transpose and get identical behaviour, so do not over-interpret single weights. Second, because each head's QK matrix has low rank, a head can only make a limited number of distinctions, which is one reason models use many heads and many layers.

    Common mistakes and debugging tips

    Thinking the value is the same as the key

    Keys are used only for matching, values only for what gets copied. Using the keys as values (or reusing one matrix for both) ties "how I am found" to "what I give", which removes a lot of flexibility.

    Fix: keep three separate projections (or one fused matrix split three ways, as in multihead.py).

    Reading high attention weight as "important"

    A head can attend strongly to a token whose value vector is nearly zero, which moves almost nothing. Experiment 4 above has even weights but a near-zero effect for most tokens.

    Fix: look at weight times value (what actually arrives), not the weights alone.

    Forgetting that a zero query still produces output

    A zero query gives equal scores, so softmax returns a uniform average, not "no attention". There is no built-in "attend to nothing" option.

    Fix: remember this when reading patterns. Trained models often fake "nothing" by attending to a token with a small value vector, such as the first token ("attention sink").

    Key takeaways

    • Query = what I look for; key = how I am found; value = what I hand over. Three matrices, three roles.
    • Direction of the query chooses the match; its length controls how sharp the weights are.
    • Attention outputs are blends of value vectors; they never leave the space the values span.
    • Changing only WQ changes where a token looks; changing WV changes what it brings back.

    Exercise: make the verb find its subject

    Extend qkv_handmade.py so that the verb "was" attends mostly to "it". Add a third dimension to the query and key space meaning "pronoun-ness": keys get it from the pronoun feature, and verbs query for it with strength 4. Keep W_v as it is. Predict the weight on "it" before running (9 tokens are visible from "was").

    Hint

    Add a column to W_k that is 1 in the pronoun row, and a column to W_q that is 4 in the verb row; np.hstack appends a column. The score for "it" will be 4/3 now that the space has 3 dimensions.

    Show a solution
    W_k3 = np.hstack([W_k, [[0], [0], [1], [0]]])   # new key column: "I am a pronoun"
    W_q3 = np.hstack([W_q, [[0], [0], [0], [4]]])   # verbs now ask: "where is a pronoun?"
    i = tokens.index("was")
    q, scores, w, out = attend(i, W_q3, W_k3, W_v)
    print(np.round(q, 2))                           # [0. 0. 4.]
    for t, a in zip(tokens, w):
        print(f"{t:<8}{float(a):.3f}")              # it 0.557, the other eight 0.055

    The score for "it" is 4/3≈2.31, and e2.31/(e2.31+8)≈0.557. The weight is lower than "it" got for "cat" (0.707) because there are more competitors and the score is divided by a larger square root. Note that "sat", also a verb, finds no pronoun before it and spreads evenly: the same weights do different things in different contexts. The output for "was" is still about zero, since W_v passes on nothing for a pronoun; giving it a meaningful value is a good follow-up.

    Check your understanding

    Which vector of a token is used when other tokens decide whether to attend to it?

    1. Its key
    2. Its query
    3. Its value
    Other tokens compare their queries with this token's key. The value is what they receive once they attend; the query is only used when this token itself is asking.

    You double the length of a query without changing its direction. What happens to that token's attention weights?

    1. Nothing, because softmax normalises
    2. They all double
    3. They become sharper: the best-matching key gets more weight, the others less
    All scores double, which spreads them further apart; softmax of more spread-out scores is more peaked. The weights still sum to 1, so they cannot all double.

    In the hand-made example, what single change made "it" attend to "mat" instead of "cat"?

    1. Changing the embedding of "mat"
    2. Changing the pronoun row of W_Q to ask for object-ness
    3. Changing W_V
    Only the query changed. Keys and values stayed the same; the token asked a different question, so a different key matched.

    Lesson 4.7Module 4: Understanding transformers

    Feed-forward networks

    • ⏱ 13 min read
    • Intermediate

    Learning objectives

    • Describe the feed-forward network (FFN) of a transformer block: expand, apply a non-linearity, compress.
    • Explain what "position-wise" means and prove it in code.
    • Compare ReLU, GELU and SiLU activations and the gated SwiGLU variant used in many modern open models.
    • Estimate what share of a block's parameters the FFN holds, and explain the "key-value memory" view of FFNs.

    Attention moves information between tokens. But moving information is not the same as processing it. After attention has gathered "the subject of this verb is a plural noun about animals" into a token's vector, something has to turn that into useful new features. That is the job of the second sub-layer of every block, the feed-forward network (also called the MLP). It is the simplest part of the transformer, the network you built by hand in module 3, yet it holds most of the parameters.

    Analogy: a moment of private thought

    Back at the meeting from lesson 4.2: attention was the round where everyone listened to each other. The FFN is the moment afterwards when each person looks at their own notes, alone, and checks them against a huge mental index of patterns ("this looks like a date", "this is the start of a Python function", "this is a capital city"). Each matching pattern adds its own extra notes. Nobody talks during this step, so everyone can do it at the same time.

    Expand, switch, compress

    The FFN is two linear layers with a non-linear function between them. The first layer expands each token's vector from d_model numbers to a much wider hidden layer of d_ff numbers, classically dff=4dmodel (2,048 for the original 512-wide transformer, 3,072 for GPT-2 small). The activation function then switches each hidden unit on or off depending on its input. The second layer compresses back to d_model so the result can be added to the residual stream.

    FFN(x)=GELU(xW1+b1)W2+b2

    In words: multiply the token vector by W₁ (d_model × d_ff) and add a bias, apply GELU to every element, then multiply by W₂ (d_ff × d_model) and add another bias.

    d_model d_ff = 4 × d_model d_model W₁: expand W₂: compress on off
    One token through the FFN. The hidden layer is four times wider. After the activation, only some hidden units are "on" (green) for this token; each active unit adds its own row of W₂ to the output.

    Why widen at all? The hidden layer is where the network can represent many separate "detectors" at once. A wide hidden layer means more patterns can be recognised for the same output size. Without the activation function in the middle, the two matrices would collapse into one (a product of linear maps is linear), and the FFN would add nothing a single matrix could not do: the non-linearity is what lets each hidden unit act as an on/off switch.

    "Position-wise": every token alone

    The FFN treats every row of the (T, d_model) matrix independently, with the same weights. Feeding the whole sentence or feeding one token at a time gives exactly the same rows. In code you still run it on the whole matrix at once, because one big matrix multiplication is far faster than T small ones, but logically no information crosses between tokens here. That separation of jobs (attention: communication; FFN: per-token computation) is a clean design that makes both parts easier to reason about.

    Activation functions

    The original transformer used ReLU, max(0,x): a hard switch. GPT-2 and BERT used GELU (Hendrycks and Gimpel, 2016), a smooth version that lets small negative values leak through slightly and has a gradient everywhere:

    GELU(x)=xΦ(x)≈0.5x(1+tanh(2/π(x+0.044715x3)))

    In words: GELU multiplies x by the probability that a standard normal variable is below x. Large positive x passes almost unchanged, large negative x becomes almost 0, and around 0 the curve bends smoothly. The tanh formula is a fast approximation used by GPT-2.

    SiLU (also called Swish), x·σ(x), has a very similar shape. Compare the three curves:

    Activation functionsInteractive

    The differences look small, and they are: the choice of activation changes final quality by modest amounts. What matters more is the next idea, gating.

    Gated FFNs: SwiGLU

    Shazeer (2020) tested "gated linear unit" variants: compute two expansions of the input, apply the activation to one, and multiply them element by element, so one path decides how much of the other passes through. The SiLU version, SwiGLU, is used in many published open models (the Llama family among them):

    FFNSwiGLU(x)=(SiLU(xWgate)⊙xWup)Wdown

    In words: two parallel expansions of x; the "gate" one goes through SiLU and then multiplies the "up" one element by element (⊙); the result is compressed by W_down. Three matrices instead of two.

    With three matrices, the hidden width is usually reduced to about 83dmodel so the parameter count stays about the same as a classic 4dmodel FFN. Whether Claude uses gated FFNs is not public Not public; it is a widespread choice in open models Industry practice.

    The FFN in NumPy

    # @run
    # The position-wise feed-forward network (FFN / MLP) of a transformer block: GELU and SwiGLU versions.
    # Lesson 4.7 of "How to Build Claude from Scratch". Needs only NumPy.
    import numpy as np
    
    
    def gelu(x):
        """GELU, tanh approximation (used by GPT-2)."""
        return 0.5 * x * (1 + np.tanh(np.sqrt(2 / np.pi) * (x + 0.044715 * x ** 3)))
    
    
    def silu(x):
        return x / (1 + np.exp(-x))
    
    
    def ffn_gelu(x, W1, b1, W2, b2):
        h = gelu(x @ W1 + b1)          # (T, d_ff): expand and switch features on or off
        return h @ W2 + b2             # (T, d_model): compress back
    
    
    def ffn_swiglu(x, W_gate, W_up, W_down):
        return (silu(x @ W_gate) * (x @ W_up)) @ W_down   # a gate decides how much of each "up" feature passes
    
    
    rng = np.random.default_rng(0)
    T, d_model = 4, 16
    d_ff = 4 * d_model                                     # the classic expansion factor
    x = rng.normal(0, 1, (T, d_model))
    W1 = rng.normal(0, d_model ** -0.5, (d_model, d_ff)); b1 = np.zeros(d_ff)
    W2 = rng.normal(0, d_ff ** -0.5, (d_ff, d_model)); b2 = np.zeros(d_model)
    
    y = ffn_gelu(x, W1, b1, W2, b2)
    print(f"x {x.shape} -> hidden {(x @ W1).shape} -> y {y.shape}")
    
    # Position-wise: running the FFN on each token alone gives exactly the same rows
    rows = np.stack([ffn_gelu(x[t:t + 1], W1, b1, W2, b2)[0] for t in range(T)])
    print("whole sequence == token by token:", bool(np.allclose(y, rows)))
    
    # Changing token 0 changes only output row 0 (no mixing between tokens here)
    x2 = x.copy(); x2[0] += 1.0
    diff = np.abs(ffn_gelu(x2, W1, b1, W2, b2) - y).sum(axis=1)
    print("rows changed after editing token 0:", [bool(v > 1e-12) for v in diff])
    
    print("\nactivation values at x = -3 .. 3")
    for v in [-3.0, -1.0, -0.5, 0.0, 0.5, 1.0, 3.0]:
        print(f"  x={v:5.1f}  relu={max(v, 0.0):6.3f}  gelu={float(gelu(v)):6.3f}  silu={float(silu(v)):6.3f}")
    
    # SwiGLU uses three matrices, so d_ff is usually shrunk to about 8/3 * d_model to keep the parameter count
    d_sw = int(8 * d_model / 3)
    W_gate = rng.normal(0, d_model ** -0.5, (d_model, d_sw))
    W_up = rng.normal(0, d_model ** -0.5, (d_model, d_sw))
    W_down = rng.normal(0, d_sw ** -0.5, (d_sw, d_model))
    print("\nSwiGLU output:", ffn_swiglu(x, W_gate, W_up, W_down).shape)
    p_gelu = W1.size + b1.size + W2.size + b2.size
    p_sw = W_gate.size + W_up.size + W_down.size
    print(f"parameters: GELU FFN (d_ff={d_ff}) {p_gelu:,}   SwiGLU FFN (d_ff={d_sw}) {p_sw:,}")
    
    # Share of a block's weights: attention has 4*d^2, the FFN 8*d^2
    d = 768
    attn, ffn = 4 * d * d, 2 * d * 4 * d
    print(f"\nGPT-2 small block (d={d}): attention {attn:,} weights, FFN {ffn:,} weights -> FFN share {ffn / (attn + ffn):.0%}")
    1. gelu(x): the tanh approximation from the equation above, applied to every element.
    2. silu(x): x * sigmoid(x), written as x / (1 + exp(-x)).
    3. h = gelu(x @ W1 + b1): expand from 16 to 64 numbers per token and switch.
    4. return h @ W2 + b2: compress back to 16.
    5. (silu(x @ W_gate) * (x @ W_up)) @ W_down: the gated variant in one line.
    6. rows = np.stack([ffn_gelu(x[t:t + 1], …)[0] …]): runs the FFN one token at a time and compares with the whole-sequence result: identical, so the FFN is position-wise.
    7. x2[0] += 1.0: changing token 0 changes only output row 0.
    8. d_sw = int(8 * d_model / 3): the narrower hidden width that keeps SwiGLU's parameter count comparable.
    9. attn, ffn = 4 * d * d, 2 * d * 4 * d: weight counts of one GPT-2-small block's two sub-layers.
    x (4, 16) -> hidden (4, 64) -> y (4, 16)
    whole sequence == token by token: True
    rows changed after editing token 0: [True, False, False, False]
    
    activation values at x = -3 .. 3
      x= -3.0  relu= 0.000  gelu=-0.004  silu=-0.142
      x= -1.0  relu= 0.000  gelu=-0.159  silu=-0.269
      x= -0.5  relu= 0.000  gelu=-0.154  silu=-0.189
      x=  0.0  relu= 0.000  gelu= 0.000  silu= 0.000
      x=  0.5  relu= 0.500  gelu= 0.346  silu= 0.311
      x=  1.0  relu= 1.000  gelu= 0.841  silu= 0.731
      x=  3.0  relu= 3.000  gelu= 2.996  silu= 2.858
    
    SwiGLU output: (4, 16)
    parameters: GELU FFN (d_ff=64) 2,128   SwiGLU FFN (d_ff=42) 2,016
    
    GPT-2 small block (d=768): attention 2,359,296 weights, FFN 4,718,592 weights -> FFN share 67%

    The table of activation values matches the demo: GELU dips slightly below zero (minimum around −0.17 near x = −0.75), SiLU dips further (about −0.28 near x = −1.28), and both approach ReLU for large positive x. SwiGLU with a hidden width of 42 has 2,016 weights, close to the 2,128 of the GELU FFN with width 64. The last line is the headline: in a standard block, the FFN holds about two thirds of the weights (8d² vs 4d²).

    What do FFNs learn?

    One useful way to read an FFN (Geva et al., 2020): each hidden unit has an input pattern, its column of W1 (a "key"), and an output pattern, its row of W2 (a "value"). When the token vector resembles the key, the unit switches on and adds its value to the residual stream. So an FFN behaves like a large soft lookup table, with thousands of entries per layer. Studies of trained models find units and directions that respond to recognisable things (particular word endings, topics, code syntax), and editing them can change facts the model states. This is part of why people say factual knowledge lives largely in FFN weights, although in practice knowledge is spread across many units and layers, and a single unit usually responds to several unrelated things (Anthropic's interpretability research calls this superposition).

    Mixture of experts: many FFNs, few used per token

    Because the FFN is position-wise, it can be replaced by several FFNs ("experts") plus a small router that picks, for each token, the top 1 or 2 experts by score. Total parameters grow with the number of experts, but compute per token grows only with the number of experts actually used. Published examples include the Switch Transformer (Fedus et al., 2021) and the open-weight Mixtral models, which route each token to 2 of 8 experts. Training MoE models needs extra care: a load-balancing loss so tokens do not all crowd onto one expert, capacity limits, and communication between accelerators that hold different experts.

    MoE is a common way to scale Industry practice. Anthropic has not said whether Claude models use it Not public. The exercise below builds a tiny top-1 router so you can see the idea in a dozen lines.

    One more practical note: during generation, the FFN's cost per token is fixed (it does not grow with context), while attention's cost grows with the number of cached tokens. For short prompts the FFN dominates compute; for very long contexts attention does.

    Common mistakes and debugging tips

    Leaving out the activation

    (x @ W1) @ W2 is just x @ (W1 @ W2), a single linear map. The model loses most of its ability to compute new features, and nothing errors.

    Fix: check that an activation sits between the two matrices; a quick test is that ffn(2 * x) != 2 * ffn(x) (a linear map would scale exactly).

    Using the wrong initial scale for W₂

    W₂ has d_ff inputs, four times more than W₁. Initialising both with the same standard deviation makes the FFN's output too large and destabilises early training.

    Fix: scale initial weights by about 1/fan_in, as ffn.py does with d_ff ** -0.5. GPT-2 also scales the output projections of residual branches down by the depth.

    Mixing up GELU formulas between training and inference

    The exact GELU (using the error function) and the tanh approximation differ by up to about 0.0005 (in absolute terms), which is enough to break bit-exact tests and slightly change outputs of converted models.

    Fix: use the same formula the model was trained with; libraries usually let you choose (for example an "approximate" option).

    Key takeaways

    • The FFN expands each token to a wider hidden layer, applies a non-linearity, and compresses back.
    • It is position-wise: no information crosses between tokens in this sub-layer.
    • It holds about two thirds of a standard block's weights; gated variants like SwiGLU are common in open models.
    • Hidden units act like soft key-value memories, which is one reason knowledge is said to live in FFN weights.

    Exercise: a tiny mixture of experts

    Using the functions and the input x from ffn.py, build 4 GELU FFNs ("experts") and a router matrix W_router of shape (d_model, 4). Write moe_top1(x) that sends each token to the single expert with the highest router score and returns the outputs and the chosen expert per token. Check the output shape is still (4, 16).

    Hint

    np.argmax(x @ W_router, axis=-1) gives one expert index per token. Then, for each expert, select the rows that chose it with a boolean mask and run only those rows through that expert's FFN. Position-wise is what makes this legal.

    Show a solution
    n_exp = 4
    experts = [(rng.normal(0, d_model ** -0.5, (d_model, d_ff)), np.zeros(d_ff),
                rng.normal(0, d_ff ** -0.5, (d_ff, d_model)), np.zeros(d_model)) for _ in range(n_exp)]
    W_router = rng.normal(0, d_model ** -0.5, (d_model, n_exp))
    
    def moe_top1(x):
        choice = np.argmax(x @ W_router, axis=-1)        # one expert per token
        out = np.zeros_like(x)
        for e in range(n_exp):
            rows = choice == e
            if rows.any():
                out[rows] = ffn_gelu(x[rows], *experts[e])
        return out, choice
    
    out, choice = moe_top1(x)
    print(out.shape, choice.tolist())                    # (4, 16) and one expert id per token

    Inserted right after the weight setup in ffn.py (before y = ffn_gelu(…)), this printed (4, 16) [2, 1, 3, 3] for us; your expert ids depend on where in the script you draw the random weights. Four times the FFN parameters, but each token used only one expert's worth of compute. A real MoE also multiplies each output by the router's softmax probability so the router gets a gradient, and adds a load-balancing loss.

    Check your understanding

    What does "position-wise" mean for the FFN?

    1. It only runs on the last position
    2. It adds positional encodings
    3. It applies the same function to each token's vector independently
    Every row goes through the same two layers on its own, so outputs for one token never depend on other tokens. Mixing across positions is attention's job.

    In a standard block with d_ff = 4·d_model, roughly what share of the weights is in the FFN?

    1. About two thirds
    2. About one tenth
    3. About one half
    Attention has 4d² weights; the FFN has 2·d·4d = 8d². So 8 / 12 ≈ 67 %, as ffn.py prints for GPT-2 small.

    Why must there be a non-linear activation between W₁ and W₂?

    1. To keep the values positive
    2. Without it the two matrices collapse into one linear map, adding no new expressive power
    3. To normalise the output
    A product of linear maps is linear. GELU and SiLU are not even always positive, and normalisation is LayerNorm's job.

    Lesson 4.8Module 4: Understanding transformers

    Layer normalization and residual connections

    • ⏱ 13 min read
    • Advanced

    Learning objectives

    • Compute LayerNorm and RMSNorm by hand and explain what each normalises and what it leaves alone.
    • Explain why residual connections keep gradients flowing through dozens of layers.
    • Run a 48-layer experiment that shows plain stacks vanishing, residual stacks exploding, and pre-norm residual stacks staying healthy.
    • Contrast post-norm and pre-norm transformers and say why large models use pre-norm.

    Everything so far would work in a model with two or three blocks. Real language models stack dozens of blocks, and naive deep stacks are notoriously hard to train: signals shrink or blow up as they pass through layer after layer, exactly the problem RNNs had through time in lesson 4.1, but now through depth. Two small ingredients solve it, and they appear twice in every block: normalisation and the residual connection. Neither is glamorous. Without them, the transformer would not scale.

    Analogy: a shared document with tracked suggestions

    Imagine forty editors improving one document in turn. If each editor had to retype the whole document in their own words, after forty rounds the original would be unrecognisable and one bad editor could destroy it. Instead, each editor only adds suggestions on top of the existing text (the residual connection), so the original always survives and a bad suggestion can simply be small. Before reading, each editor also zooms the page to a standard size, whether the text has grown huge or tiny (normalisation), so nobody is confused by the scale.

    Layer normalisation

    As vectors pass through many layers, their scale drifts. One token's vector might have numbers around 100, another's around 0.01. A sub-layer that receives inputs of wildly varying scale learns slowly, because the same weights produce outputs of wildly varying size. Layer normalisation (Ba, Kiros and Hinton, 2016) fixes the scale right before each sub-layer reads its input. For each token separately, it subtracts the mean of that token's features and divides by their standard deviation, then applies a learned scale and shift:

    LayerNorm(x)=γ⊙x−μσ2+ε+β,μ=1d∑j=1dxj,σ2=1d∑j=1d(xj−μ)2

    In words: for one token's vector of d numbers, compute their mean μ and variance σ². Subtract the mean, divide by the standard deviation (ε is a tiny number such as 0.00001 to avoid dividing by zero), then multiply each feature by a learned gain γ and add a learned bias β.

    After normalisation every token's vector has mean 0 and standard deviation 1 (before γ and β), whatever happened in earlier layers. The learned γ and β let the network choose a different scale per feature if that helps, so no expressive power is lost. Note the direction of normalisation: across the features of one token, not across a batch of examples. That is the difference from batch normalisation, which you may have met in image models, and it means LayerNorm behaves identically during training and generation, for any batch size, even one token.

    RMSNorm: the simpler cousin

    RMSNorm (Zhang and Sennrich, 2019) drops the mean subtraction and the bias. It only divides by the root-mean-square of the features:

    RMSNorm(x)=γ⊙x1d∑j=1dxj2+ε

    In words: divide the vector by the square root of the mean of its squared entries, so its root-mean-square becomes 1, then multiply by a learned gain. The mean is not removed.

    It is slightly cheaper and in practice works about as well, which is why many recent open models use it Industry practice. What Claude uses is not public Not public.

    Residual connections

    The residual connection (He et al., 2015, from image recognition) is a single plus sign: instead of x←f(x), a layer computes x←x+f(x). The layer learns a change to its input rather than a replacement. Two things follow. First, a layer that has nothing useful to add can learn f≈0 and pass its input through unchanged, so extra layers can never make things much worse at the start of training. Second, and more important, look at the derivative:

    ∂(x+f(x))∂x=I+∂f∂x

    In words: the gradient through a residual layer is the identity matrix plus the layer's own Jacobian. Even if the layer's Jacobian is tiny, the identity carries the gradient through unchanged.

    Multiply 48 of these together and, unlike the RNN's product of 48 Jacobians, there is always a direct path from the loss to the earliest layer. This is the same "add, don't transform" idea as the LSTM cell state in lesson 4.1. In transformer language, the running vector x is called the residual stream: every attention layer and FFN reads from it (through a norm) and writes an update back into it, and the stream itself is never overwritten.

    See it: a 48-layer stack

    The demo runs a stack of random layers f(h)=Wrelu(h) on a 32-number vector, in three arrangements, and plots the spread (standard deviation) of the activations after each layer on a log scale. Green band: the healthy range from 0.3 to 3; dashed grey lines show the other two arrangements for comparison.

    Deep stack: plain vs residual vs pre-normInteractive

    The JavaScript demo uses its own random numbers, so values differ from the Python run below, but the shapes of the curves are the same: plain collapses towards zero, residual grows steadily, pre-norm residual stays within a small factor of 1.

    LayerNorm, RMSNorm and the stack in NumPy

    # @run
    # LayerNorm, RMSNorm and residual connections: why deep stacks of layers stay trainable.
    # Lesson 4.8 of "How to Build Claude from Scratch". Needs only NumPy.
    import numpy as np
    
    
    def layer_norm(x, gamma, beta, eps=1e-5):
        mu = x.mean(axis=-1, keepdims=True)                # per token: mean over its features
        var = x.var(axis=-1, keepdims=True)
        return gamma * (x - mu) / np.sqrt(var + eps) + beta
    
    
    def rms_norm(x, gamma, eps=1e-6):
        rms = np.sqrt((x ** 2).mean(axis=-1, keepdims=True) + eps)
        return gamma * x / rms                             # no mean subtraction, no beta
    
    
    rng = np.random.default_rng(0)
    T, d = 3, 8
    x = rng.normal(5, 20, (T, d))                          # badly scaled activations
    g, b = np.ones(d), np.zeros(d)
    
    ln, rn = layer_norm(x, g, b), rms_norm(x, g)
    print("per-token statistics (mean, std):")
    for name, a in [("input", x), ("LayerNorm", ln), ("RMSNorm", rn)]:
        stats = "  ".join(f"({round(float(m), 2) + 0.0:6.2f}, {float(s):5.2f})" for m, s in zip(a.mean(1), a.std(1)))
        print(f"  {name:<10} {stats}")
    print("RMSNorm output: root-mean-square per token =", np.round(np.sqrt((rn ** 2).mean(1)), 3))
    
    # Scale invariance: multiplying a token by 1000 does not change the normalised output
    print("\nLayerNorm(1000 * x) == LayerNorm(x):", bool(np.allclose(layer_norm(1000 * x, g, b), ln)))
    print("RMSNorm(1000 * x) == RMSNorm(x):    ", bool(np.allclose(rms_norm(1000 * x, g), rn)))
    print("LayerNorm(x + 7) == LayerNorm(x):   ", bool(np.allclose(layer_norm(x + 7, g, b), ln)))
    print("RMSNorm(x + 7) == RMSNorm(x):       ", bool(np.allclose(rms_norm(x + 7, g), rn)))
    
    # Deep stack experiment: 48 random layers f(x) = W @ relu(x)
    L, d = 48, 64
    Ws = [rng.normal(0, 1.0 / np.sqrt(d), (d, d)) for _ in range(L)]
    x0 = rng.normal(0, 1, d)
    f = lambda W, h: W @ np.maximum(h, 0)
    
    
    def run(mode):
        h, stds = x0.copy(), []
        for W in Ws:
            if mode == "plain":
                h = f(W, h)                                # no shortcut
            elif mode == "residual":
                h = h + f(W, h)                            # shortcut, no norm
            else:
                n = h / np.sqrt((h ** 2).mean() + 1e-6)    # pre-norm (RMS) ...
                h = h + 0.5 * f(W, n)                      # ... then add back to the stream
            stds.append(float(h.std()))
        return stds
    
    
    print("\nactivation std after layer:   1        8       16       32       48")
    for mode in ["plain", "residual", "pre-norm + residual"]:
        s = run(mode)
        print(f"  {mode:<21}" + "".join(f"{s[i]:9.2e}" for i in [0, 7, 15, 31, 47]))
    
    # Gradient through a residual block: d(x + f(x))/dx = I + df/dx, so there is always a direct path
    W = Ws[0]
    J_plain = W * (x0 > 0)                                 # Jacobian of W @ relu(x)
    J_res = np.eye(d) + J_plain
    print(f"\nsmallest singular value of the Jacobian: plain {np.linalg.svd(J_plain, compute_uv=False).min():.3f},"
          f" residual {np.linalg.svd(J_res, compute_uv=False).min():.3f}")
    1. mu = x.mean(axis=-1, keepdims=True): the mean over the last axis, i.e. over each token's features. keepdims keeps a (T, 1) shape so it broadcasts back over the row.
    2. gamma * (x - mu) / np.sqrt(var + eps) + beta: LayerNorm exactly as in the equation.
    3. rms = np.sqrt((x ** 2).mean(axis=-1, keepdims=True) + eps): RMSNorm's only statistic.
    4. x = rng.normal(5, 20, (T, d)): deliberately badly scaled input, mean 5 and spread 20.
    5. round(float(m), 2) + 0.0: a formatting detail. It turns a tiny negative mean like -0.0000001 into 0.00 instead of -0.00, so the output is identical on every machine.
    6. layer_norm(1000 * x, g, b) and layer_norm(x + 7, g, b): invariance checks. LayerNorm ignores both scaling and shifting; RMSNorm ignores scaling only.
    7. Ws = [rng.normal(0, 1.0 / np.sqrt(d), (d, d)) …]: 48 random layers with the usual 1/d scale.
    8. h = h + 0.5 * f(W, n): the pre-norm residual update. The 0.5 stands in for the small initial scale that real models give the output projections of each branch.
    9. J_res = np.eye(d) + J_plain: the Jacobian of one residual layer, identity plus the layer's own.
    per-token statistics (mean, std):
      input      ( 12.04, 11.13)  (-12.68, 13.74)  (  8.79, 13.81)
      LayerNorm  (  0.00,  1.00)  (  0.00,  1.00)  (  0.00,  1.00)
      RMSNorm    (  0.73,  0.68)  ( -0.68,  0.73)  (  0.54,  0.84)
    RMSNorm output: root-mean-square per token = [1. 1. 1.]
    
    LayerNorm(1000 * x) == LayerNorm(x): True
    RMSNorm(1000 * x) == RMSNorm(x):     True
    LayerNorm(x + 7) == LayerNorm(x):    True
    RMSNorm(x + 7) == RMSNorm(x):        False
    
    activation std after layer:   1        8       16       32       48
      plain                 5.32e-01 2.28e-02 9.52e-04 8.65e-07 2.72e-09
      residual              9.34e-01 3.40e+00 1.29e+01 1.86e+02 4.54e+03
      pre-norm + residual   8.60e-01 1.23e+00 1.37e+00 2.27e+00 2.71e+00
    
    smallest singular value of the Jacobian: plain 0.000, residual 0.190

    Read it top to bottom. LayerNorm turns every token into mean 0, standard deviation 1. RMSNorm leaves a non-zero mean but sets the root-mean-square to exactly 1. The invariance checks confirm that only LayerNorm ignores a shift. In the stack, plain layers lose half their signal at each ReLU and collapse to 3e-09 after 48 layers; residual layers keep adding and grow to 4.5e+03; pre-norm residual layers stay between 0.86 and 2.71. The last line shows the gradient side: the plain layer's Jacobian has a singular value of 0 (ReLU zeroed some inputs, so some directions are lost completely), while the residual version's smallest singular value is 0.19: no direction is ever fully blocked.

    Post-norm, pre-norm and training stability at scale

    The original transformer normalised after the addition, x←LN(x+f(x)). That keeps the stream's scale perfectly controlled, but every normalisation sits on the residual path, so the gradient is rescaled at every layer, and the path is no longer a clean identity. Xiong et al. (2020) showed that post-norm transformers have large gradients near the output at initialisation, which is why they need a learning-rate warm-up and become fragile when deep. Pre-norm, x←x+f(LN(x)), keeps the path clean, at the price that the stream's scale can grow with depth, which is why a final LayerNorm is added before the LM head. Most large published models use pre-norm.

    Other stabilisers used in published large-model training include: scaling the initial weights of each branch's output projection by 1/2L (GPT-2), normalising queries and keys before the dot product ("QK-norm"), gradient clipping, and keeping normalisation statistics in 32-bit precision even when the rest runs in 16-bit or 8-bit formats. Loss spikes in large training runs are a well-known practical problem and much of the published engineering is about avoiding them. Which of these Anthropic uses is not public Not public.

    The residual-stream view also matters for interpretability: since every layer only adds to the stream, the final vector is literally the embedding plus the sum of every attention head's and every FFN's output. Researchers can therefore ask how much each component contributed to a prediction, which is much harder in architectures that overwrite their state.

    Common mistakes and debugging tips

    Normalising over the wrong axis

    x.mean(axis=0) averages over tokens instead of features. The code runs, but information leaks between positions (breaking causality) and results depend on sequence length.

    Fix: always normalise over the last axis with keepdims=True, and test that the output for token 0 is unchanged when you append more tokens.

    Forgetting the final LayerNorm in a pre-norm model

    In a pre-norm stack the residual stream is never normalised in place, so its scale grows with depth. Feeding it straight to the LM head gives overconfident, badly scaled logits.

    Fix: add one LayerNorm after the last block, as transformer.py does.

    Dropping epsilon or using it in the wrong place

    Without ε, a token whose features are all equal (possible with padding or at initialisation) divides by zero and produces NaNs that spread through the whole batch.

    Fix: add ε inside the square root, and if you see NaNs, check norms first: print the minimum variance per token.

    Initialising γ to zero

    A zero gain makes every normalised output zero, so the sub-layer sees nothing and, in a plain stack, gradients cannot flow.

    Fix: initialise γ to ones and β to zeros, as in init_params.

    Key takeaways

    • LayerNorm rescales each token's features to mean 0 and standard deviation 1; RMSNorm only fixes the root-mean-square.
    • Residual connections add a learned update to an unchanged stream; their Jacobian is identity plus a correction.
    • Plain deep stacks vanish, plain residual stacks drift upward, pre-norm residual stacks stay healthy.
    • Large transformers use pre-norm plus a final norm; the exact recipe of any frontier model is not public.

    Exercise: add a post-norm stack

    Add a fourth mode, "post-norm", to run() in layernorm.py: compute h = h + f(W, h), then normalise h with the same RMS normalisation. Add it to the list of modes and run. What happens to the activation spread, and why is that not enough to conclude post-norm is the best arrangement?

    Hint

    Insert an elif mode == "post-norm": branch before elif mode == "residual":. Then think about the gradient, not the forward pass: where does the normalisation sit relative to the shortcut path?

    Show a solution
            elif mode == "post-norm":
                h = h + f(W, h)
                h = h / np.sqrt((h ** 2).mean() + 1e-6)   # normalise ON the residual path

    With for mode in ["plain", "residual", "pre-norm + residual", "post-norm"]: the new row reads 9.98e-01 1.00e+00 9.99e-01 1.00e+00 1.00e+00: perfectly controlled, by construction. But the forward spread is only half the story. In post-norm, every layer's normalisation divides the gradient on the shortcut path by the stream's current scale, so the path from the loss to early layers is a product of 48 rescalings rather than a clean identity. That is what makes deep post-norm transformers need careful warm-up, and why pre-norm (with a final norm) became standard for large models.

    Check your understanding

    LayerNorm in a transformer computes its mean and variance over…

    1. all tokens in the batch, per feature
    2. the features of each token separately
    3. all layers of the model
    It normalises each token's vector across its own features. Normalising over the batch is batch normalisation, which transformers generally avoid.

    Why do residual connections help gradients reach early layers?

    1. The Jacobian of x + f(x) is I + ∂f/∂x, so there is always an identity path
    2. They make every layer's weights smaller
    3. They remove the need for backpropagation
    The identity term carries the gradient through unchanged even when the layer's own Jacobian is tiny. Weights are not shrunk, and training still uses backpropagation.

    What does RMSNorm leave out compared with LayerNorm?

    1. The learned gain γ
    2. The division by a scale statistic
    3. The mean subtraction (and the bias β)
    RMSNorm only divides by the root-mean-square and multiplies by γ. That is why the script shows RMSNorm(x + 7) ≠ RMSNorm(x) while LayerNorm is shift-invariant.

    Lesson 4.9Module 4: Understanding transformers

    Implement a simplified transformer in NumPy

    • ⏱ 22 min read
    • Advanced

    Learning objectives

    • Assemble embeddings, positional encoding, multi-head causal attention, FFN, LayerNorm and residuals into a complete decoder-only transformer.
    • Run a forward pass, read its output shapes and next-token probabilities, and test causality.
    • Count the parameters with a closed-form formula and check it against GPT-2's published size.
    • Add a KV cache for fast generation and prove it gives identical logits (mini-project).

    Every piece is built. In this lesson they come together into one file, transformer.py, a complete GPT-style forward pass in about 120 lines of NumPy. It has random weights, so its predictions are meaningless; training it is the job of module 5. But every matrix multiplication, mask and normalisation is the real thing, and you will be able to point at any line and say which lesson it came from. At the end, the mini-project adds the optimisation that makes generation practical: the KV cache.

    Analogy: building an engine on a workbench

    Over the last eight lessons we machined the parts one by one: pistons, valves, the crankshaft. Today we bolt them together on the workbench and turn the crank by hand. It runs, every part moves as it should, and you can watch each one. It is not a car yet: there is no fuel (training data) and no tuning (learned weights), and a production engine is thousands of times bigger and built with very different tools. But it is the same kind of engine.

    Simplified implementation Simplified

    This model has 26,016 parameters, 2 blocks, a 17-word vocabulary and random weights. It processes one sequence at a time (no batch dimension), in 64-bit floats on a CPU, with no dropout, no training and no attention optimisations. Frontier models such as Claude are vastly larger; their exact size and architecture are not public, and they are trained on accelerator clusters with very different software. Nothing here is comparable to Claude in capability. What is the same is the core computation of a decoder-only transformer, which is what this module set out to teach.

    Where each piece comes from

    Function in transformer.pyWhat it doesLesson
    params["tok_emb"][ids]Embedding lookup4.3
    sinusoidal_positionsPosition information4.4
    causal_self_attentionMulti-head causal attention with Q, K, V4.5, 4.6
    ffn, geluPosition-wise feed-forward network4.7
    layer_norm, x = x + …Normalisation and residual stream4.8
    block, forwardThe stack and the LM head4.2

    The complete model

    Read it from the bottom up if you like: the script at the end builds parameters, runs the forward pass with a shape trace, prints the next-token distribution, checks causality and counts parameters. Press ▶ Run to execute it in your browser, or run it locally with python transformer.py (only NumPy needed).

    # @run
    # A simplified decoder-only (GPT-style) transformer, forward pass only, in plain NumPy.
    # Lesson 4.9 of "How to Build Claude from Scratch". Random weights: no training, no KV cache.
    import numpy as np
    
    VOCAB = ["<unk>", "the", "a", "cat", "dog", "bird", "sat", "ran", "slept", "on", "under",
             "mat", "log", "tree", "and", "quietly", "."]
    CFG = dict(vocab_size=len(VOCAB), d_model=32, n_heads=4, n_layers=2, d_ff=128, max_len=64)
    
    
    # ---------- building blocks (each one was a lesson in this module) ----------
    def softmax(z, axis=-1):
        z = z - z.max(axis=axis, keepdims=True)
        e = np.exp(z)
        return e / e.sum(axis=axis, keepdims=True)
    
    
    def layer_norm(x, g, b, eps=1e-5):
        mu, var = x.mean(-1, keepdims=True), x.var(-1, keepdims=True)
        return g * (x - mu) / np.sqrt(var + eps) + b
    
    
    def gelu(x):
        return 0.5 * x * (1 + np.tanh(np.sqrt(2 / np.pi) * (x + 0.044715 * x ** 3)))
    
    
    def sinusoidal_positions(T, d):
        pos, i = np.arange(T)[:, None], np.arange(d // 2)[None, :]
        ang = pos / 10000 ** (2 * i / d)
        pe = np.zeros((T, d))
        pe[:, 0::2], pe[:, 1::2] = np.sin(ang), np.cos(ang)
        return pe
    
    
    def causal_self_attention(x, p, n_heads):
        T, d = x.shape
        hd = d // n_heads
        q, k, v = np.split(x @ p["W_qkv"] + p["b_qkv"], 3, axis=-1)
        q, k, v = (m.reshape(T, n_heads, hd).transpose(1, 0, 2) for m in (q, k, v))   # (h, T, hd)
        scores = q @ k.transpose(0, 2, 1) / np.sqrt(hd)                                # (h, T, T)
        scores = np.where(np.triu(np.ones((T, T), bool), 1), -np.inf, scores)          # no peeking ahead
        out = softmax(scores) @ v                                                      # (h, T, hd)
        return out.transpose(1, 0, 2).reshape(T, d) @ p["W_o"] + p["b_o"]
    
    
    def ffn(x, p):
        return gelu(x @ p["W1"] + p["b1"]) @ p["W2"] + p["b2"]
    
    
    def block(x, p, cfg):
        x = x + causal_self_attention(layer_norm(x, p["ln1_g"], p["ln1_b"]), p, cfg["n_heads"])  # pre-norm
        x = x + ffn(layer_norm(x, p["ln2_g"], p["ln2_b"]), p)
        return x
    
    
    # ---------- parameters ----------
    def init_params(cfg, rng):
        d, f, V = cfg["d_model"], cfg["d_ff"], cfg["vocab_size"]
        n = lambda *shape: rng.normal(0, 0.02, shape)               # GPT-2 style small init
        blocks = [dict(ln1_g=np.ones(d), ln1_b=np.zeros(d),
                       W_qkv=n(d, 3 * d), b_qkv=np.zeros(3 * d), W_o=n(d, d), b_o=np.zeros(d),
                       ln2_g=np.ones(d), ln2_b=np.zeros(d),
                       W1=n(d, f), b1=np.zeros(f), W2=n(f, d), b2=np.zeros(d))
                  for _ in range(cfg["n_layers"])]
        return dict(tok_emb=n(V, d), blocks=blocks, lnf_g=np.ones(d), lnf_b=np.zeros(d))
    
    
    def count_params(cfg, learned_positions=False, tied_head=True):
        """Closed-form parameter count for this architecture (LayerNorms with gain and bias, biases everywhere)."""
        d, f, V, L = cfg["d_model"], cfg["d_ff"], cfg["vocab_size"], cfg["n_layers"]
        per_block = (2 * d                       # LayerNorm 1
                     + d * 3 * d + 3 * d         # Q, K, V projections
                     + d * d + d                 # output projection
                     + 2 * d                     # LayerNorm 2
                     + d * f + f + f * d + d)    # FFN
        total = V * d + L * per_block + 2 * d    # embeddings + blocks + final LayerNorm
        if learned_positions:
            total += cfg["max_len"] * d
        if not tied_head:
            total += d * V
        return total
    
    
    def actual_params(params):
        arrays = [params["tok_emb"], params["lnf_g"], params["lnf_b"]] + [a for b in params["blocks"] for a in b.values()]
        return sum(a.size for a in arrays)
    
    
    # ---------- forward pass ----------
    def forward(ids, params, cfg, verbose=False):
        T, d = len(ids), cfg["d_model"]
        say = print if verbose else (lambda *a: None)
        say(f"token ids                {str(tuple(np.shape(ids))):>10}")
        x = params["tok_emb"][ids] * np.sqrt(d)                  # lookup (scaled as in the original paper)
        say(f"token embeddings         {str(x.shape):>10}")
        x = x + sinusoidal_positions(T, d)                       # add position information
        say(f"+ positions              {str(x.shape):>10}")
        for i, p in enumerate(params["blocks"]):
            x = block(x, p, cfg)
            say(f"after block {i + 1}            {str(x.shape):>10}")
        x = layer_norm(x, params["lnf_g"], params["lnf_b"])      # final norm
        say(f"final LayerNorm          {str(x.shape):>10}")
        logits = x @ params["tok_emb"].T                         # LM head, tied to the embedding table
        say(f"logits                   {str(logits.shape):>10}")
        return logits
    
    
    rng = np.random.default_rng(0)
    params = init_params(CFG, rng)
    prompt = ["the", "cat", "sat", "on", "the"]
    ids = np.array([VOCAB.index(w) for w in prompt])
    print("prompt:", " ".join(prompt), "->", ids.tolist())
    print(f"config: {CFG}\n")
    
    logits = forward(ids, params, CFG, verbose=True)
    probs = softmax(logits[-1])                                  # only the LAST position predicts the next token
    print("\nnext-token distribution after 'the cat sat on the' (top 5):")
    for i in np.argsort(-probs)[:5]:
        print(f"  {VOCAB[i]:<8} {float(probs[i]):.4f}")
    H = float(-(probs * np.log(probs)).sum())
    print(f"entropy {H:.3f} nats vs uniform {np.log(len(VOCAB)):.3f}: random weights -> almost a uniform guess")
    
    # Causality: the prediction at position 2 does not depend on later tokens
    ids2 = ids.copy(); ids2[4] = VOCAB.index("a")
    print("logits for positions 0-3 unchanged when token 4 changes:", bool(np.allclose(logits[:4], forward(ids2, params, CFG)[:4])))
    
    print(f"\nparameters: formula {count_params(CFG):,}, actual arrays {actual_params(params):,}")
    gpt2 = dict(vocab_size=50257, d_model=768, n_heads=12, n_layers=12, d_ff=3072, max_len=1024)
    print(f"GPT-2 small (public config, learned positions, tied head): {count_params(gpt2, learned_positions=True):,}")
    for name, d, L in [("GPT-2 medium", 1024, 24), ("GPT-2 large", 1280, 36), ("GPT-2 XL", 1600, 48)]:
        c = dict(gpt2, d_model=d, n_layers=L, d_ff=4 * d)
        print(f"{name + ':':<14} {count_params(c, learned_positions=True) / 1e6:,.1f} M")

    The parts that are new in this lesson:

    1. CFG = dict(vocab_size=…, d_model=32, n_heads=4, n_layers=2, d_ff=128, max_len=64): every size in one place. Changing the model's size means changing only this dictionary.
    2. q, k, v = np.split(x @ p["W_qkv"] + p["b_qkv"], 3, axis=-1): one fused projection for Q, K and V, with a bias (GPT-2 style), then the head reshape from lesson 4.5.
    3. np.where(np.triu(np.ones((T, T), bool), 1), -np.inf, scores): the causal mask, applied to every head at once by broadcasting.
    4. block(x, p, cfg): the two pre-norm residual updates from lesson 4.2.
    5. n = lambda *shape: rng.normal(0, 0.02, shape): GPT-2's initialisation scale for weight matrices; gains start at 1, biases at 0.
    6. count_params(cfg, learned_positions=False, tied_head=True): a closed-form count, written from the architecture rather than from the arrays, so comparing it with actual_params is a real check.
    7. params["tok_emb"][ids] * np.sqrt(d) and x @ params["tok_emb"].T: the same table used at the start (lookup) and at the end (scoring), i.e. a tied LM head.
    8. probs = softmax(logits[-1]): only the last position's row is needed to predict the next token.
    9. H = float(-(probs * np.log(probs)).sum()): the entropy of the prediction in nats. The maximum, for a uniform guess over 17 words, is ln17≈2.833.
    10. ids2[4] = VOCAB.index("a"): changes the last token and checks that logits at positions 0–3 do not move.
    11. gpt2 = dict(vocab_size=50257, d_model=768, …): GPT-2 small's published configuration, counted with the same formula plus learned positions.
    prompt: the cat sat on the -> [1, 3, 6, 9, 1]
    config: {'vocab_size': 17, 'd_model': 32, 'n_heads': 4, 'n_layers': 2, 'd_ff': 128, 'max_len': 64}
    
    token ids                      (5,)
    token embeddings            (5, 32)
    + positions                 (5, 32)
    after block 1               (5, 32)
    after block 2               (5, 32)
    final LayerNorm             (5, 32)
    logits                      (5, 17)
    
    next-token distribution after 'the cat sat on the' (top 5):
      mat      0.0755
      the      0.0735
      log      0.0655
      cat      0.0648
      sat      0.0637
    entropy 2.824 nats vs uniform 2.833: random weights -> almost a uniform guess
    logits for positions 0-3 unchanged when token 4 changes: True
    
    parameters: formula 26,016, actual arrays 26,016
    GPT-2 small (public config, learned positions, tied head): 124,439,808
    GPT-2 medium:  354.8 M
    GPT-2 large:   774.0 M
    GPT-2 XL:      1,557.6 M

    Reading the output

    The shape trace goes from 5 ids to (5, 32) vectors, through two blocks, to (5, 17) logits. The "prediction" after "the cat sat on the" puts "mat" first, but only with probability 0.0755, barely above the uniform 1/17 ≈ 0.059. The entropy, 2.824 nats against a maximum of 2.833, says the same: an untrained model is guessing. That "mat" came out on top is a coincidence of the random seed, not knowledge. The causality line is the most important test in the file: if it ever prints False, the model can see the future and training would teach it to cheat.

    The parameter count is a real verification. Our formula gives 26,016, which equals the sum of every array's size. Applied to GPT-2 small's published configuration with learned positions and a tied head, the same formula gives 124,439,808, which matches the commonly cited "124M" for that model. The medium, large and XL sizes (about 355M, 774M and 1.56B) match the published GPT-2 family too. This is how you can sanity-check any open model's configuration file. For Claude, no such configuration is public, so no such count is possible.

    From this file to a real model

    What separates our 26-thousand-parameter toy from a production LLM? Not new kinds of blocks, mostly scale and engineering:

    • Training: a loss (cross-entropy on the next token), backpropagation through every operation, and an optimiser such as AdamW. Module 5 does this on a small text with a small model.
    • Batches and hardware: an extra batch axis, 16-bit or lower precision, fused GPU kernels, and the model split across many accelerators. Frontier pretraining is publicly estimated to use thousands to tens of thousands of accelerators for weeks to months on trillions of tokens, at a cost of tens to hundreds of millions of dollars (estimates for frontier models in general, not Claude figures).
    • Architecture refinements covered in the deeper sections: RoPE, RMSNorm, SwiGLU, grouped-query attention, sometimes mixture of experts.
    • Post-training: turning a next-token predictor into an assistant with fine-tuning and preference training, the subject of module 6.

    For practical work you will not train such models yourself. You will use hosted models through APIs, or run open-weight models locally (for example with Ollama) and adapt them with LoRA on one GPU (module 10). Knowing what is inside, which you now do, is what makes you good at using them.

    Why generation needs a KV cache

    To generate text, you call the model, take the most likely (or a sampled) next token, append it, and call the model again on the longer sequence. Done naively, step 100 recomputes the keys and values of the first 99 tokens, which were already computed at step 99 and have not changed: thanks to the causal mask, earlier positions never depend on later ones. A KV cache stores each layer's keys and values as they are computed. Each new step then runs only the one new token through the blocks, computes its query, key and value, appends the key and value to the cache, and attends over the cached keys. That turns the cost per generated token from "the whole sequence" into "one token plus one attention row". Every production inference server does this; the cache's memory size is also why the grouped-query attention of lesson 4.5 matters.

    Inference costs, prefill and decode

    Serving an LLM has two phases. Prefill processes the whole prompt in one forward pass, which is a big matrix computation and keeps the hardware busy. Decode then produces one token at a time; each step reads all the model's weights and the whole KV cache from memory to do a relatively small amount of arithmetic, so it is limited by memory bandwidth rather than computation. That is why servers batch many users' decode steps together and why techniques such as quantised weights, paged KV-cache memory and speculative decoding (a small model drafts several tokens and the big model checks them in one pass) are widely published and used Industry practice.

    The KV cache's size per token is 2×nlayers×nkv heads×dhead numbers. For a model with 32 layers, 8 key/value heads of size 128 and 16-bit numbers, that is 2 × 32 × 8 × 128 × 2 bytes = 128 KB per token, so a 100,000-token context needs about 13 GB for the cache of one conversation. Long context windows are an engineering achievement as much as a modelling one. How Anthropic serves Claude is not public Not public.

    Common mistakes and debugging tips

    Reading meaning into an untrained model's output

    "It predicted mat!" With random weights every token gets roughly 1/V probability; whichever comes first is chance.

    Fix: compare with the uniform baseline (entropy close to lnV, top probability close to 1/V) before claiming anything. After training, the entropy should drop well below it.

    Shape bugs that broadcasting hides

    NumPy happily adds a (T,) array to a (T, d) array if the sizes happen to line up, and silently does the wrong thing when T == d.

    Fix: use different sizes for every dimension in tests (here T = 5, d = 32, V = 17, heads = 4) and print a shape trace like forward(…, verbose=True).

    A cache that gives slightly different answers

    Wrong position offsets, a mask that is not shifted for the new rows, or appending keys after attending instead of before all produce plausible but different text.

    Fix: always test cached generation against full recomputation, logit by logit, as kv_cache.py does.

    Key takeaways

    • A decoder-only transformer is about 120 lines of NumPy: embed, add positions, N pre-norm blocks, final norm, tied LM head.
    • Test it with a shape trace, a causality check and an independent parameter count.
    • The same formula reproduces GPT-2 small's published 124M parameters; Claude's configuration is not public.
    • Generation reuses cached keys and values so each new token costs one row, not the whole sequence.

    Exercise: greedy generation without a cache

    Using forward, params, CFG and VOCAB from transformer.py, write generate(words, n_new) that appends the most likely next token n_new times, recomputing the full forward pass every step. Generate 8 tokens after "the cat sat on the". How many token rows pass through the blocks in total?

    Hint

    Convert words to ids with VOCAB.index, call forward(np.array(ids), params, CFG), take np.argmax(logits[-1]), append, repeat. Rows per step equal the current sequence length.

    Show a solution
    def generate(words, n_new):
        ids = [VOCAB.index(w) for w in words]
        for _ in range(n_new):
            logits = forward(np.array(ids), params, CFG)   # recompute everything
            ids.append(int(np.argmax(logits[-1])))         # greedy: most likely token
        return " ".join(VOCAB[i] for i in ids)
    
    print(generate(["the", "cat", "sat", "on", "the"], 8))
    # the cat sat on the mat mat mat mat mat mat mat mat

    The rows processed are 5 + 6 + … + 12 = 68 (the reference in the mini-project counts 6 + 7 + … + 13 = 76, because it recomputes the sequence after each append to check the new logits). The repetition is what greedy decoding of an untrained model looks like: the same weak favourite wins every time. Module 5 adds training and sampling with temperature, top-k and top-p.

    Mini-project: add a KV cache and prove it is exact

    Extend the NumPy transformer so it can generate with a key-value cache, and prove with a test that cached generation produces the same logits as full recomputation. This is exactly the optimisation inference servers rely on, at toy scale.

    1. Copy transformer.py to kv_cache.py. Write embed(ids, start, …) that adds positional encodings for positions start … start + n − 1 instead of always starting at 0.
    2. Write new_cache(cfg) returning one {"k": None, "v": None} dictionary per layer.
    3. Write cached_attention(x, p, n_heads, layer_cache, start): compute Q, K, V for the new rows only, concatenate the new K and V onto the cached ones along the position axis, store them back, and attend. The causal mask must compare absolute positions: a new query at position start + i may see keys 0 … start + i.
    4. Write forward_cached(new_ids, params, cfg, cache, start) that runs only the new tokens through every block with the cache.
    5. Prefill: run the 5-token prompt once with start = 0 and check the logits equal forward()'s.
    6. Decode: generate 8 tokens greedily, feeding one token per step at start = len(seq) − 1. After each step, compare the new logits with a full recomputation and track the largest absolute difference.
    7. Report the generated text, the largest difference (it should be below 1e-12), the cache shape, and how many token rows each method pushed through the blocks.
    Hints / reference solution

    Keep the cache tensors in the head layout (n_heads, positions, d_head) so concatenation is along axis 1. Build the shifted mask from position grids: q_pos = np.arange(start, start + n)[:, None], k_pos = np.arange(start + n)[None, :], forbidden where k_pos > q_pos. Using the same seed as transformer.py gives the same weights, so your greedy text should match the exercise above. The reference solution is self-contained (it repeats the model code so it runs alone, including with ▶ Run):

    # @run
    # Mini-project reference solution (lesson 4.9): add a KV cache to the NumPy transformer and prove that
    # cached generation gives exactly the same logits as recomputing the whole sequence every step.
    # Self-contained copy of the model from transformer.py so it runs on its own (Pyodide included).
    import numpy as np
    
    VOCAB = ["<unk>", "the", "a", "cat", "dog", "bird", "sat", "ran", "slept", "on", "under",
             "mat", "log", "tree", "and", "quietly", "."]
    CFG = dict(vocab_size=len(VOCAB), d_model=32, n_heads=4, n_layers=2, d_ff=128, max_len=64)
    
    
    # ---------- building blocks (each one was a lesson in this module) ----------
    def softmax(z, axis=-1):
        z = z - z.max(axis=axis, keepdims=True)
        e = np.exp(z)
        return e / e.sum(axis=axis, keepdims=True)
    
    
    def layer_norm(x, g, b, eps=1e-5):
        mu, var = x.mean(-1, keepdims=True), x.var(-1, keepdims=True)
        return g * (x - mu) / np.sqrt(var + eps) + b
    
    
    def gelu(x):
        return 0.5 * x * (1 + np.tanh(np.sqrt(2 / np.pi) * (x + 0.044715 * x ** 3)))
    
    
    def sinusoidal_positions(T, d):
        pos, i = np.arange(T)[:, None], np.arange(d // 2)[None, :]
        ang = pos / 10000 ** (2 * i / d)
        pe = np.zeros((T, d))
        pe[:, 0::2], pe[:, 1::2] = np.sin(ang), np.cos(ang)
        return pe
    
    
    def causal_self_attention(x, p, n_heads):
        T, d = x.shape
        hd = d // n_heads
        q, k, v = np.split(x @ p["W_qkv"] + p["b_qkv"], 3, axis=-1)
        q, k, v = (m.reshape(T, n_heads, hd).transpose(1, 0, 2) for m in (q, k, v))   # (h, T, hd)
        scores = q @ k.transpose(0, 2, 1) / np.sqrt(hd)                                # (h, T, T)
        scores = np.where(np.triu(np.ones((T, T), bool), 1), -np.inf, scores)          # no peeking ahead
        out = softmax(scores) @ v                                                      # (h, T, hd)
        return out.transpose(1, 0, 2).reshape(T, d) @ p["W_o"] + p["b_o"]
    
    
    def ffn(x, p):
        return gelu(x @ p["W1"] + p["b1"]) @ p["W2"] + p["b2"]
    
    
    def block(x, p, cfg):
        x = x + causal_self_attention(layer_norm(x, p["ln1_g"], p["ln1_b"]), p, cfg["n_heads"])  # pre-norm
        x = x + ffn(layer_norm(x, p["ln2_g"], p["ln2_b"]), p)
        return x
    
    
    # ---------- parameters ----------
    def init_params(cfg, rng):
        d, f, V = cfg["d_model"], cfg["d_ff"], cfg["vocab_size"]
        n = lambda *shape: rng.normal(0, 0.02, shape)               # GPT-2 style small init
        blocks = [dict(ln1_g=np.ones(d), ln1_b=np.zeros(d),
                       W_qkv=n(d, 3 * d), b_qkv=np.zeros(3 * d), W_o=n(d, d), b_o=np.zeros(d),
                       ln2_g=np.ones(d), ln2_b=np.zeros(d),
                       W1=n(d, f), b1=np.zeros(f), W2=n(f, d), b2=np.zeros(d))
                  for _ in range(cfg["n_layers"])]
        return dict(tok_emb=n(V, d), blocks=blocks, lnf_g=np.ones(d), lnf_b=np.zeros(d))
    
    
    def embed(ids, start, params, cfg):
        d = cfg["d_model"]
        pe = sinusoidal_positions(start + len(ids), d)[start:]      # positions start .. start+n-1
        return params["tok_emb"][ids] * np.sqrt(d) + pe
    
    
    def forward(ids, params, cfg):
        """Reference: full recomputation over the whole sequence (same as transformer.py)."""
        x = embed(ids, 0, params, cfg)
        for p in params["blocks"]:
            x = block(x, p, cfg)
        return layer_norm(x, params["lnf_g"], params["lnf_b"]) @ params["tok_emb"].T
    
    
    def new_cache(cfg):
        return [{"k": None, "v": None} for _ in range(cfg["n_layers"])]
    
    
    def cached_attention(x, p, n_heads, layer_cache, start):
        """x holds only the NEW tokens (positions start..start+n-1); old keys/values come from the cache."""
        n, d = x.shape
        hd = d // n_heads
        q, k, v = np.split(x @ p["W_qkv"] + p["b_qkv"], 3, axis=-1)
        q, k, v = (m.reshape(n, n_heads, hd).transpose(1, 0, 2) for m in (q, k, v))   # (h, n, hd)
        if layer_cache["k"] is not None:                                              # append to the cache
            k = np.concatenate([layer_cache["k"], k], axis=1)
            v = np.concatenate([layer_cache["v"], v], axis=1)
        layer_cache["k"], layer_cache["v"] = k, v                                     # (h, start+n, hd)
        scores = q @ k.transpose(0, 2, 1) / np.sqrt(hd)                               # (h, n, start+n)
        q_pos = np.arange(start, start + n)[:, None]
        k_pos = np.arange(start + n)[None, :]
        scores = np.where(k_pos > q_pos, -np.inf, scores)                             # causal mask, shifted
        out = softmax(scores) @ v
        return out.transpose(1, 0, 2).reshape(n, d) @ p["W_o"] + p["b_o"]
    
    
    def forward_cached(new_ids, params, cfg, cache, start):
        x = embed(new_ids, start, params, cfg)
        for p, lc in zip(params["blocks"], cache):
            x = x + cached_attention(layer_norm(x, p["ln1_g"], p["ln1_b"]), p, cfg["n_heads"], lc, start)
            x = x + ffn(layer_norm(x, p["ln2_g"], p["ln2_b"]), p)
        return layer_norm(x, params["lnf_g"], params["lnf_b"]) @ params["tok_emb"].T
    
    
    rng = np.random.default_rng(0)
    params = init_params(CFG, rng)                       # same seed -> same weights as transformer.py
    prompt = [VOCAB.index(w) for w in ["the", "cat", "sat", "on", "the"]]
    
    # 1. Prefill: run the prompt once, filling the cache
    cache = new_cache(CFG)
    logits = forward_cached(np.array(prompt), params, CFG, cache, 0)
    print("prefill logits match full forward:", bool(np.allclose(logits, forward(np.array(prompt), params, CFG))))
    
    # 2. Decode greedily, one token at a time, checking against full recomputation every step
    seq, worst, rows_full, rows_cached = list(prompt), 0.0, 0, 0
    for step in range(8):
        nxt = int(np.argmax(logits[-1]))
        seq.append(nxt)
        logits = forward_cached(np.array([nxt]), params, CFG, cache, len(seq) - 1)   # ONE new row
        full = forward(np.array(seq), params, CFG)                                      # every row again
        worst = max(worst, float(np.abs(logits[-1] - full[-1]).max()))
        rows_cached += 1
        rows_full += len(seq)
    
    print("generated:", " ".join(VOCAB[i] for i in seq))
    print("max |cached - full| over 8 steps:", "< 1e-12" if worst < 1e-12 else f"{worst:.2e}")
    print("cache shape per layer (heads, positions, head dim):", cache[0]["k"].shape)
    print(f"token rows pushed through the blocks: cached {rows_cached}, recompute {rows_full}")
    prefill logits match full forward: True
    generated: the cat sat on the mat mat mat mat mat mat mat mat
    max |cached - full| over 8 steps: < 1e-12
    cache shape per layer (heads, positions, head dim): (4, 13, 8)
    token rows pushed through the blocks: cached 8, recompute 76

    The cached path pushed 8 token rows through the blocks; recomputation pushed 76. At 1,000 generated tokens the gap is about 1,000 against half a million. The cost moved from compute to memory: the cache now holds (4, 13, 8) keys and values per layer and grows with every token. Possible extensions: add temperature sampling (lesson 5.7), add a batch dimension, or implement grouped-query attention with 2 key/value heads shared by 4 query heads and measure the cache shrink.

    Check your understanding

    The untrained model gives "mat" probability 0.0755 with 17 words in the vocabulary. What does that tell you?

    1. The model has learned that cats sit on mats
    2. Almost nothing: it is barely above the uniform 1/17 ≈ 0.059, as expected for random weights
    3. The tokenizer is broken
    Random weights give nearly uniform predictions, which the entropy (2.824 vs a maximum of 2.833) confirms. The ranking is a coincidence of the seed.

    Why is it valid to reuse cached keys and values from earlier steps?

    1. Because keys and values are learned constants
    2. Because the model ignores old tokens
    3. Because, with the causal mask, earlier positions' keys and values never depend on later tokens
    Each position's computation in every layer depends only on itself and earlier positions, so appending a token cannot change earlier keys or values. Old tokens are still attended to; their keys and values depend on the input, so they are not constants.

    The closed-form parameter count reproduces GPT-2 small's 124,439,808. Why can't you do the same for Claude?

    1. Anthropic has not published Claude's architecture configuration
    2. Claude does not have parameters
    3. The formula only works for models under 1 billion parameters
    The formula needs the configuration (layers, width, vocabulary, FFN size and so on). GPT-2's is public; Claude's is not. The formula itself works at any size.