Part 6 of 6 · What interviewers ask nextLearn and do
Layer norm's backward mixes every feature in a row
Layer norm and batch norm both subtract a mean and divide by a spread. They differ only in the axis. Layer norm takes the mean across each row, axis 1. Batch norm takes it down each column, axis 0:
Layer norm reads across a row, batch norm down a columnInteractive
Here μ is the row's mean, σ2 its variance, s its spread with a small constant added, and x^ the row rescaled to mean 0 and spread 1. γ and β are the learned scale and shift, C numbers each, and ⊙ multiplies entry by entry.
Ba et al. (2016) built it this way: the mean and variance come from one example's own features, never from the rest of the batch. Three things change in the backward pass.
First, the local derivative isn't entry by entry anymore. Every output in a row depends on every input in that row, through μ and σ. You don't build the full C×C table of slopes. You use its short closed form. Write g=γ⊙dy, and take both means over the features:
dxa=s1(g−mean(g)−x^⊙a)=mean(g⊙x^)
Drop the paths through μ and σ and treat it as an entry-by-entry scale by γ/s, and in a small test the input gradient is off by up to 1.5 on entries no bigger than 3.8.
Second, γ and β are one per feature, broadcast over the batch. So their gradients sum over the batch, like a bias: dgamma = (dy * xhat).sum(axis=0) and dbeta = dy.sum(axis=0).
Third, each row of dx sums to zero, like each row of dlogits.
Pick an answer above to see the rest
Predict
Why does each row of layer norm's dx sum to zero?
In the editor, write layernorm_backward(dy, xhat, s, gamma) from the closed form above.
Pick an answer above to see the rest
Instructions
1
Write layernorm_backward(dy, xhat, s, gamma): return dx, dgamma and dbeta.
2
With g = gamma * dy, dx is (g - mean(g) - xhat * mean(g * xhat)) / s, both means across each row's features. dgamma and dbeta sum over the batch.