Forward pass of a pre-norm residual MLP block
Transformer layers are stacks of pre-norm residual blocks: normalise, transform, then add back the untouched input. The skip path carries the raw x, which is what keeps very deep stacks trainable.
Write prenorm_block(x, gamma, beta, W1, b1, W2, b2, eps=1e-5) for x of shape (n, d):
1. h = LayerNorm(x) over the last axis (population variance, eps inside the sqrt), then h = h * gamma + beta.
2. u = relu(h @ W1 + b1), with W1 (d, k) and b1 (k,).
3. y = x + u @ W2 + b2, with W2 (k, d) and b2 (d,).
Return y with shape (n, d).
def prenorm_block(x, gamma, beta, W1, b1, W2, b2, eps=1e-5)Example
if W2 and b2 are all zeros, y equals x exactly.
Understand the idea
A pre-norm residual block has two paths. The branch normalises the input, runs a small MLP and produces a change; the skip path carries the raw input untouched, and the two are added. Think of editing a document with tracked changes: the original text stays and only the edits are added on top. Worked example: x = [1, 3], gamma = [1, 1], beta = [0, 0]. Mean = 2, population variance = 1, so LayerNorm gives about [-1, 1]. With W1 = identity and b1 = 0, u = relu([-1, 1]) = [0, 1]. With W2 = identity and b2 = 0, y = x + u = [1, 4]. Rule: h = (x - mean) / sqrt(var + eps) * gamma + beta over the last axis, using variance with divisor d; u = relu(h W1 + b1); y = x + u W2 + b2. If the branch outputs zero, y equals x exactly. Adding h instead of x on the skip path is the common bug. This block shape, with attention or an MLP inside, is stacked dozens of times in GPT-style transformers.