Derive the LayerNorm backward pass

LayerNorm's gradient is a classic interview derivation because the mean and variance both depend on every input.

Forward (over the last axis, d features): xhat = (x - mean) / sqrt(var + eps), y = xhat * gamma + beta.

Write layer_norm_backward(x, gamma, dy, eps=1e-5) for x and dy of shape (n, d). Return (dx, dgamma, dbeta).

Known result, with inv = 1 / sqrt(var + eps) and g = dy * gamma:
dx = inv * (g - mean(g) - xhat * mean(g * xhat)), means over the last axis.

Signaturedef layer_norm_backward(x, gamma, dy, eps=1e-5)

Understand the idea

In LayerNorm, the mean and variance depend on every input, so nudging one input shifts all outputs. The backward pass must include those indirect effects. Using inv = 1 / sqrt(var + eps) and g = dy * gamma, the known result subtracts two terms from g: its mean (the effect through the mean) and xhat times mean(g * xhat) (the effect through the variance). Worked example: x = [1, 2, 3], gamma = 1, dy = [1, 0, 0]. xhat = [-1.225, 0, 1.225], inv = 1.225. mean(g) = 0.333. mean(g * xhat) = -0.408. dx = 1.225 x ([1, 0, 0] - 0.333 - xhat x (-0.408)) = 1.225 x [0.167, -0.333, 0.167] = [0.204, -0.408, 0.204]. The row sums to 0, which is a good check. Treating mean and variance as constants would give just inv * g. Rule: dx = inv (g - mean(g) - xhat mean(g xhat)) per row; dgamma = sum over rows of dy xhat; dbeta = sum over rows of dy. Training every transformer needs this.

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

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

  • Sample 1: dxlayer_norm_backward(_x, _gm, _dy)[0]
  • Sample 2: dgammalayer_norm_backward(_x, _gm, _dy)[1]