Backpropagate through a residual MLP block
Why it matters Every transformer layer is two residual blocks; this is the gradient that keeps 100-layer models trainable.
A residual block computes y = x + W2 relu(W1 x + b1) + b2. The skip path is why deep networks train.
Write residual_backward(x, W1, b1, W2, b2, dy). x is (n, d), W1 is (d, h), b1 (h,), W2 (h, d), b2 (d,), and rows are samples (so the layer is x @ W1). Return the dict {"dx", "dW1", "db1", "dW2", "db2"} of gradients given upstream dy of shape (n, d).
def residual_backward(x, W1, b1, W2, b2, dy)Example
with W2 all zeros, dx equals dy exactly, because only the skip path carries gradient.
Understand the idea
A residual block adds its input straight to the output of a small MLP: y = x + relu(x W1 + b1) W2 + b2. Backward, the gradient reaches x by two roads: the skip path passes dy unchanged and the MLP path uses the chain rule; the two add. Worked example with every size 1: x = 2, W1 = 1, b1 = -1, W2 = 3, b2 = 0, dy = 1. Forward: z = 1, a = 1. Backward: dW2 = a * dy = 1, db2 = 1, da = dy * W2 = 3, dz = 3 because z > 0, dW1 = x * dz = 6, db1 = 3, dx = dy + dz * W1 = 1 + 3 = 4. If b1 were -3, the ReLU blocks the MLP path and dx = 1. Rule (rows are samples): dW2 = a^T dy, db2 = sum of dy over rows, da = dy W2^T, dz = da * (z > 0), dW1 = x^T dz, db1 = sum of dz over rows, dx = dy + dz W1^T. Used in: ResNets and every transformer layer.
Shapes and data flow
x (n, d) @ W1 (d, h) -> z, a (n, h) @ W2 (h, d) -> (n, d) + x back: dy (n, d) @ W2^T -> (n, h) gate -> @ W1^T -> (n, d) + dy