DEV Community

Umesh Tharuka Malaviarachchi
Umesh Tharuka Malaviarachchi

Posted on

Layer Normalization: Why Normalising Across Features Beats Normalising Across the Batch

Layer Normalization: Why Normalising Across Features Beats Normalising Across the Batch

Batch normalization changed how deep networks train, but it has a blind spot. It normalises each feature across the batch, which means it needs a batch to work at all. Make the batch small, make the examples variable in length, or move to a recurrent network where the batch statistics shift at every time step, and the method starts to fight you. The fix is to turn the normalisation sideways: instead of normalising one feature across many examples, normalise all the features of one example. That is layer normalization, and it is the reason modern transformers train at all.

The idea is simple enough to state in one sentence, but its consequences run deep. A single example carries its own statistics, so the normalisation works with a batch of one, behaves identically at train and test time, and never needs running averages. That independence from the batch is not a minor convenience. It is what lets layer normalization work inside recurrent networks and transformers, where batch normalization never quite fit.

The definition

Take the activations of one layer for one example, a vector hh with HH hidden units. Layer normalization computes the mean and variance across those HH units, for that example alone:

μ=1H∑i=1Hhi \mu = \frac{1}{H} \sum_{i=1}^{H} h_i
σ2=1H∑i=1H(hi−μ)2 \sigma^2 = \frac{1}{H} \sum_{i=1}^{H} (h_i - \mu)^2

Then it normalises, and rescales with learned parameters γ\gamma and β\beta , exactly as batch normalization does after its own normalisation step:

h^i=hi−μσ2+ϵγi+βi \hat{h}_i = \frac{h_i - \mu}{\sqrt{\sigma^2 + \epsilon}} \gamma_i + \beta_i

The small constant ϵ\epsilon is there only to avoid division by zero. The learned γ\gamma and β\beta matter more than they first appear. Without them, every layer would be forced to output activations with zero mean and unit variance, which would cap what the network can represent. With them, the network can recover any mean and scale it wants, so the normalisation constrains the optimisation, not the function class. In practice γ\gamma is initialised to one and β\beta to zero, so training starts from the plain normalised activations and learns the rescaling from there.

Notice what is absent. There is no batch dimension in any of these formulas. Two examples in the same batch never interact through the normalisation, and the same example gets the same output whether it is processed alone or in a batch of a thousand. That determinism is the whole point, and it is the sharpest contrast with batch normalization, where the output for one example depends on whichever other examples happen to share its batch.

Why normalise across features at all

At first glance, normalising across features looks odd. The hidden units of a layer are not interchangeable measurements of the same quantity, the way the same feature measured across a batch is. They are different features, with different roles. Averaging them together seems to throw away information.

The reason it works is that the goal of normalisation is not to make the features comparable with each other. It is to control the scale of the activations that flow into the next layer, and to keep that scale stable as the weights change during training. The mean and variance across a layer are a summary of that scale for one example. Centring and rescaling by them keeps the input to the next layer in a sane range, regardless of how the weights below have drifted, and it does so using only information from the example itself.

There is a second, more geometric way to see it. Subtracting the mean and dividing by the standard deviation makes the normalised vector invariant to shifting and scaling the original activations. If every activation in the layer is multiplied by a constant, or shifted by a constant, the normalised output is unchanged. That invariance removes two directions of variation that the optimizer would otherwise have to chase: the network no longer needs to relearn its downstream weights every time the scale of a layer drifts. The same invariance argument applies to batch normalization, but there it is invariance across the batch. Here it is invariance per example, which is stronger in exactly the settings where the batch is unreliable.

Batch normalization versus layer normalization

The two methods differ in one choice, which axis to normalise over, and that choice decides where each one works.

Batch normalization normalises each feature across the batch. For a fixed feature, it gathers that feature's value across all examples, computes a mean and variance, and normalises. It needs a batch that is large enough for those statistics to be meaningful, and it needs the examples in the batch to be comparable. It also behaves differently at train and test time, because at test time there is no batch to gather statistics from, so it falls back on running averages collected during training.

Layer normalization normalises each example across its features. It needs no batch at all, it behaves identically at train and test time, and it needs no running averages. It works naturally with variable-length sequences, because each time step, or each token, is normalised on its own statistics. And it works in recurrent networks, where the same layer is applied at every time step and the batch statistics would otherwise change from step to step.

That is why the split in practice is so clean. Convolutional networks, where the batch is usually large and the features are spatial maps with shared statistics, still use batch normalization widely. Recurrent networks and transformers, where sequences vary in length and the batch is often small, use layer normalization almost exclusively. The choice is not a matter of taste. It follows from which axis has stable, meaningful statistics in that architecture.

There is one setting where the difference is easy to feel directly. Train a small model with a batch size of two, or one, and batch normalization becomes noisy or undefined, while layer normalization does not notice. The batch is a property of how you happen to train, not a property of the model, and a normalisation scheme that depends on it inherits all of its fragility.

Why transformers depend on it

The transformer is where layer normalization earns its keep. Every transformer block applies it twice, once before the attention sublayer and once before the feedforward sublayer in the modern pre-norm arrangement, or after each sublayer in the original post-norm arrangement. The reason is depth. A transformer stacks dozens of blocks, and without normalisation inside each block the activations would drift in scale as they pass through the stack, and the gradients would follow them.

The placement matters, and the field learned this the hard way. In the original post-norm design, the normalisation sits after the residual addition, so the residual stream itself is renormalised at every block. That works for shallow stacks, but as depth grows the gradients through the normalisation layers shrink, and training becomes unstable unless the learning rate and warmup are tuned carefully. In the pre-norm design, the normalisation sits inside the residual branch, before the attention or feedforward sublayer, and the residual stream itself is never renormalised. The identity path stays clean, gradients flow straight through it, and much deeper stacks train reliably with less tuning. Almost every large transformer trained today uses pre-norm, and the difference between the two is a live example of a small architectural choice with outsized consequences.

