Normalization Layers in Deep Learning

Normalization layers rescale intermediate activations so that later layers receive inputs with a more controlled scale. BatchNorm, LayerNorm, and GroupNorm compute a mean and variance over different groups of values. RMSNorm uses a root mean square without subtracting a mean. Choosing the group determines whether one example depends on its batch-mates; the treatment of running statistics determines what changes at evaluation time.

Centering and scaling a group of values

\[\hat x=\frac{x-\mu}{\sqrt{\sigma^2+\epsilon}},\qquad y=\gamma\hat x+\beta\]

Here \(\mu\) and \(\sigma^2\) are the mean and variance within the selected group, and \(\epsilon>0\) prevents division by zero. The learned scale \(\gamma\) and shift \(\beta\) let training adjust the output. With identity affine parameters, the normalized group has mean zero and variance \(\sigma^2/(\sigma^2+\epsilon)\), close to one when the variance is large relative to \(\epsilon\). A constant group becomes zero. These statements describe the values used to compute the statistics, not a population distribution or BatchNorm outputs computed with stored statistics.

An affine scale and shift do not generally recover information removed by normalization. LayerNorm maps a vector and a constant-shifted copy to the same normalized vector, so fixed \(\gamma\) and \(\beta\) cannot distinguish those two inputs. Initialization still affects signal propagation; see Weight Initialization and Gradient Flow in Deep Networks.

Which axes each layer averages over

Take a convolutional activation of shape \((N,C,H,W)\): batch, channels, height, width. Each table row specifies a group sharing one mean and variance. Here LayerNorm is configured to normalize all \((C,H,W)\) values within an example; other choices are possible. โ€œStatistics countโ€ counts groups, not statistically independent estimates.

LayerReduces overStatistics countUses other examples to compute statistics?
BatchNorm\(N,H,W\)\(C\)yes
LayerNorm\(C,H,W\)\(N\)no
InstanceNorm\(H,W\)\(N\times C\)no
GroupNorm\(C/g,H,W\)\(N\times g\)no

Among these configurations, only BatchNorm combines examples when computing input statistics. The table describes BatchNorm in training mode and InstanceNorm using current-input statistics. BatchNorm normally uses stored statistics at evaluation; InstanceNorm can also be configured to store statistics. The code below computes means only, making the group counts visible before we implement the normalization.

import numpy as np

x = np.random.default_rng(0).standard_normal((8, 4, 5, 5))   # N, C, H, W

bn = x.mean(axis=(0, 2, 3))              # shape (4,)   one per channel
ln = x.mean(axis=(1, 2, 3))              # shape (8,)   one per example
inorm = x.mean(axis=(2, 3))              # shape (8, 4) one per example-channel
gn = x.reshape(8, 2, 2, 5, 5).mean(axis=(2, 3, 4))   # (8, 2) two groups

print(bn.shape, ln.shape, inorm.shape, gn.shape)
# (4,) (8,) (8, 4) (8, 2)

Batch normalization

BatchNorm uses \(NHW\) values per channel for a convolutional input. Changing the other examples can change a fixed exampleโ€™s normalized output during training. This variability can have a regularizing effect, though it is not always helpful. Inference can also use batches, including a batch of one. With running statistics enabled, evaluation uses accumulated estimates so that the output no longer depends on the other examples in that inference batch:

\[\mu_{\text{run}}\leftarrow(1-m)\mu_{\text{run}}+m\mu_{\text{batch}}\]

Here \(m\) is the fraction assigned to the new batch statistic, not the batch size or optimizer momentum. A running variance is maintained as well. In PyTorch BatchNorm, training normalization uses variance with divisor \(K\), while the running-variance update uses the unbiased estimate with divisor \(K-1\), where \(K=NHW\). With track_running_stats=False, evaluation also uses batch statistics.

A small \(N\) does not automatically make BatchNorm unusable: spatial positions also contribute, although correlations reduce how much information they add. Having only one value per channel cannot provide a useful variance estimate; PyTorch rejects that training case. Stored statistics may fit a shifted deployment distribution poorly, so evaluation quality must be checked. For a newly constructed convolution immediately followed by BatchNorm, bias=False avoids a channelwise offset that training-time centering cancels. Removing an existing bias at evaluation requires a corresponding adjustment to the stored mean.

