Skip to content
AI.info

Training and optimization

Normalization Layers and Training Behavior

Compare batch, layer, group, and related normalization schemes, including train/eval state, small-batch behavior, and affine parameters.

By the end you can

Comparison

Normalization methods summarize different sets of activations

The chosen axes determine which examples or features shape one another.

The fourth card is no longer a research curiosity. Drop LayerNorm's re-centering step and the layer gets cheaper. Zhang and Sennrich tested that in 2019, starting from the hypothesis “that re-centering invariance in LayerNorm is dispensable”. What they found: “Extensive experiments on several tasks using diverse network architectures show that RMSNorm achieves comparable performance against LayerNorm but reduces the running time by 7%~64% on different models.”

PyTorch now ships the layer as torch.nn.RMSNorm, defined as y = x / RMS(x) * gamma with RMS(x) = sqrt(eps + mean(x^2)) and elementwise_affine=True. There is no mean-subtraction term anywhere in that formula. Meta runs it in production. Its own disclosure of LLaMA, in 2023, says: “To improve the training stability, we normalize the input of each transformer sub-layer, instead of normalizing the output. We use the RMSNorm normalizing function, introduced by Zhang and Sennrich (2019).”

That is what the card's “efficient transformer variants” actually names: a measured 7%–64% runtime reduction, a shipped framework layer, and a production model that normalizes this way.

FigureComparison · 4 columns

BatchNorm

Uses batch statistics for each channel during training.

  • State: running statistics
  • Strength: effective in many CNNs
  • Risk: small or shifted batches
  • Eval: uses stored estimates

LayerNorm

Normalizes features within each example.

  • State: no running batch mean
  • Strength: sequence models
  • Risk: feature-axis assumptions
  • Eval: same statistic rule

GroupNorm

Normalizes channel groups within each example.

  • State: no running batch mean
  • Strength: small vision batches
  • Risk: group choice
  • Eval: same statistic rule

RMS-style norm

Uses root-mean-square scale without centering.

  • State: no running mean
  • Strength: efficient transformer variants
  • Risk: recipe dependence
  • Eval: same statistic rule

Visual

BatchNorm has learned parameters and persistent statistics

A complete checkpoint must preserve both categories.

The two categories are not stored the same way. Gamma and beta are learned parameters that gradients update. The running mean and variance are buffers that no gradient touches. They are advanced by a fixed rule on each training forward pass, then substituted for the batch statistics at evaluation time. Restore the first category, reset the second, and you have loaded a model whose weights are right and whose evaluation behavior is not. Nothing in the training loss reports it.

FigureLayers · 5 layers
  1. 01

    Batch activations

    Current examples produce a channel mean and variance during training.

  2. 02

    Normalized values

    Activations are centered and scaled using batch statistics.

  3. 03

    Affine parameters

    Learned gamma and beta restore flexible scale and offset.

  4. 04

    Running estimates

    Moving statistics summarize training batches for evaluation mode.

  5. 05

    Evaluation output

    Stored estimates replace current batch statistics during inference.

Example

Normalization failures that masquerade as data shift

