llm.guideChapter 5The Transformer, Fully

The Transformer, Fully

Q, K and V, multi-head attention, positional encodings and the modern transformer block.

Part 2: Foundations. 9 sections, about 15 minutes.

TokensThe␣cat␣satT idsEmbedtoken + positionT × 768residual stream, T × 768Block, repeated 12 timesNormAttentiontokens read each other4d² weights+NormMLP768 → 3,072 → 7688d² weights+NormUnembed768 →50,257Nexttoken␣on␣down␣in
TokensThe␣cat␣satEmbedtoken + position, T × 768residual streamBlock × 12NormAttentiontokens read each other4d² weights+NormMLP768 → 3,072 → 7688d² weights+NormUnembed768 → 50,257Next token␣on␣down␣in
A decoder-only transformer from end to end, with the shapes of GPT-2 small: T tokens, a stream 768 wide, 12 blocks and a 50,257-token vocabulary. Everything in this chapter is a closer look at one of these boxes.

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.

Attention(Q, K, V) = softmax(QKT / √d) V
xquerykeyvaluescoresquery · every keyblendsoftmaxaddedback to x
Figure 5.1 One attention head. The query and key decide where to look. The value decides what is copied. The blend is added to the token’s vector, not swapped in for it.

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:

00.51416642561024largest attention weightdimensions per headno scaling: 0.95÷ √d: 0.11
00.51416642561024largest attention weightdimensions per headno scaling: 0.95÷ √d: 0.11
  • raw dot products
  • divided by √d
Figure 5.2 Simulation, 300 trials per point. Without scaling, the largest of 64 weights grows from 0.28 to 0.95 as the head grows from 4 to 1,024 dimensions; the head effectively attends to 1.2 keys, down from 21. With scaling it stays near 0.11 at every size.

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

FFiirrsstt··CCiittiizzeenn::↵↵BBeeffoorree··wwee··pprroocceeeedd

Layer 2, head 1

FFiirrsstt··CCiittiizzeenn::↵↵BBeeffoorree··wwee··pprroocceeeedd
Figure 5.3 Real attention weights from a trained model. The first head puts 60% of its weight, on average, on the character just before. The second looks back 12 characters on average and puts 55% of its weight on the line break after the speaker’s name, as if keeping track of where the speech began.

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.

SchemeHow it worksWhere you meet it
SinusoidalA fixed pattern of sines and cosines, one per position, added to the token embeddingThe 2017 transformer
Learned absoluteA trainable vector per position, added to the token embeddingGPT-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 areMost current open models, including the Llama and Qwen families
Relative bias (ALiBi)Subtracts a penalty from each score that grows with distanceSome 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.

Sinusoidal, 2017: added oncea wave per dimension, added to the embeddingRotary, today: applied in every layerquery and key are rotated by an angleproportional to their positionthe score depends on how far aparttwo tokens are, not where they areextends better to longer contexts,with tricks such as scaling the angles
Figure 5.4 Two ways to inject order. The sinusoidal pattern is mixed into the input once; rotation acts on queries and keys at every layer, which is why most current open models use it.

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:

ComponentThis guide’s small model
3 layers, width 64, 65 tokens
GPT-2 small
12 layers, width 768, 50,257 tokens
Token embedding4,16038,597,376
Position embedding4,096786,432
Attention, per layer16,4482,362,368
MLP, per layer33,0884,722,432
Normalization, per layer2563,072
All layers149,37685,054,464
Final normalization1281,536
Output layer4,160shared with the token embedding
Total161,920124,439,808
GPT-2 small124,439,808 weightsEmbeddings31%Attention23%MLPs46%This guide’s small model161,920 weightsAttention30%MLPs61%
GPT-2 small124,439,808 weightsEmbeddings31%Attention23%MLPs46%This guide’s small model161,920 weightsAttention30%MLPs61%
  • embeddings and position
  • attention
  • MLPs
  • output layer
Figure 5.5 Computed from the table above. In both models the MLPs hold about twice the weights of attention. GPT-2 small also spends almost a third of its weights on the embedding table, because its vocabulary is large.

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.

ShapeEach token can seeTrained toUsed forExamples
Encoder-onlyThe whole input, both directionsFill in masked tokensEmbeddings, classification, rerankingBERT and its descendants
Decoder-onlyItself and earlier tokensPredict the next tokenGeneration, and by extension almost everythingGPT, Claude, Llama, Qwen
Encoder–decoderDecoder also attends to the encoder’s outputMap an input sequence to an output sequenceTranslation, speech recognitionThe 2017 transformer, T5, Whisper
Encoder-onlysees the whole inputfill in masked tokens:embeddings, rerankingDecoder-onlysees itself and earlier tokenspredict the next token:GPT, Claude, LlamaEncoder-decoderdecoder also reads the encoderown tokensencoder outputmap one sequence to another:translation, WhisperEach row is a token doing the looking; a filled cell is a token it can see.
Figure 5.6 The three shapes are one block with three masks. The lower triangle of the decoder is what lets it be trained on every position of a text at once, and what makes the KV cache possible.

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.

Part2017NowWhat it buys
Normalization placementAfter each sublayerBefore each sublayer (pre-norm)Deep stacks train without fragile warmup (section 3.9)
Normalization typeLayerNormRMSNormSame effect with less arithmetic: it rescales without re-centering
MLP activationReLUGELU, then SwiGLUA gated MLP that gives slightly better quality per parameter
PositionSinusoidal, added onceRoPE, applied in every attention layerRelative distance, better behavior at long range
Key and value headsOne per query headShared across groups of query heads (GQA)A KV cache several times smaller
Attention computationBuild the full score matrixFlashAttentionThe 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:

DesignKey–value headsKV cache per tokenFor an 8,192-token conversation
One key–value head per query head32512 KB4.00 GB
Grouped-query attention8128 KB1.00 GB
One shared key–value head116 KB0.12 GB

The middle row is the 128 KB per token from section 2.7.

2017 blockMulti-head attentionAdd, then LayerNormpost-normMLP with ReLUAdd, then LayerNormpost-normSinusoids at the inputA modern blockRMSNorm firstpre-norm: a clean residual pathGrouped-query attentionfewer key-value heads, smaller cacheRoPE inside attentionrelative positionsRMSNorm firstbefore the MLP tooMLP with SwiGLUa gated activation
Figure 5.7 What changed since 2017, block by block. Each highlighted change buys training stability, a smaller KV cache or better long-context behavior; the shape of the block is unchanged.

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:

ModelTotal parametersActive per token
Mixtral 8x7BAbout 47BAbout 13B
DeepSeek-V3671BAbout 37B
Qwen3.5-397B-A17B397B17B

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.

Figure 5.8 Computed live in your browser for a decoder with gated (SwiGLU) MLPs and untied embeddings; the defaults are shaped like Llama 3 8B. Change any number to see parameters, compute per token and memory move.

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

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

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

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

↑↓ to move↵ to openesc to close