AI Logic

Normalization

Layer Normalization

Updated:

Difference between Layer Normalization and Batch Normalization in the range used to compute the mean and variance. Layer Normalization (left) uses all units of one sample (one row); Batch Normalization (right) uses one unit across the whole batch (one column). Below: the computation flow for one sample

What Is Layer Normalization?

Layer Normalization is a normalization method that rescales the values of all units in a layer within a single sample to mean 0 and variance 1. It was proposed by Ba, Kiros, and Hinton in 2016. Because it does not use other samples in the batch, it does not depend on batch size and performs exactly the same computation at training and inference time.

Today it is an essential component of every layer of the Transformer, and many language models such as BERT and GPT use it.

Let a1,…,aHa_1, \dots, a_H be the inputs to the HH units of a layer (the values before the activation function). The mean and standard deviation are computed as follows (Eq. (3) in the paper).

μ=1H∑i=1Hai,σ=1H∑i=1H(ai−μ)2\mu = \frac{1}{H} \sum_{i=1}^{H} a_i, \qquad \sigma = \sqrt{\frac{1}{H} \sum_{i=1}^{H} (a_i - \mu)^2}

Each unit's value is then normalized, and its scale and offset are adjusted with a learned gain gig_i and bias bib_i.

a^i=gi ai−μσ+bi\hat{a}_i = g_i \, \frac{a_i - \mu}{\sigma} + b_i

μ\mu and σ\sigma are computed per sample and shared by all units of the layer. In contrast, gig_i and bib_i take a separate value for each unit and are learned. Normalization alone narrows the range of representable values, so gig_i and bib_i allow the original scale to be restored if needed.

Difference from Batch Normalization: Which Axis Is Normalized

The difference between Layer Normalization and Batch Normalization lies in along which axis the mean and variance are computed. The figure at the top of the article arranges the samples in the batch vertically and the units (features) of the layer horizontally, with the range used to compute the mean and variance shown in blue.

  • Layer Normalization (left in the figure): The mean and variance are computed over the HH units of one sample. Each sample gets its own μ\mu and σ\sigma.
  • Batch Normalization (right in the figure): The mean and variance are computed for one unit over all samples in the batch. Each unit gets its own μ\mu and σ\sigma.

This difference leads to the following differences in properties.

AspectLayer NormalizationBatch Normalization
Range for mean/varianceAll units of the layer in one sampleAll samples in the batch for one unit
Batch sizeNo effect (works even with batch size 1)Small batches make the mean/variance noisy and degrade performance
Training vs. inferenceExactly the same computationInference uses the mean/variance collected during training
RNNs (models that process a sequence step by step)Can be applied at each time step as isNeeds separate mean/variance per time step; hard to use
Main usesTransformers, RNNsConvolutional networks (CNNs)

In the paper's preliminary experiments with convolutional networks, Layer Normalization trained faster than no normalization, but Batch Normalization gave better results. The authors suggest that units near the image boundary behave very differently from the others, so normalizing all units with the same mean and variance may not be appropriate.

Worked Example

Consider a small example. Let the inputs to H=4H = 4 units be a=(2,4,6,8)\boldsymbol{a} = (2, 4, 6, 8), with gain 1 and bias 0.

  1. Compute the mean: μ=(2+4+6+8)/4=5\mu = (2 + 4 + 6 + 8) / 4 = 5.
  2. Compute the standard deviation: σ=(9+1+1+9)/4=5≈2.236\sigma = \sqrt{(9 + 1 + 1 + 9)/4} = \sqrt{5} \approx 2.236.
  3. Subtract the mean from each value and divide by the standard deviation: (−1.342, −0.447, 0.447, 1.342)(-1.342,\ -0.447,\ 0.447,\ 1.342).

The result does not change if the whole input is multiplied by a constant or shifted by the same amount. For example, a=(20,40,60,80)\boldsymbol{a} = (20, 40, 60, 80) and (12,14,16,18)(12, 14, 16, 18) give the same normalized values. The paper calls this property "invariance to scaling of a single training case" and cites it as one reason training is stabilized.

The paper's equations do not include the small value ϵ\epsilon that prevents division by zero. Actual implementations compute σ=Var+ϵ\sigma = \sqrt{\mathrm{Var} + \epsilon} (PyTorch's nn.LayerNorm uses ϵ=10−5\epsilon = 10^{-5}). When all values are equal the variance becomes 0, so include ϵ\epsilon in custom implementations as well.

Use in RNNs and Transformers

In RNNs, Layer Normalization is applied to the computation of the hidden state at each time step (Eq. (4) in the paper).

ht=f ⁣[gσt⊙(at−μt)+b]\boldsymbol{h}^t = f\!\left[\frac{\boldsymbol{g}}{\sigma^t} \odot (\boldsymbol{a}^t - \mu^t) + \boldsymbol{b}\right]