These cases can change predictions without changing the learned matrix weights.

  • Mode bug: Evaluation runs with BatchNorm in training mode, making predictions depend on nearby examples. The switch that turns that off is not the same switch in every framework. PyTorch documents Module.train() and Module.eval() as “Set the module in training mode” and “Set the module in evaluation mode”, each adding that “This has an effect only on certain modules... e.g. Dropout, BatchNorm, etc.”; freezing weights there is a separate mechanism, requires_grad. Keras 3 makes this layer an explicit exception: “However, in the case of the BatchNormalization layer, setting trainable = False on the layer means that the layer will be subsequently run in inference mode (meaning that it will use the moving mean and the moving variance to normalize the current batch, rather than using the mean and variance of the current batch).” The same page states that “'Frozen state' and 'inference mode' are two separate concepts” — everywhere except here. One intent, freeze this layer. Two different normalization behaviors.
  • Stale statistics: Fine-tuning changes representations while running means and variances remain poorly adapted. The gap has been measured rather than guessed at. Schneider and colleagues recomputed BatchNorm statistics on the images actually being served, in 2020, and found that the correction “consistently improves the robustness across 25 different popular computer vision models”. A group at Google Brain reached “an mCE of 60.28% on the challenging ImageNet-C dataset” the same year with the same one-line change, which they call prediction-time batch normalization.
  • Tiny micro-batches: Per-device statistics are noisy even though the global nominal batch is large. Wu and He gave that noise a shape in 2018: “BN's error increases rapidly when the batch size becomes smaller, caused by inaccurate batch statistics estimation”.
  • Distributed mismatch: Workers maintain different statistics or synchronize them under an unexpected policy. The unexpected policy is the shipped default. Keras 3's BatchNormalization carries synchronized=False in its signature, described in its own argument documentation as: “If False, each replica uses its own local batch statistics.”
  • Incomplete checkpoint: Affine parameters load correctly while running statistics are missing or reset. Gamma and beta arrive through the parameter dictionary. The running mean and variance arrive as buffers, so a loader that tolerates missing keys hands back a model that trains identically and evaluates differently.

Steps

Debug normalization with mode and state tests

Use small, reproducible comparisons before changing architecture.

Step 4 is worth a number rather than a hope. Schneider and colleagues replaced the training-set BatchNorm statistics with statistics of the corrupted test images and reported: “Using the corrected statistics, ResNet-50 reaches 62.2% mCE on ImageNet-C compared to 76.7% without adaptation.” No retraining. No change to a single learned weight. The whole gain came from recomputing buffers, and a second group at Google Brain reproduced the effect independently.

Step 5 says architecture-specific because the same layer in a different position changes what the optimizer requires. Xiong and colleagues showed in 2020 that in Post-LN Transformers “the expected gradients of the parameters near the output layer are large”. That is why the warm-up stage is needed at all. In Pre-LN Transformers “the gradients are well-behaved at initialization”, and “Pre-LN Transformers without the warm-up stage can reach comparable results with baselines while requiring significantly less training time”.

Nguyen and Salazar had reported the same thing the year before: “First, we show that pre-norm residual connections (PRENORM) and smaller initializations enable warmup-free, validation-based training with large learning rates.” They measured an average +1.1 BLEU over bilingual baselines on five low-resource pairs, and 32.8 BLEU on IWSLT '15 English–Vietnamese. They also noted that in the high-resource WMT '14 English–German setting “PRENORM degrades performance”. The winner reverses with the setting. That is the whole reason step 5 is an experiment and not a recommendation.

FigureProcess · 5 steps
  1. 1. Compare train and eval outputs

    Run the same examples under both modes and quantify the difference.

  2. 2. Inspect stored statistics

    Check ranges, update counts, and missing or reset buffers.

  3. 3. Vary micro-batch composition

    Test whether predictions change when unrelated examples share a batch.

  4. 4. Recompute when appropriate

    Evaluate whether recalibrating statistics improves a fine-tuned checkpoint.

  5. 5. Compare alternative norms

    Use LayerNorm or GroupNorm only through controlled architecture-specific experiments.

Gradient accumulation does not enlarge BatchNorm’s observed micro-batch

Each forward pass computes BatchNorm statistics from the micro-batch present on that device unless synchronized normalization is used. Accumulating gradients later does not retroactively combine those activation statistics.

A global batch of 512 can therefore behave like BatchNorm batches of eight. Inspect the actual forward-pass group.

This is not folklore, and it is not an outsider's complaint. BatchNorm's own author conceded it in print two years after the original paper. Sergey Ioffe's 2017 paper on Batch Renormalization opens with the limit: “However, its effectiveness diminishes when the training minibatches are small, or do not consist of independent samples.” The cause it names is “the dependence of model layer inputs on all the examples in the minibatch, and different activations being produced between training and inference”. That is the micro-batch problem and the mode bug, in one sentence, from the person who introduced the layer.