There is also a subtle interaction with attention. Attention scores are dot products between queries and keys, and dot products grow with the scale of their inputs. If the activations feeding into attention drift in scale, the softmax sharpens or flattens for reasons that have nothing to do with what the model has learned. Normalising before attention keeps the query and key scales controlled, so the attention pattern reflects content, not drift.

RMSNorm: a simpler cousin

A natural question is whether the mean subtraction is doing any real work, or whether the rescaling alone is enough. RMSNorm answers it by dropping the centring entirely. It normalises by the root mean square of the activations, with no mean subtraction and no bias term:

h^i=hi1H∑j=1Hhj2+ϵγi \hat{h}i = \frac{h_i}{\sqrt{\frac{1}{H} \sum{j=1}^{H} h_j^2 + \epsilon}} \gamma_i

In practice RMSNorm performs almost identically to layer normalization on transformer training, while costing slightly less compute and having one less parameter per unit. That result is informative. It suggests that most of the benefit comes from controlling scale, not from centring, and that the exact form of the normalisation matters less than the fact that some per-example scale control is present. Large models increasingly use RMSNorm for exactly that reason: same stability, simpler formula, faster step.

The lesson generalises. Normalisation schemes succeed when they remove a source of drift that the optimizer would otherwise have to fight, and the cheapest scheme that removes it is usually the right one. RMSNorm is layer normalization with the parts that were not pulling their weight removed.

A minimal example

The mechanics are easiest to see in code. Here is layer normalization written out by hand, next to the built-in version, on a small batch of sequences:

import torch
import torch.nn as nn

def layer_norm_manual(x, gamma, beta, eps=1e-5):
    mean = x.mean(dim=-1, keepdim=True)
    var = x.var(dim=-1, unbiased=False, keepdim=True)
    x_hat = (x - mean) / torch.sqrt(var + eps)
    return gamma * x_hat + beta

torch.manual_seed(0)
x = torch.randn(2, 4, 8) * 5 + 3
gamma = torch.ones(8)
beta = torch.zeros(8)

manual = layer_norm_manual(x, gamma, beta)
builtin = nn.LayerNorm(8)(x)
print("max difference:", (manual - builtin).abs().max().item())
print("input mean:", x.mean(dim=-1))
print("output mean:", manual.mean(dim=-1))
print("output std:", manual.std(dim=-1, unbiased=False))
Enter fullscreen mode Exit fullscreen mode

Run it and two things stand out. First, the manual version matches the built-in one exactly, which confirms that the formula above is the whole method. Second, the output has zero mean and unit standard deviation along the last dimension for every example, even though the input had mean 3 and standard deviation 5. The normalisation is doing exactly what it promises, per example, with no help from the batch.

The other detail worth noting is the dimension. Layer normalization is applied along the feature dimension, the last one here, and the learned γ\gamma and β\beta have one value per feature. That is the shape to remember whenever you wire it into a model: normalise over features, learn one scale and shift per feature.

Limitations and common pitfalls

Layer normalization is not a cure-all, and its failures are worth knowing before you reach for it by default.

First, it discards information about the magnitude of an example's activations. Two examples whose activations differ only by a constant scale produce the same normalised output, up to the learned rescaling. If the magnitude itself carries signal, for example if a larger activation means a more confident or more important representation, layer normalization erases it. Batch normalization has the same property, but there the scale is erased per feature across the batch, which is a different, and sometimes less costly, loss.

Second, it is less effective where the batch axis really does carry the meaningful statistics. In convolutional networks, the same feature detector is applied at every spatial location, so gathering that feature across the batch and across space gives a stable, meaningful estimate of its distribution. Normalising across the very different features of one location instead is a weaker summary, and in practice batch normalization still tends to win for vision models.

Third, the mean and variance are computed over the features of one example, so they are noisy when the layer is narrow. With only a handful of hidden units, the estimated statistics fluctuate, and the normalisation adds noise rather than removing drift. This is rarely a problem in transformers, where hidden sizes run into the hundreds or thousands, but it is a real consideration for small layers.

Fourth, pre-norm and post-norm are not interchangeable, as the transformer discussion above shows. Swapping one for the other without adjusting the learning rate schedule can turn a stable run into an unstable one, and the failure often looks like a generic optimisation problem rather than a normalisation problem. If a deep transformer is unstable, check the placement before blaming the optimizer.

Finally, there is the usual trap of applying normalisation where it is not needed. A shallow network, or a layer whose activations are already well scaled, gains little from an extra normalisation layer and pays for it in code complexity and a small amount of compute. Normalisation is a tool for controlling drift in deep stacks, not a ritual to perform on every layer.

The takeaway

Batch normalization normalises each feature across the batch, which ties it to batch size, to train-test differences, and to running averages. Layer normalization turns the operation sideways and normalises each example across its features, so it works with any batch size, behaves the same at train and test time, and needs no stored statistics. That independence is what makes it the right choice for recurrent networks and transformers, where the batch is small, the sequences vary in length, and the stack is deep. RMSNorm shows that the centring is optional and the scale control is the essential part. The cost is real: magnitude information is discarded, narrow layers get noisy statistics, and convolutional networks still prefer the batch axis. But for the architectures that dominate modern machine learning, normalising across features instead of across the batch is the decision that lets training scale.


Connect with me on LinkedIn: linkedin.com/in/umeshtharukaofficial

Top comments (0)