Here, at\boldsymbol{a}^t is the input to the units at time tt, μt,σt\mu^t, \sigma^t are the mean and standard deviation at that time step, ⊙\odot is the element-wise product, and ff is the activation function. Because each time step is normalized using only its own values, it works even when the sequence length differs from training. The paper shows that it stabilizes the magnitude of RNN hidden states and speeds up training on tasks such as image–sentence retrieval, question answering, and learning sentence representations.

In Transformers, the input is a tensor of shape "batch × sequence length × dmodeld_{\text{model}}," and the mean and variance are computed over the dmodeld_{\text{model}} values of each word (token). The original Transformer adds the residual to each sublayer's output and then normalizes.

Output=LayerNorm(x+Sublayer(x))\text{Output} = \mathrm{LayerNorm}\bigl(x + \mathrm{Sublayer}(x)\bigr)

This arrangement is called Post-LN. Later it was found that Pre-LN, which normalizes before the sublayer, trains more stably as layers get deeper, and many models since GPT-2 use Pre-LN (Pre-LN vs. Post-LN). RMSNorm, which skips subtracting the mean and divides only by the root mean square, is a lighter variant used by models such as LLaMA.

PyTorch's nn.LayerNorm(normalized_shape) computes the mean and variance over the last axes of the tensor (those specified by normalized_shape). In a Transformer, nn.LayerNorm(d_model) normalizes over the dmodeld_{\text{model}} values of each word. Applied directly to an image tensor (batch × channels × height × width), it may normalize over unintended axes, so check the axis order.

PyTorch example

Show code
python
import torch
import torch.nn as nn

# Example from the text: inputs to H = 4 units
a = torch.tensor([[2.0, 4.0, 6.0, 8.0]])
mu = a.mean(dim=-1, keepdim=True)                         # 5.0
sigma = a.var(dim=-1, unbiased=False, keepdim=True).sqrt()  # √5 ≈ 2.236
print((a - mu) / sigma)  # about [-1.342, -0.447, 0.447, 1.342]

ln = nn.LayerNorm(4)     # gain g starts at 1, bias b at 0. eps = 1e-5
print(ln(a))             # almost the same values, slightly different due to ε


# Transformer sublayer (Post-LN): add the residual, then normalize per word
class PostLNFeedForward(nn.Module):
    def __init__(self, d_model: int = 512, d_ff: int = 2048, dropout: float = 0.1):
        super().__init__()
        self.ff = nn.Sequential(nn.Linear(d_model, d_ff), nn.ReLU(), nn.Linear(d_ff, d_model))
        self.norm = nn.LayerNorm(d_model)   # mean/variance over the last axis (d_model)
        self.dropout = nn.Dropout(dropout)

    def forward(self, x: torch.Tensor) -> torch.Tensor:
        # x: [batch, sequence length, d_model]
        return self.norm(x + self.dropout(self.ff(x)))


x = torch.randn(2, 10, 512)
y = PostLNFeedForward()(x)
print(y.shape)                       # torch.Size([2, 10, 512])
print(y.mean(-1)[0, :3])             # the mean of each word is almost 0 (because g = 1, b = 0)

FAQ

Q. Should I use Layer Normalization or Batch Normalization?
A.

For convolutional networks with sufficiently large batches, Batch Normalization is the standard choice. Use Layer Normalization for Transformers and RNNs, when batches must be small, or when training and inference should use the same computation. If unsure, follow what is widely used in the same type of model.

Q. Why are the gain g and bias b needed?
A.

Normalization alone forces every unit's values to mean 0 and variance 1, narrowing the range of representable values. The per-unit learned g and b allow the scale and offset to be readjusted.

Q. Is Layer Normalization not used in image models?
A.

It is. The Vision Transformer (ViT) turns an image into a sequence of small patches and processes it with a Transformer, so it uses Layer Normalization. Some convolutional networks, such as ConvNeXt, also apply Layer Normalization along the channel axis.

References

  1. J. L. Ba, J. R. Kiros, and G. E. Hinton, "Layer Normalization," arXiv:1607.06450, 2016.
  2. S. Ioffe and C. Szegedy, "Batch Normalization: Accelerating Deep Network Training by Reducing Internal Covariate Shift," ICML, 2015.
  3. A. Vaswani, N. Shazeer, N. Parmar, J. Uszkoreit, L. Jones, A. N. Gomez, Ł. Kaiser, and I. Polosukhin, "Attention Is All You Need," NIPS, 2017.
  4. R. Xiong, Y. Yang, D. He, K. Zheng, S. Zheng, C. Xing, H. Zhang, Y. Lan, L. Wang, and T.-Y. Liu, "On Layer Normalization in the Transformer Architecture," ICML, 2020.
  5. B. Zhang and R. Sennrich, "Root Mean Square Layer Normalization," NeurIPS, 2019.
  6. PyTorch Documentation, "torch.nn.LayerNorm."