Implement GroupNorm with contiguous channel groups

GroupNorm normalises over groups of channels within each example, so it does not depend on batch size. With one group it matches LayerNorm over (C, H, W); with one channel per group it is InstanceNorm.

Write group_norm(x, G, gamma, beta, eps=1e-5). x has shape (N, C, *spatial) with any number of spatial axes (possibly none). C is divisible by G. Group g holds the CONTIGUOUS channels g * (C // G) up to (g + 1) * (C // G) - 1.
For each example and group, compute the mean and population variance over that group's channels and all spatial positions, normalise with eps inside the sqrt, then apply per-channel gamma and beta (both shape (C,)). Return an array shaped like x.

Signaturedef group_norm(x, G, gamma, beta, eps=1e-5)

Example

x of shape (1, 2) = [[1.0, 3.0]] with G = 1, gamma = [1, 1], beta = [0, 0] gives about [[-1.0, 1.0]].

Understand the idea

GroupNorm splits the channels of each example into G groups and normalises each group on its own, over its channels and all spatial positions. It never looks across the batch, so it works the same with a batch of 1. Groups are contiguous blocks: with C = 4 and G = 2, group 0 is channels 0 and 1, group 1 is channels 2 and 3. Worked example: one example with no spatial axes, x = [1, 3, 10, 14], G = 2. Group 0 values [1, 3]: mean 2, variance 1, normalised [-1, 1]. Group 1 values [10, 14]: mean 12, variance 4, normalised [-1, 1]. Then each channel c applies its own gamma[c] and beta[c]. Rule: reshape to (N, G, C // G, spatial...), take mean and population variance over every axis after G, compute (x - mean) / sqrt(var + eps), reshape back, then scale and shift per channel. G = 1 behaves like LayerNorm over (C, H, W); G = C behaves like InstanceNorm. Grouping channels 0, G, 2G together is the classic reshape bug. GroupNorm is standard in diffusion U-Nets and detection backbones.

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

Run checks the first 2 tests. Submit checks all 5.

  • Sample 1: examplegroup_norm([[1.0, 3.0]], 1, [1.0, 1.0], [0.0, 0.0])
  • Sample 2: G = 2 of 6 channelsgroup_norm(_x, 2, _ga, _be)
  • Test 3: G = 3group_norm(_x, 3, np.ones(6), np.zeros(6))
  • Test 4: G = C is instance normgroup_norm(_x, 6, _ga, _be)
  • Test 5: 1-D spatialgroup_norm(_x1, 2, np.ones(4), np.zeros(4))