Merge per-thread mean and variance statistics in a block
Why it matters Layernorm and batchnorm kernels merge per-thread statistics this way to get stable variances in one pass over the data.
A layernorm kernel splits a row across threads. Each thread computes (count, mean, M2) for its part, where M2 is the sum of squared deviations from its own mean, and the block merges these partial statistics in a tree.
Write merge_stats(stats). stats is a list of (count, mean, M2) tuples. Merge two parts with n = na + nb, delta = mb - ma, mean = ma + delta * nb / n, M2 = M2a + M2b + delta^2 * na * nb / n (if n is 0 the result is (0, 0.0, 0.0)). Merge pairwise in a tree: repeatedly merge neighbours (0 with 1, 2 with 3, ...; an odd last item passes through) until one remains. Return (count, mean, variance) with population variance M2 / count (0.0 when count is 0). Raise ValueError for an empty list.
def merge_stats(stats)Example
stats [(2, 1.0, 2.0), (2, 5.0, 2.0)] (data [0, 2] and [4, 6]) gives (4, 3.0, 5.0).
Understand the idea
Merging statistics is like combining two classes' test results. Each class reports its size, its average and how spread out its marks are around its own average. The combined spread is the two spreads plus extra spread because the two class averages differ. Worked example: part A is [0, 2] with mean 1 and M2 = 1 + 1 = 2. Part B is [4, 6] with mean 5 and M2 = 2. delta = 4, merged mean = 1 + 4 x 2 / 4 = 3, M2 = 2 + 2 + 16 x 2 x 2 / 4 = 20, variance 20 / 4 = 5. Check: [0, 2, 4, 6] has variance 5. Rule: mean = ma + d nb / n, M2 = M2a + M2b + d^2 na nb / n. This avoids the cancellation errors of computing E[x^2] - E[x]^2 in low precision.