Wu and He measured the size of it a year later: “On ResNet-50 trained in ImageNet, GN has 10.6% lower error than its BN counterpart when using a batch size of 2”. It holds because “GN's computation is independent of batch sizes” — the statistic is computed per example, so batch size never enters it.

Synchronization across devices is an opt-in that an engineer has to name. PyTorch offers no flag on the layer. Cross-device statistics live in a separate class, torch.nn.SyncBatchNorm (eps=1e-05, momentum=0.1), whose statistics are “calculated per-dimension over all mini-batches of the same process groups”. The documentation says it must be applied through torch.nn.SyncBatchNorm.convert_sync_batchnorm() before the network is wrapped in DistributedDataParallel. Skip that conversion and every worker normalizes with its own local micro-batch.

Optimizer batch size and normalization batch size can be different.

Dataset standardization and network normalization solve different problems

Input standardization uses statistics from the training data to place raw features on suitable scales. A normalization layer transforms intermediate activations using a rule embedded in the model.

The layer may contain learned affine parameters and mode-dependent state. Replacing one with the other changes both the function and the training dynamics.

“Normalize the data” and “add normalization layers” are not interchangeable instructions.

Analogy

Adjusting audio levels with different reference groups

Balancing microphone levels can take its reference from everyone in the room, from each speaker’s own range, or from small groups of channels. The chosen reference changes what counts as loud.

A fader setting is not part of the recording. This reference is part of the model. The layer carries learned affine parameters that can undo parts of the normalization it just applied, and running statistics a checkpoint has to save. Choosing the axis is only the first of those decisions.

The rate those statistics move at is a default nobody reads. PyTorch’s BatchNorm2d uses eps=1e-05 and momentum=0.1, updating as x̂_new = (1 − momentum) × x̂ + momentum × x_t. Keras 3’s BatchNormalization uses momentum=0.99 and epsilon=0.001 for the same layer, updating as moving_mean = moving_mean * momentum + mean(batch) * (1 - momentum). The same word runs in opposite directions in the two libraries. PyTorch says so in a note: “This momentum argument is different from one used in optimizer classes and the conventional notion of momentum”. A checkpoint carries whichever convention the code was written against.

Normalization defines a reference set for scale, and that reference becomes part of the model.

Normalization can improve optimization without explaining every gain

Normalization alters scale, parameterization, noise, and gradient flow. Its benefit may not come from one simple story such as “reducing internal covariate shift.”

Focus on observable consequences. These include stable rates, faster progress, batch sensitivity, evaluation consistency, and resource cost. Each one is something you can measure on your own model, rather than something you accept from a paper's title.

Use normalization as an engineered transformation, not a slogan about hidden distributions.

Case

A fourteenfold speed-up that outlived its own explanation

Ioffe and Szegedy put the headline in their own abstract in 2015: “Applied to a state-of-the-art image classification model, Batch Normalization achieves the same accuracy with 14 times fewer training steps, and beats the original model by a significant margin”. The title of that paper also names its explanation: reducing internal covariate shift.

The explanation was tested three years later. Santurkar and colleagues found that “such distributional stability of layer inputs has little to do with the success of BatchNorm”. What they put in its place is a property of the loss surface rather than of the activations: “it makes the optimization landscape significantly smoother”.

One smaller detail from the 2015 paper is worth carrying, because it is the habit this whole lesson is about. Its two hosted copies do not report the same headline error rate. It is “4.9% top-5 validation error (and 4.8% test error)” on arXiv, and “4.82% top-5 test error” in the published proceedings. That is why only the training-step figure is quoted here. The speed-up survived the explanation. The explanation did not.

Key takeaways