def normalize_with_stats(x, mean, var, eps=1e-5):
    return (x - mean) / np.sqrt(var + eps)

for batch in (np.array([1., 3.]), np.array([1., 3., 5.])):
    train = normalize_with_stats(batch, batch.mean(), batch.var())
    evaluation = normalize_with_stats(batch, 2.0, 1.0)
    print(len(batch), round(float(train[0]), 6), round(float(evaluation[0]), 6))
# 2 -0.999995 -0.999995
# 3 -1.224743 -0.999995

The first value stays at 1. Its training output changes with the batch; its evaluation output stays fixed because both calls use mean 2 and variance 1. These stored values are supplied for illustration. A trained layer would accumulate them during training. Scale and shift are set to 1 and 0 here.

Layer normalization

LayerNorm computes statistics separately for each example over the configured feature axes, using the same rule in training and evaluation. For transformer activations shaped \((N,T,D)\), the usual choice is the last axis \(D\): each token has its own mean and variance across features. It does not mix tokens or examples. Normalizing over \((T,D)\) would be a different operation and could mix future tokens into an autoregressive computation. Other layers, such as dropout, can still behave differently between training and evaluation.

For the vector [1,2,3,4], the mean is 2.5 and the variance is (2.25 + 0.25 + 0.25 + 2.25)/4 = 1.25. Subtracting 2.5 and dividing by \(\sqrt{1.25+\epsilon}\) produces the four values below. keepdims=True retains an axis of length one so that NumPy broadcasts each groupโ€™s statistics over its values. The printed standard deviation rounds to 1; it is slightly smaller before rounding.

def layer_norm(x, gamma, beta, eps=1e-5):
    """x: (batch, features). Normalizes over the last axis."""
    mu = x.mean(axis=-1, keepdims=True)
    var = x.var(axis=-1, keepdims=True)
    return gamma * (x - mu) / np.sqrt(var + eps) + beta

x = np.array([[1.0, 2.0, 3.0, 4.0]])
out = layer_norm(x, np.ones(4), np.zeros(4))
print(np.round(out, 4))            # [[-1.3416 -0.4472  0.4472  1.3416]]
print(round(float(out.mean()), 6), round(float(out.std()), 4))   # 0.0 1.0

Group normalization

GroupNorm splits the \(C\) channels into \(g\) equal groups and normalizes each groupโ€™s channels and spatial positions separately within each example. The positive integer \(g\) must divide \(C\). With \(g=1\), its normalized values match LayerNorm over \((C,H,W)\); with \(g=C\), they match InstanceNorm using input statistics. This equivalence assumes the same epsilon and compatible affine parameters. PyTorch GroupNorm learns one scale and shift per channel, whereas LayerNorm over \((C,H,W)\) can learn them for every element of that shape.

GroupNorm uses current-input statistics in both training and evaluation. A fixed exampleโ€™s output is unchanged by its batch-mates, but this does not guarantee equal training accuracy at different batch sizes: the optimizer still sees different batches. It is useful when small batches make BatchNorm unreliable. A choice such as 32 groups is valid only when the channel count permits it. InstanceNorm removes each channelโ€™s spatial mean and normalizes its spatial variation, which can suppress task-relevant intensity information or help a style-transfer model. The task determines whether that loss of information is useful.

