advanced24 min studyLesson 477 in Engineering

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

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.

μ=1n∑ixi,v=1n∑i(xi−μ)2,yi=γixi−μv+ϵ+βi\mu=\frac1n\sum_i x_i,\qquad v=\frac1n\sum_i(x_i-\mu)^2,\qquad y_i=\gamma_i\frac{x_i-\mu}{\sqrt{v+\epsilon}}+\beta_i
n is a positive integer, ε>0, and x, γ, β are finite dimensionless values in this teaching model. v is population variance with denominator n. Real APIs define nonfinite behavior, arithmetic precision, normalized axes, and affine broadcasting separately.↔ Scroll wide equations horizontally.

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.

n=nA+nB,δ=μB−μA,μ=μA+δnBn,M2=M2A+M2B+δ2nAnBnn=n_A+n_B,\quad \delta=\mu_B-\mu_A,\quad \mu=\mu_A+\delta\frac{n_B}{n},\quad M2=M2_A+M2_B+\delta^2\frac{n_A n_B}{n}
Both groups have positive counts and finite values; M2 denotes their centered-square sum rather than variance. This is a real-arithmetic merge identity. Empty groups need a separate identity rule, and floating-point rounding still affects its implementation.↔ Scroll wide equations horizontally.

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.

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.

  1. The mean is (1+3)/2=2. Squared deviations are one and one, so population variance is (1+1)/2=1.

  2. The denominator is sqrt(1+3)=2. Centered values [−1,1] become [−0.5,0.5], then gamma 2 produces [−1,1].

  3. 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 result

The output is [−1,1] under the stated operation. Using n−1 or adding epsilon outside the square root would compute a different result.

Explore the model

Interactive lab

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.

The variance of a symmetric two-feature rowThis 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. Current readings: y at chosen x: 0.608; Tangent slope · 2ax: 1.35; Signed area · ax³/3: 0.182. All parameters are adjustable with the labeled controls below.−2.4−1.201.22.4−9−4.504.59xy(x, ax²)
y = ax²TangentSigned integral
y at chosen x
0.608
Tangent slope · 2ax
1.35
Signed area · ax³/3
0.182
t = 0 s

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.

Check your understanding

Why can averaging two block means equally produce the wrong normalized result?

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.

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.