Run a full pre-norm transformer block forward pass

A decoder block is the unit stacked dozens of times in a GPT-style model. Modern models put LayerNorm before each sublayer (pre-norm) and add the sublayer output back onto the residual stream, which keeps training stable in deep stacks.

Write transformer_block(x, p, n_heads). x has shape (T, d). p is a dict of arrays:
ln1_g, ln1_b, ln2_g, ln2_b (shape (d,)); Wq, Wk, Wv, Wo (shape (d, d)); W1 (d, f), b1 (f,); W2 (f, d), b2 (d,).

Compute:
1. LN(z, g, b) = g * (z - mean) / sqrt(var + 1e-5) + b over the last axis (var is the biased variance).
2. a = LN(x, ln1_g, ln1_b). Q = a Wq, K = a Wk, V = a Wv. Split d into n_heads heads of size dh = d / n_heads (head h uses columns h*dh to (h+1)*dh). For each head, scores = Q_h K_h^T / sqrt(dh) with a causal mask (key j > query i is excluded), softmax over keys, then multiply by V_h. Concatenate heads back to (T, d) and multiply by Wo.
3. h = x + attention output.
4. m = LN(h, ln2_g, ln2_b). mlp = relu(m W1 + b1) W2 + b2.
5. Return h + mlp, shape (T, d).

Signaturedef transformer_block(x, p, n_heads)

Example

if Wo, W2 and b2 are all zeros, the block returns x unchanged.

Understand the idea

A GPT-style decoder block has two sublayers, attention then an MLP, each wrapped the same way: normalise the input, run the sublayer, add the result back onto the running residual stream. The stream itself is never normalised inside the block. Inside attention, d is split into heads, each head scores queries against keys, a causal mask stops a token looking ahead, and the heads are joined back. Worked example of the causal softmax for one head with dh = 1: token 0 can only see itself, so its weights are [1, 0]. Token 1 has raw scores [1, 0] against keys 0 and 1, divided by sqrt(1), so its weights are softmax = [0.7311, 0.2689] and its output is 0.7311 * v0 + 0.2689 * v1. Rule: a = LN1(x); per head softmax(Q K^T / sqrt(dh) with future keys excluded) V; concatenate, times Wo; h = x + that; m = LN2(h); out = h + relu(m W1 + b1) W2 + b2. LN uses the biased variance and eps 1e-5. If Wo, W2 and b2 are zero, out equals x. Normalising after the residual add is the post-norm layout, which is different. Modern LLMs stack it dozens of times.

solution.pyPython idle
Ctrl/Cmd + Enter runs sample tests

Run checks the first 2 tests. Submit checks the hidden tests with Pro.

  • Sample 1: zero sublayers keep xtransformer_block(_x0, _P0, 2)
  • Sample 2: d 8, 2 headstransformer_block(_x1, _P1, 2)