Pidoku

Normalization Layers

Module 11 Lesson 11.e 45 min Difficulty 2/5

Prerequisites 10.d, 10.k, 11.a


Before you start: words you need#

WordPlain meaning
NormalizationRescaling a vector so its size stays in a predictable range.
LayerNormSubtract the mean, divide by the standard deviation, then apply a learned scale γ and shift β.
RMSNormDivide by the root mean square (the square root of the average of the squares), then apply γ. No mean, no shift.
γ (gamma)A learned per-feature scale, one number per hidden dimension, applied after normalising.
epsA tiny number (such as 1e-6) added before the square root so it never divides by zero.
ReductionAn operation that combines many values into one, such as a sum or a mean.
Residual streamThe running vector x that each layer adds its output to (10.i).
Fused kernelOne GPU kernel that does several steps in a single pass over memory (11.h).

1. What is it?#

An operation that rescales each token’s hidden vector so its size stays in a predictable range.

LayerNorm:  y = (x − mean(x)) / sqrt(var(x) + eps) · γ + β
RMSNorm:    y = x / sqrt(mean(x²) + eps) · γ

Both work on one token at a time, across its hidden dimension. Almost every 2026 open model uses RMSNorm: Llama, Qwen, DeepSeek, Gemma, gpt-oss. A plain dense layer applies it twice; newer designs apply it more often (section 5).

Both are tiny in FLOPs and both are memory bound: their cost is a story about moving bytes and launching kernels, not about arithmetic.


2. Why does it exist?#

Without normalisation, deep networks are hard to train: values drift in size from layer to layer and gradients explode or vanish. Putting a norm before each sub-layer (“pre-norm”) keeps every layer’s input at a steady scale while the residual stream carries the signal through.

At inference the training benefit is already baked into the weights, but the operation still runs: 72 times per forward pass for Qwen3-8B’s 36 layers, plus 72 more small ones on queries and keys. Each one reads and writes the activations. The engineering question is how to make it almost free.


3. Simple analogy#

A volume leveller on a mixing desk. Each channel is brought to a standard loudness before mixing, so no instrument drowns the others however it was recorded. The learned γ is the sound engineer’s preference for each channel, applied after levelling.


4. Tiny example: both norms, and a precision trap#

The program computes LayerNorm and RMSNorm on [1, 2, 3, 4]. Then it computes the RMS of real-sized vectors twice: once adding up the squares in BF16, once in FP32.

Go
// norm.go — LayerNorm and RMSNorm by hand, then why the sum of squares
// must be accumulated in FP32 even when the tensor is BF16.
package main

import (
	"fmt"
	"math"
	"math/rand"
)

// bf16 rounds a float32 to the nearest BF16 value (8 significant bits), round-half-to-even.
func bf16(x float32) float32 {
	b := math.Float32bits(x)
	b += 0x7FFF + (b>>16)&1
	return math.Float32frombits(b &^ 0xFFFF)
}

func main() {
	x := []float64{1, 2, 3, 4}
	const eps = 1e-6
	n := float64(len(x))

	var mean, variance, meanSq float64
	for _, v := range x {
		mean += v / n
		meanSq += v * v / n
	}
	for _, v := range x {
		variance += (v - mean) * (v - mean) / n
	}
	fmt.Print("layernorm:")
	for _, v := range x {
		fmt.Printf(" %7.4f", (v-mean)/math.Sqrt(variance+eps)) // gamma = 1, beta = 0
	}
	fmt.Printf("    (mean %.2f, variance %.4f)\n", mean, variance)
	fmt.Print("rmsnorm:  ")
	for _, v := range x {
		fmt.Printf(" %7.4f", v/math.Sqrt(meanSq+eps)) // gamma = 1
	}
	fmt.Printf("    (mean of squares %.2f)\n\n", meanSq)

	// The reduction: sum d squared values in BF16, and in FP32.
	rng := rand.New(rand.NewSource(1))
	for _, d := range []int{256, 1024, 4096, 8192} {
		var acc16, acc32 float32
		for i := 0; i < d; i++ {
			v := bf16(float32(rng.NormFloat64()))
			acc16 = bf16(acc16 + bf16(v*v)) // every partial sum rounded to BF16
			acc32 += v * v
		}
		rms16 := math.Sqrt(float64(acc16) / float64(d))
		rms32 := math.Sqrt(float64(acc32) / float64(d))
		fmt.Printf("d=%5d  rms with BF16 sum %.4f   with FP32 sum %.4f   error %5.1f%%\n",
			d, rms16, rms32, 100*math.Abs(rms16-rms32)/rms32)
	}
}

