Normalization kernels: compute the right statistics and reuse the row
Specify LayerNorm axes, population variance, epsilon placement, parallel moment combination, and resource-limited reuse.
On this page
The question for today
What you’ll understand
- Compute LayerNorm with a stated variance denominator and epsilon.
- Combine count, mean, and centered-square summaries correctly.
- Distinguish LayerNorm, RMSNorm, and BatchNorm before fusing or changing a kernel.
A normalization kernel combines reductions with elementwise output, making it a tempting fusion target. Its semantics are easy to change accidentally: the normalized axes, variance denominator, epsilon location, and affine parameters all matter. Derive those choices and a stable statistics algorithm before optimizing how long input values remain in registers or shared memory.
Normalize a precisely defined population
For the LayerNorm variant used here, each chosen row contains n feature values. Compute its mean and population variance using denominator n, add positive epsilon inside the square root, then apply per-feature scale and bias. PyTorch 2.14 documents population variance for LayerNorm and normalization over the configured trailing dimensions. Dividing by n−1 would instead use a sample-variance correction and change the operation. Epsilon is a numerical and model parameter, not a value that may be moved outside the square root while preserving the same function.
LayerNorm uses each instance's selected feature population, unlike BatchNorm's different statistical axes and training/evaluation behavior. RMSNorm omits the mean subtraction and uses a different normalization statistic; it is not merely a faster spelling of identical LayerNorm semantics. Affine parameter shapes also matter when several trailing dimensions are normalized. Confirm broadcasting, dtype conversion, and output layout. Constant rows and single-feature rows are useful semantic tests: with positive epsilon, their centered values are zero and the output follows the bias rather than requiring division by zero.
Stable moment summaries support parallel combination
Computing variance as mean of squares minus square of mean can lose significant digits when the mean is large and variation is small. A centered two-pass method or a Welford-style count/mean/centered-square summary can improve stability. Neither method is exact in finite precision, and accumulation dtype remains important. A parallel implementation must combine summaries with their counts rather than average two means equally when their populations differ. Empty masked groups require an explicit identity case before divisions by count.
A useful summary stores count n, mean μ, and M2, the sum of squared deviations from that mean. When two groups merge, the difference between their means contributes an additional centered-square term. After the merge, divide the combined M2 by the intended population count for this LayerNorm variant. Padding a row with zeros and then treating padded lanes as genuine observations changes both mean and variance. Masked lanes must affect the reduction identity and count consistently, including the final partial tile.
Keep row reuse within the resource and accuracy budget
A fused row kernel can reuse loaded feature values while computing statistics and normalized output, avoiding some intermediate writes and rereads. A wide row can require too many registers or too much shared memory, leading to spills or less parallelism. Multiple-pass designs may then be better despite extra traffic. Affine scale and bias also require access and can change the bottleneck. Benchmark complete forward semantics and any required backward work separately; a forward-only improvement does not imply the same training-step improvement.
The function lab represents a small exact variance family. For the symmetric two-value row [−x,x], the mean is zero and population variance is x². Reset, set a=1 and x=0.50 in y=ax², predict y=0.25, then Play or Step. Separately Reset, set a=1 and x=1, predict y=1, then Play or Step. The graph cannot normalize an arbitrary row, set epsilon, or model rounding and GPU execution. Use it to see how small feature spread changes the variance scale, then compute the epsilon and affine effects by hand.
Work it through
Normalize two features with an explicit epsilon
For row [1,3], use population variance, epsilon 3, per-feature gamma 2, and beta 0. The deliberately large epsilon makes its placement visible.
The mean is (1+3)/2=2. Squared deviations are one and one, so population variance is (1+1)/2=1.
The denominator is sqrt(1+3)=2. Centered values [−1,1] become [−0.5,0.5], then gamma 2 produces [−1,1].
Combining singleton summaries also gives mean two and M2=0+0+(3−1)²×1×1/2=2. Dividing M2 by count two recovers variance one before the same normalization.
The output is [−1,1] under the stated operation. Using n−1 or adding epsilon outside the square root would compute a different result.
The living notebook
Explore the model
Interactive lab · function
The variance of a symmetric two-feature row
For row [−x,x], variance is x². Reset, set a=1 and x=0.50, predict y=0.25, then Play or Step. Separately Reset, set a=1 and x=1, predict y=1, then Play or Step. This fixed quadratic has no arbitrary row, epsilon control, affine transform, floating-point simulation, or GPU kernel.
- y at chosen x
- 0.608
- Tangent slope · 2ax
- 1.35
- Signed area · ax³/3
- 0.182
This lab uses only y = ax². Playback traces the curve within the fixed integration interval from 0 to x; it does not estimate numerical error or change the chosen point. Parameter changes pause playback and recompute the model at the current elapsed time. Reset restores both parameters and returns time to zero. Playback starts paused. Adjust either parameter, then choose Play or Step.
Look forVariance scale and epsilon must be considered together under the actual normalization definition.
Pause & reason
Check your understanding
Your turn
Try it yourself
A row contains [7,7,7], gamma values [2,3,4], beta values [1,2,3], and positive epsilon. Find its LayerNorm output under the defined population-variance operation.
Take a moment to make a prediction or work it out on paper. Open a hint when you need one.
Give me a hint
Compute centered values before applying scale and bias.
Compare with the solution
Mean is seven and variance zero. Every centered value is zero, so division by sqrt(epsilon) still gives zero; multiplying by gamma and adding beta produces [1,2,3]. This is a useful constant-row correctness case and assumes finite values and the specified positive epsilon.
Keep the idea
Take it with you
- Axes, variance denominator, epsilon placement, and affine shapes define the operation.
- Parallel statistics require count-aware stable combination.
- Row reuse trades memory traffic against resource use and numerical behavior.
Read further
Original sources and deeper explanations to follow at your own pace.
Optional progress, saved in this browser when available. Revisit any lesson at any time.
Lesson not marked complete.