The Transformer, Fully
Q, K and V, multi-head attention, positional encodings and the modern transformer block.
Chapter 2 gave the working picture: tokens become vectors, attention lets them read each other, and a stack of layers ends in a probability for every possible next token. This chapter opens each box. By the end you can read a model card, count its parameters by hand, and say what each architectural choice costs.
Two things here are measured, not asserted. The attention patterns come from the small transformer that Chapter 7 trains from scratch, and the scaling experiment is a simulation of a few lines.
5.1Queries, keys and values
Each token asks a question, and every earlier token offers an answer.
Attention is how one token’s vector gets information from the others. For a single head, each token’s vector is multiplied by three learned matrices to produce three smaller vectors:
- a query: what this token is looking for;
- a key: what this token offers to others that are looking;
- a value: what this token hands over if it is chosen.
A token’s query is compared with the key of every token it is allowed to see, by dot product. A softmax turns the scores into weights that sum to 1. The token then receives the weighted average of the values, and that result is added to its own vector.
In a model that generates text, a token may only look at itself and earlier tokens. This causal mask is applied by setting the scores for later positions to minus infinity before the softmax, so their weights are exactly zero. It is what lets one pass over a sequence train every position at once without any position seeing its own answer (section 2.2).
Common take“Attention finds the important words.”
Sharper take“Attention is a learned lookup. The query and key decide where to look and the value decides what gets copied. They are separate matrices, so ‘where’ and ‘what’ are learned independently.”
5.2Why divide by √d
Without the scaling, softmax saturates and learning stalls.
The division by √d looks like a detail. It is the reason attention can be trained at all. A dot product of two vectors with d dimensions is a sum of d terms, so its typical size grows like √d. Feed large scores into a softmax and it puts almost all the weight on one item, and a saturated softmax passes almost no gradient, the same failure as the saturated sigmoid in section 3.2.
A simulation shows the size of the effect. Draw one random query and 64 random keys, compute the attention weights, and record the largest one:
- raw dot products
- divided by √d
With the scaling, the scores have about unit variance whatever the head size, so every head starts out spread across many tokens and learns to sharpen where sharpening helps.
Common take“The √d is a normalization detail.”
Sharper take“It keeps the scores at unit variance for any head size, so softmax starts soft and gradients can flow. It is Chapter 3’s initialization argument, applied to attention.”
5.3Multi-head attention
Several small lookups in parallel, each free to learn a different relation.
One head can express one pattern of looking. A layer therefore runs several heads side by side. The model’s width d is split across h heads, each working with d/h dimensions and its own query, key and value matrices. Their outputs are concatenated and passed through one more matrix. The total cost is the same as one large head; what changes is that each head can track a different relation.
Nobody tells the heads what to track. Here are two from the small model of Chapter 7, reading the first line of the play. Each row is a character; each column is an earlier character it attends to.
Layer 1, head 3
Layer 2, head 1
Maps like these are useful for building intuition and risky as explanations. They show where information moved in one head of one layer. They do not show what was done with it, and a model’s answer usually depends on many heads acting together.
These weights exist only inside the model, and hosted APIs do not return them. A product that highlights “what the model focused on” is usually showing something else: a model’s answer to the question of which phrases matter. Section 30.10 has a demo built that way.
Common take“More heads means more attention, so more is better.”
Sharper take“Heads split a fixed width. Doubling the heads halves the size of each one: more distinct relations, each with less capacity. Parameters and compute stay the same.”
5.4Position
Attention has no sense of order, so order has to be injected.
Look again at the attention formula: nothing in it depends on where a token sits. Shuffle the input and each token receives the same blend. For language that would be fatal, so every transformer adds position information somewhere. The method has changed more than any other part of the design.
| Scheme | How it works | Where you meet it |
|---|---|---|
| Sinusoidal | A fixed pattern of sines and cosines, one per position, added to the token embedding | The 2017 transformer |
| Learned absolute | A trainable vector per position, added to the token embedding | GPT-2, BERT, and the small model in Chapter 7 |
| Rotary (RoPE) | Rotates each query and key by an angle proportional to its position, so a dot product depends on how far apart two tokens are | Most current open models, including the Llama and Qwen families |
| Relative bias (ALiBi) | Subtracts a penalty from each score that grows with distance | Some long-context models |
Absolute schemes tie what a model learns to particular positions and give it no vector at all for positions beyond the training length. Relative schemes such as RoPE encode distance, which is what language mostly cares about, and they behave better as contexts grow. They do not make length free: a model still attends poorly at distances it rarely saw in training, which is one reason a context window is a property of the training run and not only of the architecture.
Common take“The model knows word order because it reads left to right.”
Sharper take“Attention is an operation on a set. Order exists only because position is injected, and modern models inject it as rotations of the query and key, so what counts is the distance between two tokens.”
5.5The block
Attention moves information between tokens, the MLP transforms it within each one.
A transformer layer, or block, has two parts, each wrapped in the normalize-then-add pattern from section 3.9. Attention is the only place where tokens exchange information. The MLP that follows works on each token separately: it widens the vector to four times its size, applies a nonlinearity, and projects it back. A useful summary is that attention is communication and the MLP is computation.
The vector that runs through all the layers, picking up additions from each, is called the residual stream. After the last block comes a final normalization and the unembedding, a matrix that turns the vector into one score per vocabulary entry. Many models reuse the embedding matrix for this, which is called weight tying.
Counting the weights shows where a model’s capacity sits:
| Component | This guide’s small model 3 layers, width 64, 65 tokens | GPT-2 small 12 layers, width 768, 50,257 tokens |
|---|---|---|
| Token embedding | 4,160 | 38,597,376 |
| Position embedding | 4,096 | 786,432 |
| Attention, per layer | 16,448 | 2,362,368 |
| MLP, per layer | 33,088 | 4,722,432 |
| Normalization, per layer | 256 | 3,072 |
| All layers | 149,376 | 85,054,464 |
| Final normalization | 128 | 1,536 |
| Output layer | 4,160 | shared with the token embedding |
| Total | 161,920 | 124,439,808 |
- embeddings and position
- attention
- MLPs
- output layer
Two rules of thumb fall out. The blocks hold about 12 · L · d² weights for L layers of width d: 4d² in attention and 8d² in the MLP. And the MLPs hold twice as much as attention does.
Common take“The attention layers are where the model’s knowledge lives.”
Sharper take“Two thirds of each block’s weights are in the MLP. Attention routes information; the MLPs hold most of what the model knows.”
5.6Three shapes
Encoder-only, decoder-only, and encoder–decoder.
The same block is assembled in three ways, and the difference is the attention mask and the training task.
| Shape | Each token can see | Trained to | Used for | Examples |
|---|---|---|---|---|
| Encoder-only | The whole input, both directions | Fill in masked tokens | Embeddings, classification, reranking | BERT and its descendants |
| Decoder-only | Itself and earlier tokens | Predict the next token | Generation, and by extension almost everything | GPT, Claude, Llama, Qwen |
| Encoder–decoder | Decoder also attends to the encoder’s output | Map an input sequence to an output sequence | Translation, speech recognition | The 2017 transformer, T5, Whisper |
Decoder-only models took over language modeling for practical reasons. Next-token prediction needs no labels and turns every token of raw text into a training example. One stack does both the reading and the writing. Because prompt and answer share one sequence, any task can be phrased as a continuation. And the causal mask is what makes the KV cache of section 2.7 possible.
Encoders did not disappear. Seeing both directions gives better representations per parameter, so most embedding and reranking models are still encoders (Chapter 14).
Common take“BERT is obsolete.”
Sharper take“Encoders lost generation, not retrieval. If the job is to represent text, an encoder is usually the cheaper and better tool.”
5.7The modern block
What changed since 2017, and what each change buys.
A current model’s block would be recognizable to the authors of the 2017 paper. The changes are refinements, each small and each measured.
| Part | 2017 | Now | What it buys |
|---|---|---|---|
| Normalization placement | After each sublayer | Before each sublayer (pre-norm) | Deep stacks train without fragile warmup (section 3.9) |
| Normalization type | LayerNorm | RMSNorm | Same effect with less arithmetic: it rescales without re-centering |
| MLP activation | ReLU | GELU, then SwiGLU | A gated MLP that gives slightly better quality per parameter |
| Position | Sinusoidal, added once | RoPE, applied in every attention layer | Relative distance, better behavior at long range |
| Key and value heads | One per query head | Shared across groups of query heads (GQA) | A KV cache several times smaller |
| Attention computation | Build the full score matrix | FlashAttention | The same result computed in blocks, so the n × n matrix never sits in memory |
Grouped-query attention is the one with the most visible effect in production, because the KV cache is what limits how many conversations fit on a GPU. For a 32-layer model with a head size of 128 at 16-bit precision:
| Design | Key–value heads | KV cache per token | For an 8,192-token conversation |
|---|---|---|---|
| One key–value head per query head | 32 | 512 KB | 4.00 GB |
| Grouped-query attention | 8 | 128 KB | 1.00 GB |
| One shared key–value head | 1 | 16 KB | 0.12 GB |
The middle row is the 128 KB per token from section 2.7.
Common take“New models have new architectures.”
Sharper take“Since 2017 the block has changed in details, each worth a few percent of quality or a constant factor in memory. The big gains came from scale, data and training method.”
5.8Mixture of experts
More parameters without more compute per token.
A mixture-of-experts (MoE) model replaces the single MLP in each block with many MLPs, the experts, plus a small router that sends each token to a few of them. All the experts are stored; only the chosen ones run. Total parameters and active parameters come apart:
| Model | Total parameters | Active per token |
|---|---|---|
| Mixtral 8x7B | About 47B | About 13B |
| DeepSeek-V3 | 671B | About 37B |
| Qwen3.5-397B-A17B | 397B | 17B |
The appeal is capacity at a fixed compute cost per token. The price is paid elsewhere. Every expert has to be held in memory, so you buy memory for the total and compute for the active part. Training needs extra care to keep the router from sending everything to a few favorites. And serving is harder to batch, since different tokens take different paths.
Common take“A 400B-parameter model must be ten times slower than a 40B one.”
Sharper take“Check the active parameters. For an MoE, compute follows the active count and memory follows the total.”
5.9Counting cost
Parameters, compute and memory from a config file.
With three numbers from a model card, layers L, width d and vocabulary V, you can estimate what a model costs before downloading it.
- Parameters ≈ 12 · L · d² + V · d.
- Compute to process one token ≈ 2 floating-point operations (FLOPs) per parameter, since each weight takes part in one multiply and one add.
- Compute to train on one token ≈ 6 FLOPs per parameter, since the backward pass costs about twice the forward pass. Chapter 8 builds its cost estimates on this.
- Memory = bytes per parameter for the weights (section 3.4), plus the KV cache per token of context (section 2.7).
Those rules leave out one term: comparing each token with every other. Per token and per layer, the weights cost about 24d² FLOPs, and the pairwise scoring and blending cost about 4nd for a context of n tokens. The two are equal when n ≈ 6d. For a width of 4,096 that is about 25,000 tokens. Below that length, cost per token is roughly constant; well above it, context length is the main driver of compute.
Common take“A longer context just costs proportionally more.”
Sharper take“Cost per token has a part that is constant and a part that grows with the context. They cross near six times the model’s width, around 25,000 tokens for a width of 4,096. Past that, doubling the context roughly doubles the cost of every token in it.”
Key takeaways
- An attention head is a learned lookup: query and key decide where to look, the value decides what is copied, and the result is added to the token’s vector.
- Dividing scores by √d keeps softmax soft. Without it, the largest of 64 random weights rose from 0.28 to 0.95 as heads grew from 4 to 1,024 dimensions.
- Heads specialize untold. In the small model, one put 60% of its weight on the previous character and another 55% on the last line break.
- Attention has no sense of order. Position is injected, today mostly as rotations of queries and keys (RoPE), so that relative distance is what matters.
- A block is attention, which moves information between tokens, plus an MLP, which transforms it within each token. Two thirds of the weights are in the MLPs.
- Block parameters ≈ 12 · L · d². Processing a token costs about 2 FLOPs per parameter; training on it costs about 6.
- Decoder-only models won generation. Encoders still lead in embeddings and reranking.
- Since 2017 the block has changed in details: pre-norm, RMSNorm, SwiGLU, RoPE, grouped-query attention, FlashAttention.
- For a mixture of experts, compute follows active parameters and memory follows total parameters.
Check your understanding
-
A model card lists 32 layers, a width of 4,096, a vocabulary of 128,000, and 32 attention heads sharing 8 key–value heads. Estimate the parameter count, the KV cache per token at 16-bit precision, and the context length at which attention’s pairwise cost overtakes the cost of the weights.
Answer outline
Blocks: 12 × 32 × 4,096² ≈ 6.4B. Embedding: 128,000 × 4,096 ≈ 0.5B. Total ≈ 7B. Real models of this shape are listed at 8B, because their MLP is somewhat larger and the output layer is separate from the embedding; an estimate within 15% is what the rule is for. KV cache: 2 × 32 layers × 8 heads × 128 dimensions × 2 bytes = 128 KB per token. Crossover: about 6 × 4,096 ≈ 25,000 tokens.
-
You change a model from 16 attention heads to 32 and keep the width the same. What happens to the parameter count, to compute, and to each head? Give one reason quality might improve and one reason it might get worse.
Answer outline
Parameters and compute are unchanged, because the query, key and value matrices still map the full width; they are just cut into more slices. Each head now works in half as many dimensions. Quality might improve because more distinct relations can be tracked in one layer. It might get worse because each head has less capacity to express a precise match. Head sizes of 64 to 128 dimensions are the usual compromise.
-
A teammate proposes replacing your encoder embedding model with a decoder-only language model “because decoders won.” What does each shape offer for producing embeddings, and what would you measure before switching?
Answer outline
An encoder sees both directions, so every token’s representation is informed by the whole text, and encoder embedding models are small and cheap to run. A decoder sees only leftward, so the embedding is usually taken from the last token; large decoders bring more knowledge and can score higher, at a much higher cost per text. Measure retrieval quality on your own queries and documents, latency, cost per million tokens embedded, and the storage cost of the embedding size, then decide on the measured gap.
Further reading
- Vaswani et al. (2017), “Attention Is All You Need”: short, and after this chapter every section should read as familiar.
- Jay Alammar, “The Illustrated Transformer” (free online), or chapter 3 of Hands-On Large Language Models: the same material drawn step by step.
- Chip Huyen, AI Engineering, chapter 2: the section on model architecture and model size.
- Stanford CS336: the lecture on architectures and hyperparameters, which walks through the modern choices in section 5.7 and the evidence for each.