Output:

layernorm: -1.3416 -0.4472  0.4472  1.3416    (mean 2.50, variance 1.2500)
rmsnorm:    0.3651  0.7303  1.0954  1.4606    (mean of squares 7.50)

d=  256  rms with BF16 sum 1.0193   with FP32 sum 1.0454   error   2.5%
d= 1024  rms with BF16 sum 0.9270   with FP32 sum 1.0039   error   7.7%
d= 4096  rms with BF16 sum 0.7099   with FP32 sum 1.0091   error  29.7%
d= 8192  rms with BF16 sum 0.5340   with FP32 sum 1.0176   error  47.5%

Two lessons. First, RMSNorm does not centre the data (its outputs do not average to zero). In practice that does not hurt quality, and it saves one reduction.

Second, the precision trap. BF16 keeps only 8 significant bits (10.k). Once the running sum reaches a few hundred, adding a value near 1 changes it by less than one step of BF16 and the addition is rounded away. At Qwen3-8B’s hidden size of 4096 the norm comes out 30% wrong. Every real RMSNorm kernel accumulates in FP32, even when its inputs and outputs are BF16.


5. Technical explanation#

Why normalisation is memory bound#

For S tokens with hidden size d, in BF16:

Bytes:  read x (2·S·d) + write y (2·S·d) + read γ (2·d, cached)  ≈ 4·S·d
FLOPs:  square, add, multiply by rsqrt, multiply by γ             ≈ 4·S·d

Intensity ≈ 1 FLOP per byte, against an H100 ridge point of about 295

Utterly memory bound. The only optimisation that matters is not making extra passes over the data.

What an unfused RMSNorm costs#

Written as separate PyTorch operations, as in many reference implementations:

x.float()                 read x, write an FP32 copy          (twice the size)
.pow(2)                   read, write
.mean(-1, keepdim=True)   read, write one number per token
+ eps, torch.rsqrt        tiny
x * r                     read, write
.to(bf16) * γ             read, write
→ about 7 full passes over the tensor, and 6 or 7 kernel launches

A fused kernel does one pass: load a row into registers, sum the squares in FP32 with a warp and block reduction, compute rsqrt, multiply by γ, store. One read, one write, one launch.

What that saving is worth depends on the phase:

  • Prefill moves real bytes. For an 8,192-token prompt on Qwen3-8B, each activation tensor is 67 MB. Seven passes are about 470 MB, around 0.16 ms at 3 TB/s; a fused kernel moves 134 MB in 0.045 ms. Over 72 norms that is roughly 11 ms against 3 ms, in a prefill of about 160 ms.
  • Decode moves almost no bytes (64 tokens × 4096 × 2 bytes is half a megabyte). There the cost of an unfused norm is six or seven tiny kernels instead of one, each with a few microseconds of launch and start-up time. Multiplied by 72 norms per step, that can be milliseconds of a step that should take 5. CUDA graphs (5.f) remove the CPU side of the launch, but not the per-kernel start-up on the GPU.

Fuse with the neighbours#

The bigger win is fusing the norm with what surrounds it. The usual sequence in a layer is:

x = x + sublayer_output      ← residual add, elementwise
h = rmsnorm(x)               ← reduction + elementwise
next GEMM reads h

Engines replace the first two with one fused_add_rms_norm kernel: read the residual and the sub-layer output, add, write the new residual, normalise, write h. Two outputs from one pass. It is among the first custom kernels any engine writes; vLLM’s lives in csrc/layernorm_kernels.cu. Some engines go further and fuse the norm into the next GEMM’s input stage, or produce FP8 output directly for an FP8 GEMM (13.e).

The details you must match when porting a model#

Normalisation looks standard, but models differ in small ways that change the numbers:

eps value            1e-6 (Qwen3), 1e-5 (gpt-oss, Llama 3): read rms_norm_eps in config.json
eps placement        sqrt(mean + eps)  vs  sqrt(mean) + eps
where γ is applied   Llama: cast back to BF16, then multiply by γ
                     Gemma 3, Qwen3.5: multiply in FP32, then cast
γ parameterisation   Llama, Qwen3: y · γ        Gemma 3, Qwen3.5: y · (1 + γ), γ starts at 0

The (1 + γ) form is the trap. Load Gemma or Qwen3.5 weights into a Llama-style RMSNorm and nothing errors, because the shapes match, but every layer is scaled wrongly and the output is garbage.

