Back Through Batch Norm

Training Deep NetworksHard+30 XP+30

Back Through Batch Norm

Batch normalization standardises every feature across the batch, then lets the network rescale and shift it. Running it forwards is a few lines. This problem is about running it backwards.

A batch holds NNN examples with DDD features each, and x[i][j] is feature jjj of example iii. In training mode, the forward pass works column by column, using statistics computed from this batch:

μj=1N∑ixij,σj2=1N∑i(xij−μj)2\mu_j = \frac{1}{N}\sum_{i} x_{ij}, \qquad \sigma_j^2 = \frac{1}{N}\sum_{i} \left(x_{ij} - \mu_j\right)^2μj​=N1​i∑​xij​,σj2​=N1​i∑​(xij​−μj​)2 x^ij=xij−μjσj2+ε,yij=γj x^ij+βj\hat{x}_{ij} = \frac{x_{ij} - \mu_j}{\sqrt{\sigma_j^2 + \varepsilon}}, \qquad y_{ij} = \gamma_j\,\hat{x}_{ij} + \beta_jx^ij​=σj2​+ε​xij​−μj​​,yij​=γj​x^ij​+βj​

The variance divides by NNN, not N−1N - 1N−1. The rest of the network turns the outputs yyy into a loss LLL, and the backward pass has already delivered the upstream gradient dout[i][j] =∂L∂yij= \dfrac{\partial L}{\partial y_{ij}}=∂yij​∂L​.

Task: write batchnorm_backward(x, dout, gamma, eps) and return a tuple (dx, dgamma, dbeta):

  • dx: an N×DN \times DN×D list of lists with dx[i][j] =∂L∂xij= \dfrac{\partial L}{\partial x_{ij}}=∂xij​∂L​,
  • dgamma: a list of DDD values, ∂L∂γj\dfrac{\partial L}{\partial \gamma_j}∂γj​∂L​,
  • dbeta: a list of DDD values, ∂L∂βj\dfrac{\partial L}{\partial \beta_j}∂βj​∂L​.

Round every number to 4 decimal places. eps is always positive, and NNN can be as small as 1.

Examples

x = [[1.0], [2.0], [6.0]]
dout = [[1.0], [0.0], [0.0]]
gamma = [2.0]
eps = 1e-05
returns ([[0.3527], [-0.4409], [0.0882]], [-0.9258], [1.0])
x = [[1.0, 4.0], [2.0, 0.0], [6.0, 2.0]]
dout = [[0.5, -1.0], [1.0, 0.0], [-0.5, 2.0]]
gamma = [1.0, 0.5]
eps = 0.001
returns ([[-0.1542, -0.2552], [0.1929, -0.255], [-0.0386, 0.5102]], [-1.62, -1.2245], [1.0, 1.0])

Hints

Solve it to unlock the solution

Once your code passes every test, a reference solution shows up here so you can compare it with yours.

solution.py
CtrlEnterto run