Multi-Head Attention and the Transformer Block
local graph
Chapter 8 — Multi-Head Attention and the Transformer Block
Section titled “Chapter 8 — Multi-Head Attention and the Transformer Block”A single attention head learns one way of relating positions. But a sentence has many simultaneous relationships — grammatical agreement, coreference, local phrasing, long-range topic — and one head cannot track them all at once. The transformer’s answer is to run several heads in parallel, each free to specialize, then combine them. This chapter builds multi-head attention, adds the feed-forward network and the normalization that lets a deep stack train, and assembles them into the transformer block that every model in Chapter 1 stacks dozens of times. The block we write here is, component for component, the one inside Llama, Qwen, and DeepSeek.
8.1 Multi-Head Attention
Section titled “8.1 Multi-Head Attention”The idea is to split the model dimension into h independent heads, run attention separately in each lower-dimensional subspace, and concatenate the results. Crucially this costs no extra parameters over a single head of the same width: the query/key/value projections still map d_model → d_model; we merely reshape that output into h pieces of size d_model / h. Each head attends in its own subspace, so one can specialize in local syntax while another tracks a distant antecedent.
import torch, torch.nn as nn, torch.nn.functional as F
class MultiHeadAttention(nn.Module): def __init__(self, d_model, n_heads): super().__init__() assert d_model % n_heads == 0 self.n_heads, self.d_head = n_heads, d_model // n_heads self.qkv = nn.Linear(d_model, 3 * d_model, bias=False) self.proj = nn.Linear(d_model, d_model, bias=False)
def forward(self, x): # x: (B, T, d_model) B, T, C = x.shape q, k, v = self.qkv(x).split(C, dim=2) # each (B, T, C) # (B, T, C) -> (B, n_heads, T, d_head): heads attend independently split = lambda t: t.view(B, T, self.n_heads, self.d_head).transpose(1, 2) q, k, v = split(q), split(k), split(v) y = F.scaled_dot_product_attention(q, k, v, is_causal=True) # fused, causal y = y.transpose(1, 2).contiguous().view(B, T, C) # merge heads back return self.proj(y)Python — block.py: multi-head causal self-attention (fused kernel)
The scaled_dot_product_attention call performs exactly the computation of Chapter 7 — scores, scaling, causal mask, softmax, weighted sum — but fused into one memory-efficient kernel, applied to all heads at once thanks to the extra head axis. The number of heads is a design knob: more heads mean more specialized but lower-dimensional subspaces. This same reshape-and-attend pattern is where the efficiency variants of Part IV intervene — grouped-query attention shares k and v across heads, and Multi-head Latent Attention compresses them entirely (Chapter 12).
8.2 The Feed-Forward Network
Section titled “8.2 The Feed-Forward Network”Attention mixes information across positions; the feed-forward network (FFN) then processes each position independently, giving the model nonlinear capacity to transform what attention gathered. It is a two-layer MLP that expands to a larger hidden dimension and projects back. The activation in that MLP has evolved: the original transformer used ReLU, GPT adopted the smoother GELU, and essentially every modern model now uses SwiGLU — a gated variant in which one linear branch is passed through a SiLU activation and multiplies a second branch. Gating consistently improves quality per parameter.
class SwiGLU(nn.Module): def __init__(self, d_model, hidden): super().__init__() self.gate = nn.Linear(d_model, hidden, bias=False) # the gate branch self.up = nn.Linear(d_model, hidden, bias=False) # the value branch self.down = nn.Linear(hidden, d_model, bias=False) def forward(self, x): return self.down(F.silu(self.gate(x)) * self.up(x))Python — block.py: a SwiGLU feed-forward network
Because SwiGLU uses three weight matrices instead of two, models shrink its hidden dimension to about 8/3 of the model dimension (rather than the classic 4×) to keep the parameter count comparable. Table 8.1 shows the FFN choices across the families.
| Family | FFN activation | Typical hidden ratio |
|---|---|---|
| Original Transformer | ReLU | 4× |
| GPT-2 / GPT-3 | GELU | 4× |
| Llama, DeepSeek, Qwen, Mistral | SwiGLU | ~2.7× (8/3, gated) |
| Gemma | GeGLU (gated GELU) | gated |
Table 8.1 — Feed-forward activations across model families
8.3 Normalization and the Residual Stream
Section titled “8.3 Normalization and the Residual Stream”Stacking dozens of these sublayers would be untrainable without two stabilizers. The first is the residual connection: every sublayer adds its output to its input rather than replacing it, creating a “residual stream” through which gradients flow unimpeded from the loss to the earliest layers. The second is normalization, which keeps activations at a consistent scale.
Two choices define the modern convention. Where to normalize: the original transformer applied normalization after each sublayer and residual (“post-norm”), which is fragile at depth; every model since GPT-2 normalizes the input to each sublayer (“pre-norm”), which trains stably even at a hundred layers. How to normalize: LayerNorm centers and scales using the mean and variance and adds learnable shift and scale; RMSNorm drops the mean-centering and the shift, normalizing only by the root-mean-square. RMSNorm is cheaper, performs as well, and has become the default in Llama, DeepSeek, and Qwen.
class RMSNorm(nn.Module): def __init__(self, dim, eps=1e-6): super().__init__() self.weight = nn.Parameter(torch.ones(dim)) # learnable per-channel scale self.eps = eps def forward(self, x): norm = x.pow(2).mean(dim=-1, keepdim=True).add(self.eps).rsqrt() return self.weight * (x * norm) # scale to unit RMS, then rescalePython — block.py: RMSNorm (the modern default)
| Decision | Original transformer | Modern (Llama / DeepSeek / Qwen) |
|---|---|---|
| Placement | post-norm (after residual) | pre-norm (before sublayer) |
| Normalizer | LayerNorm (mean + variance, bias) | RMSNorm (RMS only, no bias) |
| Effect | fragile; needs careful warmup | stable to great depth, slightly cheaper |
Table 8.2 — Two normalization decisions, and the modern answer
A small recent refinement worth noting is QK-norm, used by Qwen3 among others, which normalizes queries and keys before the attention dot product to further stabilize training of large models. It is a one-line addition to the attention module and a good example of how the block keeps being tuned at the margins.
8.4 Assembling the Transformer Block
Section titled “8.4 Assembling the Transformer Block”The components now snap together. A pre-norm block normalizes, attends, and adds the result back to the residual stream; then normalizes again, applies the feed-forward network, and adds again. Figure 8.1 shows the data flow, and the code is a direct transcription.
[!visual-conversion] Diagram, PDF 091 (printed 93). A vertical line labelled “x (residual stream)” runs down the left. Two branches leave it and rejoin at ⊕ nodes. Side labels: “attention sublayer (mixes across positions)” and “feed-forward sublayer (per-position transform)”.
flowchart TB
x["x (residual stream)"] --> n1["RMSNorm"] --> att["Multi-Head Attn"] --> p1(("+"))
x --> p1
p1 --> n2["RMSNorm"] --> ffn["SwiGLU FFN"] --> p2(("+"))
p1 --> p2
p2 --> out["…"]
*Figure 8.1. A pre-norm transformer block. Each sublayer normalizes its input, computes its function, and adds the result back to the residual stream (the + nodes). Normalization sits inside each branch;
the straight-through residual path is never normalized, which is what keeps deep stacks trainable.*
class Block(nn.Module): def __init__(self, d_model, n_heads, hidden): super().__init__() self.norm1 = RMSNorm(d_model) self.attn = MultiHeadAttention(d_model, n_heads) self.norm2 = RMSNorm(d_model) self.mlp = SwiGLU(d_model, hidden)
def forward(self, x): x = x + self.attn(self.norm1(x)) # pre-norm attention, added to residual x = x + self.mlp(self.norm2(x)) # pre-norm FFN, added to residual return xPython — block.py: the complete pre-norm transformer block
Both of the block’s normalizers and the classic block itself are short enough to reproduce from their real sources rather than describe. Here, first, is DeepSeek-V3’s RMSNorm — the modern normalizer this book uses, identical in form to Llama’s:
class RMSNorm(nn.Module): def __init__(self, dim, eps=1e-6): super().__init__() self.weight = nn.Parameter(torch.ones(dim)) self.eps = eps def forward(self, x): # scale by the inverse root-mean-square over the last dim rms = torch.rsqrt(x.pow(2).mean(-1, keepdim=True) + self.eps) return (x * rms) * self.weightPython — deepseek-ai/DeepSeek-V3 · RMSNorm (reproduced, MIT licence)
And here is nanoGPT’s complete classic block — the GPT-2 form, with a bias-optional LayerNorm, a GELU feed-forward network, and the same pre-norm residual structure:
class LayerNorm(nn.Module): """LayerNorm with an optional bias; PyTorch's lacks one.""" def __init__(self, ndim, bias): super().__init__() self.weight = nn.Parameter(torch.ones(ndim)) self.bias = nn.Parameter(torch.zeros(ndim)) if bias else None def forward(self, x): return F.layer_norm(x, self.weight.shape, self.weight, self.bias, 1e-5)
class MLP(nn.Module): def __init__(self, config): super().__init__() self.c_fc = nn.Linear(config.n_embd, 4 * config.n_embd, bias=config.bias) self.gelu = nn.GELU() self.c_proj = nn.Linear(4 * config.n_embd, config.n_embd, bias=config.bias) def forward(self, x): return self.c_proj(self.gelu(self.c_fc(x)))class Block(nn.Module): def __init__(self, config): super().__init__() self.ln_1 = LayerNorm(config.n_embd, bias=config.bias) self.attn = CausalSelfAttention(config) self.ln_2 = LayerNorm(config.n_embd, bias=config.bias) self.mlp = MLP(config) def forward(self, x): x = x + self.attn(self.ln_1(x)) # pre-norm + residual x = x + self.mlp(self.ln_2(x)) return xPython — karpathy/nanoGPT · model.py: LayerNorm, MLP, Block (reproduced, MIT licence)
Set this beside the modern block written earlier in the chapter and the comparison is exact. The arrangement is identical — normalize, attend, add; normalize, feed-forward, add — and only the contents of the two sublayers differ: nanoGPT uses LayerNorm where we used RMSNorm, and a plain GELU MLP where we used the gated SwiGLU. DeepSeek-V3, in turn, keeps this very structure and swaps in MLA for the attention and a Mixture-of-Experts for the feed-forward in its large layers (Part IV). The modern decoder block is remarkably standardized; the innovation of Part IV lives inside these two sublayers, never in their arrangement. With these real implementations in hand — attention from Chapter 7, the block here, the full model in Chapter 10 — you have read, not been told about, every line of a working GPT.
Stack N of these blocks, wrap them in an embedding and an output head, and you have a GPT — almost. One ingredient is still missing: the block as written has no notion of order, because attention is permutation-invariant. Supplying position is the subject of the next chapter, after which Chapter 10 assembles the complete model and trains it.
8.5 The Residual Stream as a Communication Channel
Section titled “8.5 The Residual Stream as a Communication Channel”A powerful way to read the transformer block — borrowed from interpretability research — is to see the residual connections as creating a single residual stream: a running sum that every layer reads from and writes back to. Each sublayer does not replace the representation; it computes an update and adds it to the stream. Attention and the feed-forward network play complementary roles in this channel.
Attention is how information moves between positions: a token reads from the residual stream of other tokens, mixes what it finds, and writes the result back into its own stream (Section 7.4). The feed-forward network is how information is processed within a position: it transforms each token’s stream independently, with no exchange across positions. Stacking blocks alternates these two operations — gather context, then process it; gather again, process again — and the residual stream carries the accumulating representation through all of them. This picture explains several design choices that would otherwise seem arbitrary: why pre-normalization (Section 15.5) is applied to what each sublayer reads from the stream rather than to the stream itself, leaving the additive channel intact; and why the stream’s scale must be held in check (Chapters 15 and 21), since every layer adds to it and an unchecked sum will grow without bound. The transformer is, in this light, a sequence of reads and writes to a shared workspace.
Attention moves, the MLP processes Read the block as updates to a shared residual stream: attention exchanges information across positions, the feed-forward network transforms it in place, and every sublayer adds rather than overwrites. That single view explains pre-norm, residual scaling, and how depth accumulates meaning.
8.6 The Feed-Forward Network: Where Knowledge Lives
Section titled “8.6 The Feed-Forward Network: Where Knowledge Lives”Attention gets the attention, but the feed-forward network that follows it in each block (Section 8.5) holds the majority of a dense model’s parameters — and, by a productive interpretation, much of its factual knowledge. An FFN can be read as a key-value memory: the first linear layer’s neurons act as keys that detect patterns in the input, and the second layer’s weights store the values associated with those patterns, written back into the residual stream. Modern models also replace the plain two-layer FFN with a gated variant, SwiGLU, which empirically trains better:
def swiglu_ffn(x, W_gate, W_up, W_down): return (F.silu(x @ W_gate) * (x @ W_up)) @ W_downPython — block/swiglu.py: the gated feed-forward network
The gating is the innovation. One projection (x @ W_gate) is passed through a SiLU activation to produce a gate, which multiplies a second projection (x @ W_up) element-wise before the result is projected back down. The gate lets the network modulate its own activations — suppressing some dimensions, amplifying others, conditioned on the input — which gives it more expressive power per parameter than a plain activation, and the quality gain is consistent enough that SwiGLU is now the default. Reading the block as “attention moves information between positions, the FFN processes and stores it within a position” (Section 8.5) explains why the FFN is where most parameters and most knowledge reside, and why the mixture-of-experts of Chapter 11 — which replaces this single FFN with many — is the natural place to add capacity.
The FFN is the model’s memory Read as a key-value store, the feed-forward network detects patterns and writes associated values into the residual stream — holding most of a dense model’s parameters and knowledge. SwiGLU’s gate makes it more expressive, which is why it is the default; MoE scales it by replication.
8.7 Depth versus Width
Section titled “8.7 Depth versus Width”A transformer can be made larger in two different directions, and they are not interchangeable. Depth adds more layers, stacking more transformer blocks; width enlarges each layer by increasing the hidden dimension. Both raise the parameter count, but they buy different things, and the balance between them is a real architectural decision.
Depth buys sequential computation: each layer can build on the representations the previous one produced, so more layers mean more steps of progressive refinement — loosely, more room to compute something in stages. Width buys per-layer capacity and parallelizes more efficiently on hardware, since a wider matrix multiply uses the GPU’s throughput better than a longer chain of narrower ones. The two also fail differently at the extremes: a network that is very deep and thin is hard to train, because the signal must survive propagation through many layers (the stability concerns of Chapter 21), while one that is shallow and very wide wastes capacity it cannot use in too few sequential steps. Real models therefore follow rough aspect-ratio heuristics that scaling studies inform, growing depth and width together as the parameter budget rises rather than pushing either alone. Understanding that depth and width are distinct levers — one for sequential computation, one for capacity and hardware efficiency — clarifies why model configurations (Section 16.6) specify both, and why simply “making the model bigger” is really a choice about how to make it bigger.
Depth computes in steps; width computes in parallel Adding layers buys sequential refinement; widening layers buys per-layer capacity and better hardware use. Too deep and thin is hard to train; too shallow and wide wastes capacity. Scaling grows both together along a balanced ratio.