Topic 52 of 62 · Wider ML toolkit
BatchNorm: sharing statistics across examples
EasyWhat does BatchNorm normalize, and why is it usually not the right norm inside an autoregressive Transformer?
1 · Start with the intuition
Imagine one feature channel becoming much larger than the others. BatchNorm estimates that channel’s mean and variance from many observations, then standardizes it. The important question is which observations it pools: they include other examples, not just the token being processed.
2 · How the mechanism works
Mechanism step 1 of 3 · no question to answer
Choose the channel
For images [B,C,H,W], pool B,H,W separately for each C. For BatchNorm1d on [B,C,T], pool B,T.
Next, we will look at: Center and scale. Move on when this operation makes sense.
Visualize which values share statistics
Derived toy tensor [B=2,T=3,C=4]. Select any cell: orange outlines your selection; teal cells contribute to its normalization statistics. Each cell shows input ↓ output. Training behavior, ε=10⁻⁵, γ=1, β=0; learned affine transforms are omitted.
Across batch B and positions T, separately per channel C.
Sample 0 · rows = positions T
Sample 1 · rows = positions T
Selected: sample 0, position 0, channel 0 · 6 values share statistics
Channel c across both samples and every position
(x − mean_B,T) / √(var_B,T + ε)
μ=3.500, variance=3.917, √(variance+ε)=1.979
(1 − 3.500) / 1.979 = -1.263
Try selecting sample 0, then moving “Shift sample 1 only”: only BatchNorm changes sample 0’s output. A global offset cancels in the centered norms but not RMSNorm. Variance uses the population denominator; rounded displays may differ slightly from the full-precision calculation.
# x is [B,T,C]; C=4 nn.BatchNorm1d(C)(x.transpose(1, 2)).transpose(1, 2)
Which one do I need?
Normalization controls the scale seen by sublayers; it does not replace a task loss or an explicit generalization regularizer. Preserve the norm used by a pretrained checkpoint rather than swapping it at inference.
| Method | Choose it when… | Train → eval |
|---|---|---|
| BatchNorm | CNN feature maps with adequate batch statistics. Not the usual decoder norm: sequence-wide training statistics can leak future-token information. | Usually frozen running mean/variance in eval; with track_running_stats=False, uses batch statistics even in eval. |
| LayerNorm | A standard Transformer choice when per-token centering and scaling are wanted; independent of batch size and sequence neighbors. | Current token statistics in both train and eval; no running averages. |
| GroupNorm | CNNs and convolutional diffusion blocks with small batches. Standard sequence-wide GroupNorm is not a causal per-token decoder norm. | Current sample/group statistics in both train and eval; no running averages. |
| RMSNorm | Common in modern decoder-only Transformers when controlling activation scale without centering is sufficient; fewer normalization operations, not a guaranteed speedup. | Current token RMS in both train and eval; no running averages. |
For tensors [B,T,C], token-local LayerNorm(C)/RMSNorm(C) do not read future positions. BatchNorm1d and GroupNorm after transposing to [B,C,T] do. A causal attention mask does not undo leakage introduced by a sequence-wide normalization.
3 · The governing equation
μ_c = mean_{b,t}(x_btc)
σ²_c = mean_{b,t}((x_btc − μ_c)²)
y_btc = γ_c (x_btc − μ_c) / √(σ²_c + ε) + β_cNotation: This equation describes the training forward pass for [B,T,C] transposed to PyTorch’s [B,C,T]. Forward variance uses denominator B·T; PyTorch’s running variance update uses the unbiased estimator.
Pooling observations works well for many convolutional models with representative batches. But now an example’s output depends on its neighbors, small effective sample counts can give noisy estimates, and a shifted deployment distribution can disagree with running statistics. Pooling sequence positions also lets an early token depend on later activations during training. Token-local LayerNorm and RMSNorm avoid these dependencies, which is why they are the standard decoder choices.
4 · Put concrete numbers on it
Worked numbers (from stated assumptions)5 · Common misconception to avoid
BatchNorm does not normalize each example independently. A batch of one is not automatically invalid if spatial/sequence axes supply multiple values, but one value per channel cannot support the usual training variance estimate.
Scenario practice · Choose the normalization for the scenario
8 scenarios, ordered Easy → Medium → Hard. Choose the best option, then rate your confidence. A first miss gives a nudge and one retry; a second miss or reveal gives an explanation and zero credit.
Session-only practice. Changing level, leaving, or reloading resets this set.
6 · Self-check & interview synthesis
Explain it in your own words first
Before revealing the reference answer, try answering the opening question aloud in four beats: what it is → how the math works → what trade-off it makes → a concrete number or failure mode.
Follow-up question interviewers often ask next
MediumDoes gradient accumulation make BatchNorm behave as though it saw one large batch?
Show follow-up reasoning
No. Each forward pass computes statistics on its own microbatch. Accumulating gradients changes the optimizer’s effective batch, not the BatchNorm statistics used by those forward passes.