Implement the backward pass of group normalization
Why it matters Detectron-style models with small per-GPU batches rely on group norm, and custom kernels need this exact backward.
Group norm is the batch-size-independent choice for detection and segmentation. Writing its backward pass checks that you really understand normalisation gradients.
Write groupnorm_backward(x, gamma, groups, dy, eps=1e-5). x and dy are (N, C, H, W), gamma is (C,), and C is divisible by groups. Forward: split channels into groups of C // groups consecutive channels; for each sample and group, compute the mean and biased variance over that group's channels and all positions, get x_hat, and y = gamma[c] * x_hat (+ beta). Return a dict with "dx" (N, C, H, W), "dgamma" (C,) and "dbeta" (C,).
def groupnorm_backward(x, gamma, groups, dy, eps=1e-5)Example
x = [[[[1]], [[3]]]] (shape (1, 2, 1, 1)), gamma = [1, 1], groups = 1, dy = [[[[1]], [[0]]]] gives dx about [[[[0]], [[0]]]], dgamma [-1, 0] and dbeta [1, 0] (rounded to 4 places). With only 2 values, x_hat is always [-1, 1], so dx is 0.
Understand the idea
Normalisation makes every value depend on every other value in its group, because they share a mean and a variance. So the gradient of one input has three parts: its own direct path, the path through the shared mean, and the path through the shared variance. Like a group project grade that depends on your work and also on the group average.
Tiny example: a group of two values 1 and 3. x_hat is always [-1, 1] no matter what they are (up to eps), so moving either input does not change the output and dx is 0. dgamma for channel 1 is dy * x_hat = 1 * -1 = -1.
Rule per group of M values: dxh = dy * gamma, dx = inv_std / M * (M * dxh - sum(dxh) - x_hat * sum(dxh * x_hat)).
Group norm is the default in many detection and segmentation backbones where each GPU sees only one or two images.
Shapes and data flow
x (N,C,H,W) -> (N,G,M), M = (C/G)*H*W; dgamma, dbeta (C,)