Implement the original post-norm transformer block

Why it matters Knowing post-norm versus pre-norm explains why early deep transformers needed learning-rate warmup and why GPT-2 onward switched.

The original transformer applied LayerNorm AFTER each residual add. Modern GPTs moved it before the sublayer, and comparing the two is a classic exercise.

Write postnorm_block(x, p). x has shape (T, d). p holds Wq, Wk, Wv, Wo (d, d), W1 (d, f), b1 (f,), W2 (f, d), b2 (d,).
1. LN(z) = (z - mean) / sqrt(var + 1e-5) over the last axis, population variance, no gain or bias.
2. Attn(z): q, k, v = z @ Wq, z @ Wk, z @ Wv; scores = q @ k.T / sqrt(d) with a causal mask; softmax rows; return (weights @ v) @ Wo. Single head.
3. FFN(z) = relu(z @ W1 + b1) @ W2 + b2.
4. h = LN(x + Attn(x)); return LN(h + FFN(h)).

Signaturedef postnorm_block(x, p)

Example

with every weight and bias zero, x = [[1, 2, 3, 4]] returns about [[-1.3416, -0.4472, 0.4472, 1.3416]], since both sublayers output zero.

Understand the idea

A transformer block has two sublayers, attention and a feed-forward network, each wrapped in a residual add and a LayerNorm. The only question is where the norm goes. Post-norm, used in the 2017 transformer, normalises after the add: out = LN(x + Sublayer(x)). Pre-norm, used by GPT-2 and later, normalises the input to the sublayer: out = x + Sublayer(LN(x)).

Tiny case: if all weights are zero, both sublayers output 0. Post-norm then returns LN(LN(x)). For x = [1,2,3,4]: mean 2.5, variance 1.25, so LN gives about [-1.342, -0.447, 0.447, 1.342]; normalising again changes almost nothing.

Rule here: h = LN(x + Attn(x)); y = LN(h + FFN(h)).

Post-norm keeps every block output at unit scale, but the gradient to early layers must pass through many norms, which made deep post-norm models hard to train without warmup. That is why most current LLMs use pre-norm.

Shapes and data flow

x (T, d) -> q, k, v (T, d) -> scores (T, T) -> attn out (T, d) -> h (T, d) -> FFN hidden (T, f) -> out (T, d)
solution.pyPython idle
Ctrl/Cmd + Enter runs sample tests

Run checks the first 2 tests. Submit checks all 3.

  • Sample 1: examplepostnorm_block(np.array([[1.0, 2.0, 3.0, 4.0]]), Z)
  • Sample 2: randompostnorm_block(X, P)
  • Test 3: first token sees itselfpostnorm_block(X[:1], P)