Guided tour: the Transformer block (transformer_block.py)
Multi-head attention, MLP and residual paths, in pre-LN order
This page is the third stop (3 of 5) of the guided tour. The block is the repeated unit of the network. This page follows the file line by line, from parameter initialization to the full forward. Source: src/llm_lab/foundations/transformer_block.py.
The reference block follows a pre-LN order: normalize, compute multi-head self-attention, add the residual path, then normalize, apply the MLP, and add its residual. Q/K/V/O projections and tensor shapes make the computation traceable; MQA/GQA, MLA and local attention are compared as architectural variants, not claimed as implemented in this code.
By the end of this tour, you will be able to: - trace a (B, T, d) shape through the block, from input to output; - explain why normalization sits inside the branch instead of on the residual trunk; - describe the role of each Q, K, V and O projection, and why heads stay isolated until w_o; - distinguish MHA, MQA, GQA, MLA, and local/sparse attention by the factor each one changes.
The block’s recipe: pre-LN with residuals
x = x + self._attention(layer_norm(x, self.ln1_gamma, self.ln1_beta))
return x + self._mlp(layer_norm(x, self.ln2_gamma, self.ln2_beta))Hover over or select a code line: its branch lights up in the diagram while the rest dims. Keyboard: Tab, Enter to pin, Esc to release.
The green stroke represents the identity path that bypasses each sublayer. Each branch (attention, MLP) computes a correction on a normalized copy and adds it to the stream — GPT-2’s pre-LN order. The addition can modify or cancel some input components.
The block applies two additive updates to the same stream x:
x + attention(ln(x))— the attention branch;x + mlp(ln(x))— the MLP branch.
Normalization sits inside the branch, not on the identity path. This path lets the input bypass the sublayer directly; its output is then added to the correction computed by the branch. This structure facilitates signal and gradient propagation, but the addition does not guarantee that every input component is preserved. This is GPT-2’s pre-LN order. This placement is often more favorable for optimizing deep Transformers: Xiong et al. (2020) find, in their theoretical and experimental setting, better-behaved gradients at initialization than with post-LN, which can reduce the need for learning-rate warm-up. This does not guarantee universal stability or superiority; those also depend on the architecture, initialization, and training protocol. Xiong et al. (2020), On Layer Normalization in the Transformer Architecture.
Initializing: why rng is an argument
def __init__(self, config: GPTConfig, rng: np.random.Generator) -> None:
d = config.embedding_dim
self.num_heads = config.num_heads
self.head_dim = d // config.num_heads- The
rnggenerator is supplied by the model and shared in stacking order: parameters become a deterministic function of the configuration. head_dim = d // H: each head ownsd/Hcontiguous columns — the slice bounds are recomputed in_attention.
The GPT-2 scheme keeps the base standard deviation \(0.02\) for internal projections (Q, K, V and the MLP’s first layer), and reduces it for the two output projections added to the residual stream: attention \(W_O\) and the MLP’s second layer (fc2).
residual_std = 0.02 / math.sqrt(2.0 * config.num_layers)The factor \(1/\sqrt{2L}\) accounts for the two residual contributions per block across \(L\) blocks. It reduces the initial scale of these two output projections; it does not guarantee constant residual-stream variance. The other projections retain the base standard deviation \(0.02\).
Parameter creation follows: normalizations start at identity (gamma ones, beta zeros), then four (d, d) matrices for the Q, K, V and O projections, and two matrices for the MLP (d -> mlp_hidden_dim -> d).
Attention: explicit loops, not by accident
q = linear(x, self.w_q, self.b_q)
k = linear(x, self.w_k, self.b_k)
v = linear(x, self.w_v, self.b_v)
mask = causal_mask(seq_len)
attended = np.empty_like(x)
for b in range(batch):
for h in range(self.num_heads):
columns = slice(h * self.head_dim, (h + 1) * self.head_dim)
head_out, _ = scaled_dot_product_attention(
q[b, :, columns], k[b, :, columns], v[b, :, columns], mask=mask
)
attended[b, :, columns] = head_out
return linear(attended, self.w_o, self.b_o)Line by line:
- Q, K, V are three projections of the same
x; each shape goes from(B, T, d)to(B, T, d). causal_mask(seq_len)lets positioniattend toj <= i; future positions receive-inf(zero weight after softmax).columns = slice(h * head_dim, (h+1) * head_dim): headhworks on its own columns — a slice, not a copy. The multi-head split is pure column bookkeeping over the samed.- Each
(b, h)pair solves one single-head attention problem of shape(T, head_dim)— exactly the problem solved by the testedscaled_dot_product_attention. The explicit loops keep every intermediate shape inspectable (milestone G4’s clarity-over-speed choice). - Heads never mix until the output projection
w_o, which alone blends information across heads.
Single-head primitive contract
The NumPy primitive is called separately for each (b, h) pair. Its contract is:
- Q:
(T_q, d_k); K:(T_k, d_k); V:(T_k, d_v). - Scores and weights:
(T_q, T_k); aggregated output:(T_q, d_v). T_qandT_kmay differ; so mayd_kandd_v. Keys and values must share the same key-sequence lengthT_k.- The optional additive mask has exactly shape
(T_q, T_k). It accepts finite biases and-infto forbid an interaction;NaNand+infare rejected.
An edge case that must not be interpreted as a distribution: if a row is fully masked, the primitive deliberately returns zero weights and a zero output. Rows with at least one accessible key are normalized over those keys only. This convention belongs to the reference implementation; do not generalize it to every attention API.
The test_attention.py suite checks, among other things, shapes and normalization invariants, a hand-computable weighted sum, finite additive biases, rejection of invalid masks, the fully masked-row case, causal-mask polarity, and prefix invariance under changes to future tokens. It also checks that a wrong softmax axis violates the expected per-query normalization.
Maintained sources: NumPy primitive · primitive and causal-mask tests.
Attention variants: what actually changes
The reference block above implements standard multi-head attention (MHA): each head has its own Q, K, and V projections. Modern variants do not all change the same thing. Some share K/V heads to reduce the cache; others compress what is stored or restrict which positions can be attended to.
1. MHA, MQA, and GQA: sharing K/V heads
Let \(H_q\) be the number of query heads and \(H_{KV}\) the number of key/value heads.
| Variant | Query heads Q | Key/value heads K/V | Idea |
|---|---|---|---|
| MHA | \(H_q\) | \(H_{KV}=H_q\) | Every Q head has its own K and V heads. |
| MQA | \(H_q\) | \(H_{KV}=1\) | All Q heads share one K/V head. |
| GQA | \(H_q\) | \(1 < H_{KV} < H_q\) | Q heads are partitioned into groups; each group shares K/V. |
Q remains specific to each query head. What distinguishes MQA and GQA is sharing the K/V projections and states — not removing Q heads. GQA interpolates between MHA and MQA; the number of K/V heads is an architectural choice, not a free switch applied to an already-trained model.
For dense attention with a KV cache, an approximate model-wide cache size is: One estimate is \(M_{KV}\approx 2 L B T H_{KV} d_h b\). where \(L\) is the number of attention layers, \(B\) the batch size, \(T\) the retained context, \(d_h\) the dimension of one KV head, and \(b\) the number of bytes per element. The factor 2 stores both K and V. With dimensions and precision held fixed, moving from 32 KV heads (MHA) to 8 (GQA) therefore divides this cache by 4; moving to one (MQA) divides it by 32. This ratio applies to the K/V cache, not total model memory or necessarily measured latency.
2. MLA: jointly compressing K and V into a latent space
Multi-head Latent Attention (MLA) does more than choose fewer KV heads. In DeepSeek-V2, K/V information is projected into a lower-rank latent representation that is cached during decoding; the required components are reconstructed by projection. The design described in the paper also uses a decoupled RoPE path for positional information.
The goal is to reduce the amount of KV state retained without simply replacing all heads with one shared head. The cost depends on latent dimensions, projections, kernels, and how the runtime absorbs certain projections. Do not compare MLA with GQA only by counting KV heads: the cached representation is different.
3. Local windows and sparse attention: restricting the positions being read
These methods change the connectivity pattern:
- Sliding-window attention: each position attends only to a local window of a chosen size. Attention work per position is then tied to that window rather than the entire context, but distant information is not directly accessible within one local layer.
- Sparse or block-sparse attention: only selected positions or blocks are allowed. Depending on the pattern, some long-range connections may remain; “sparse” therefore does not necessarily mean “strictly local.”
- Dense global attention: all positions permitted by the causal mask remain accessible. FlashAttention can accelerate this dense operation by reducing memory transfers without changing its mathematical connectivity pattern.
Restricting attended positions is not the same as sharing K/V heads: GQA and a local window can be combined, as illustrated by Mistral 7B. Keep three axes separate: KV-state size, number of position pairs computed, and memory-transfer cost.
What this implementation does — and does not do
The NumPy code in this walkthrough is a pedagogical MHA example: \(H_{KV}=H_q\), separate K/V projections per head, and dense causal attention. It does not implement GQA/MQA sharing, an inference-time KV cache, MLA latent compression, or a sparse pattern. The tables above describe distinct architectural choices; they do not claim that the reference code executes them.
Primary sources and visual comparison: MHA — Vaswani et al. (2017) · MQA — Shazeer (2019) · GQA — Ainslie et al. (2023) · MLA — DeepSeek-V2 (2024) · Sliding window — Mistral 7B (2023) · Sparse/local — Longformer (2020) · Visual guide to attention variants — Sebastian Raschka.
The MLP: widen, activate, project back
def _mlp(self, x: FloatArray) -> FloatArray:
hidden = gelu(linear(x, self.w_fc1, self.b_fc1))
return linear(hidden, self.w_fc2, self.b_fc2)Each position goes on its own through d -> mlp_hidden_dim (often 4d), then GELU, then back to d. The intermediate widening gives each position a larger space in which to compute its non-linear transformation.
Common misconceptions. (1) “Heads see what the others do”: no — each head is isolated until w_o. (2) “Normalization is cosmetic”: no — placing it inside the branch leaves the residual path direct. Its optimization effects have been studied, including by Xiong et al. (2020); they are not a configuration-independent guarantee.
What the tests verify
tests/unit/test_transformer_block.py: forward preserves the shape and stays finite; a non-3D input is rejected; a head count inconsistent with the width is rejected.
Exercises
The questions for this tour and their worked answers are collected on its dedicated practice page. Try them before opening the answers: they check the stated outcomes without duplicating the prompts in the walkthrough.
Connections
- Previous stop: building-block operations (
gpt_ops.py). - Next stop: assembling the GPT (
gpt.py) — where blocks get stacked.
Supplementary resources Experiment, explore further, and practise the ideas from this lesson.
Further reading
- Concept pages: GPT and Transformer overview, Q/K/V, scaled dot-product attention, causal masking, contextualized representations.
- Back to the path: Build a small GPT.
- Source:
transformer_block.py· Tests:test_transformer_block.py.