def group_norm_values(x, groups, eps=1e-5):
    n, c, h, w = x.shape
    if not 1 <= groups <= c or c % groups:
        raise ValueError("groups must divide the channel count")
    grouped = x.reshape(n, groups, c // groups, h, w)
    axes = (2, 3, 4)
    mean = grouped.mean(axis=axes, keepdims=True)
    var = grouped.var(axis=axes, keepdims=True)
    return ((grouped - mean) / np.sqrt(var + eps)).reshape(x.shape)

images = np.arange(32., dtype=float).reshape(2, 4, 2, 2)
normalized = group_norm_values(images, 2)
print("group means are zero:", np.allclose(normalized.reshape(2, 2, -1).mean(-1), 0))
print("first example unchanged alone:", np.allclose(normalized[:1], group_norm_values(images[:1], 2)))
# group means are zero: True
# first example unchanged alone: True

Reshaping exposes the group axis; the reduction then covers channels within a group and both spatial axes. This example stops before the learned affine step. In a full layer, per-channel scale and shift broadcast with shape (1,C,1,1).

RMS normalization

RMSNorm drops the mean subtraction and the shift, rescaling by the root mean square alone:

\[y=\gamma\cdot\frac{x}{\sqrt{\frac{1}{d}\sum_i x_i^2+\epsilon}}\]

Here \(d\) is the number of features in the group, usually the last dimension of a token representation. RMSNorm has no learned shift in this formulation. It removes the mean-subtraction operation and uses fewer affine parameters than LayerNorm with a shift; actual speed depends on implementation and hardware. Whether omitting centering helps a particular model is an empirical question, not a consequence of the formula.

def rms_norm(x, gamma, eps=1e-6):
    rms = np.sqrt(np.mean(x ** 2, axis=-1, keepdims=True) + eps)
    return gamma * x / rms

print(np.round(rms_norm(np.array([[1.0, 2.0, 3.0, 4.0]]), np.ones(4)), 4))
# [[0.3651 0.7303 1.0954 1.4606]]

All four outputs are positive with \(\gamma=1\), while LayerNorm centers the input and produces both signs. Dividing by a positive RMS preserves each inputโ€™s sign before the learned scale. A negative learned \(\gamma\) can reverse it. RMSNorm does not force the output mean to zero.

Placement: pre-norm versus post-norm

Let \(F\) be a sublayer such as attention or a feed-forward network. Post-norm computes \(\operatorname{Norm}(x+F(x))\): add the branch output to the residual input, then normalize. Pre-norm computes \(x+F(\operatorname{Norm}(x))\): normalize the branch input and leave the direct residual addition outside the normalization.

The derivative of a pre-norm block contains an identity term from the direct path, plus the derivative through its branch. This can make deep stacks easier to optimize, but branch contributions can cancel and stable gradients are not guaranteed. Xiong et al. studied why pre-norm can reduce the need for learning-rate warmup in their transformer settings. Architecture, initialization, and training recipe still matter. Pre-norm stacks often include a final normalization before the output head.

Self-attention, masking, and the full block are derived in Transformers from Scratch: Self-Attention to Encoderโ€“Decoder.

Choosing, and the bugs to expect

SituationCandidate and what to check
Convolutional modelBatchNorm when channel statistics are representative; check evaluation with stored statistics.
Small training batchesGroupNorm avoids cross-example statistics; choose a group count dividing the channels.
TransformerLayerNorm or RMSNorm over token features; follow and validate the architectureโ€™s normalization placement.
Style-transfer modelInstanceNorm or adaptive variants when removing spatial channel statistics suits the objective.
Single-example inferenceAll of these can be used, including BatchNorm with valid stored statistics in evaluation mode.
  • If scores differ on the same data, compare the same checkpoint, preprocessing, and metric calculation. Inspect training/evaluation mode, dropout, and BatchNormโ€™s stored statistics before attributing the gap to overfitting.
  • If outputs depend on evaluation batch size, inspect whether BatchNorm uses batch statistics. This can be intentional when running statistics are disabled; the symptom alone does not prove that model.eval() is missing.
  • During fine-tuning, compare keeping pretrained running statistics with updating them on representative target data. Freezing them and freezing the learned scale and shift are separate decisions.
  • Many training recipes exclude normalization scale and shift from weight decay. Treat that as an optimizer choice to validate for the model.

Scaling this across several GPUs is covered in Distributed Training with PyTorch DDP.

References


Discover more from Insightful Data Lab

Subscribe to get the latest posts sent to your email.

Similar Posts

Questions, corrections, or additional insights?

This site uses Akismet to reduce spam. Learn how your comment data is processed.