Derive the BatchNorm training-mode backward pass for 2-D and 4-D inputs

In training mode BatchNorm normalises with the batch's own mean and variance, so every output depends on every input in the batch. A backward pass that treats the statistics as constants is wrong, and the error grows as the batch shrinks.

Write batchnorm_backward(x, gamma, dy, eps=1e-5) for the forward y = gamma * (x - mu) / sqrt(var + eps) + beta, where mu and var are the batch mean and population variance per channel.
- If x is (N, C), channels are columns and statistics are over axis 0.
- If x is (N, C, H, W), statistics for channel c are over axes (0, 2, 3).
gamma has shape (C,), dy has the shape of x. Return a dict with "dx" (shape of x), "dgamma" (C,) and "dbeta" (C,).

Check: the per-channel sum of dx is always 0, because shifting a whole channel by a constant does not change y.

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

Understand the idea

In training mode BatchNorm uses the batch's own mean and variance, so nudging one input moves the statistics and therefore every output in that channel. The gradient has three paths: the direct one, one through the mean and one through the variance. They combine into a short formula with two per-channel sums. Worked example: one channel, x = [1, 3], gamma = 1, dy = [1, 0]. Mean 2, variance 1, x_hat = [-1, 1]. sum(dy) = 1 and sum(dy * x_hat) = -1. dx = (1 / 2) * (2 * [1, 0] - 1 - x_hat * (-1)) = 0.5 * ([2, 0] - [1, 1] - [1, -1]) = [0, 0] (tiny values with eps). That makes sense: with two points the normalised output is always [-1, 1], whatever x is. dgamma = -1, dbeta = 1. Rule per channel with m values: dx = gamma * inv_std / m * (m * dy - sum(dy) - x_hat * sum(dy * x_hat)); dgamma = sum(dy * x_hat); dbeta = sum(dy). For 4-D input, the sums run over N, H and W. Check: dx sums to 0 per channel. Any framework's BatchNorm layer uses this backward.

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

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

  • Sample 1: 2-D batchbatchnorm_backward(_x2, _g2, _d2)
  • Sample 2: 4-D batchbatchnorm_backward(_x4, _g4, _d4)