Where norms sit in 2026 models#

Pre-norm, 2 per layer       Llama 3, Qwen3, DeepSeek-V3, gpt-oss
+ QK-norm                   RMSNorm on each query and key head before RoPE:
                            Qwen3, Gemma 3. Steadies attention at scale;
                            adds two small norms per layer (often fused with RoPE).
Sandwich norm               a norm before AND after each sub-layer: Gemma 3
                            (4 per layer, plus QK-norm)
Gated RMSNorm               RMSNorm(x) · SiLU(gate), at the output of linear-attention
                            layers in Qwen3-Next and Qwen3.5

Normalisations that are not used for LLM serving#

  • BatchNorm normalises across the batch. At inference it uses stored running averages, so it is safe in vision models. But it was never adopted in transformers, and any operation whose output depended on who else is in the batch would be unacceptable for serving: your answer would change with other people’s requests.
  • GroupNorm normalises groups of channels, and appears in diffusion U-Nets and VAEs.

6. Under the hood: a fused RMSNorm kernel#

one thread block per token (one row of length d)
  each thread loads d / blockDim elements with 16-byte vector loads
  each thread sums its squares in FP32
  warp reduction with __shfl_down_sync (4.c)
  block reduction through shared memory
  one thread computes rsqrt(sum / d + eps) and shares it
  each thread multiplies its elements by rsqrt × γ and stores BF16

Vector loads matter: one 16-byte load brings eight BF16 values instead of one, so there are eight times fewer load instructions and every warp access is coalesced (6.b). A Triton version (6.e) is about 20 lines and reaches the same bandwidth.


7. Performance implications#

  • Normalisation is a fraction of a percent of the FLOPs and can still be several percent of the time if it is unfused. It is the textbook case of “count bytes and launches, not FLOPs”.
  • At prefill, fusion saves bytes. At decode, it saves kernels.
  • Fusing the residual add into the norm removes another full read and write of the residual stream per sub-layer.
  • QK-norm and sandwich norms add work. Two to four extra small kernels per layer if they are not fused into RoPE or the attention kernel.

8. Production implications#

  • Check that your engine uses fused norms. In a profile you should see rms_norm or fused_add_rms_norm kernels, not a chain of pow, mean, rsqrt and mul.
  • Match the reference exactly when porting a model: eps, where γ is applied, (1 + γ) or γ, FP32 accumulation.
  • Budget for newer norm placements in custom kernels: QK-norm, sandwich norms, gated norms.
  • Never use batch-dependent normalisation in a serving path.

9. Common mistakes#

  1. Leaving norms unfused. Several tiny kernels per norm, 72 or more norms per pass.
  2. Accumulating the sum of squares in BF16. Section 4: 30% wrong at d = 4096.
  3. Using the wrong eps. A small but real difference in every output.
  4. Loading (1 + γ) weights into a γ-style norm. No error, wrong model.
  5. Judging a norm’s cost by its FLOPs. It is memory and launches.
  6. Using LayerNorm where the model specifies RMSNorm (or the reverse). With β = 0 and matching shapes this can load silently and compute something different.

10. Hands-on exercise#

  1. Run norm.go. Change the BF16 accumulation to use pairwise summation (add neighbours, then pairs of pairs). How much of the error disappears, and why?
  2. Implement RMSNorm in PyTorch as separate ops, with torch.compile, and with your engine’s fused kernel. Benchmark all three on a (64, 4096) and an (8192, 4096) BF16 tensor and report GB/s. Which comparison is about bytes and which about launches?
  3. Write a fused RMSNorm in Triton (6.e) and compare it with PyTorch’s.
  4. Load Qwen3-8B and print the model. Count the RMSNorm modules per layer, including q_norm and k_norm.
  5. Profile one decode step of a real model and add up the time spent in normalisation kernels.

11. Interview questions#

  1. Why is normalisation memory bound despite doing almost no FLOPs?
  2. What is the difference between LayerNorm and RMSNorm, in parameters and in cost?
  3. Why must the reduction be done in FP32? What happens if it is not?
  4. What does fusing an RMSNorm save at prefill, and what does it save at decode?
  5. What is fused_add_rms_norm and why does it produce two outputs?
  6. What is QK-norm, and which 2026 models use it?
  7. Why is BatchNorm unsuitable for transformer serving?

12. Further reading#

Checked on 12 November 2026.

↑↓ navigate↵ openesc close

100% drag to pan · scroll or pinch to zoom · double-click to zoom in