Search

Search papers and lessons

Layer Normalization

Level 4 · 12 min read

Layer normalization rescales the features of one example to mean 0 and variance 1 across its own feature vector, so it does not depend on the other examples in the batch.

On this page

  • Colour = topic mix
  • Probability
  • Linear algebra
  • Neural network basics
  • Discrete math
  • Sign in to see your progress

TL;DR

Layer normalization takes the vector of activations that one layer produces for one example and rescales it so that its values have mean 0 and variance 1. It then applies a learned scale and shift to each feature. The statistics come from the features of that single example, so the result does not change with the other examples in the batch, and it works the same at batch size 1.

This makes it the default normalisation for sequence models and transformers, where sequences have different lengths and small batches are common.

Where you'll see it: before or after the attention and feedforward blocks of almost every Transformer, including the language models that write text today, and inside recurrent networks that process one token at a time.

Intuition

Normalise the example, not the column

Deep networks have a problem that normalisation was designed to fix. Each layer's output changes as the layers below it are trained, so the next layer keeps receiving inputs whose spread and centre drift. Batch normalization fixes this by looking across a mini-batch: for each feature, it averages over all the examples in the batch. That works well for images, but it has two awkward properties. The result for one example depends on which other examples happen to share its batch. And with a batch of one, or with sequences of different lengths where some positions are padding, the statistics are unreliable or undefined.

Layer normalization turns the statistics around. Instead of asking how feature 3 behaves across the batch, it asks how all the features of this one example behave together. Take the vector of, say, 512 numbers that a layer produced for one token. Compute the mean and variance of those 512 numbers, rescale them to a standard range, and pass the result on. Nothing about the other examples enters the calculation.

flowchart TB
  subgraph BN["Batch norm: average down a column"]
    B1[example 1] --> BC[feature j, all examples]
    B2[example 2] --> BC
    B3[example 3] --> BC
  end
  subgraph LN["Layer norm: average across a row"]
    L1[one example] --> LR[all features of this example]
  end

Why a per-example rule is useful

Think of a sentence as a stack of token vectors. Each token vector describes that token in context. What matters for the next layer is the relative pattern of its features, not the overall magnitude of the vector. Layer normalization removes the overall scale and offset of each token's vector, so every token enters the next layer on the same footing. A token that happened to produce large activations is not allowed to dominate the attention scores or the feedforward block just because of its size.

It is a cheap operation. It needs one mean and one variance per example per layer, and no running averages to keep track of during training and inference. The model behaves identically in both modes, which removes a common source of bugs.

The math

Setup

Let h∈Rd\mathbf{h} \in \mathbb{R}^{d} be the vector of dd activations that a layer produces for one example, with entries h1,…,hdh_1, \dots, h_d. (For a transformer token, h\mathbf{h} is the hidden vector of that token, and dd is the model width.) The layer has two learned vectors of length dd, a gain γ\boldsymbol{\gamma} and a bias β\boldsymbol{\beta}, and a small constant ϵ\epsilon (typically 10−510^{-5}) that keeps the division safe.

Definition: Layer normalization

Given h∈Rd\mathbf{h} \in \mathbb{R}^{d}, layer normalization computes

μ=1d∑j=1dhj,σ2=1d∑j=1d(hj−μ)2,\mu = \frac{1}{d}\sum_{j=1}^{d} h_j, \qquad \sigma^2 = \frac{1}{d}\sum_{j=1}^{d} (h_j - \mu)^2,

and the output

yj=γj hj−μσ2+ϵ+βj,j=1,…,d.y_j = \gamma_j \,\frac{h_j - \mu}{\sqrt{\sigma^2 + \epsilon}} + \beta_j, \qquad j = 1, \dots, d.

The mean μ\mu and variance σ2\sigma^2 are the usual sample mean and variance, but computed across the dd features of one vector. The output for feature jj has centre βj\beta_j and spread set by γj\gamma_j, not fixed at 0 and 1: the learned gain and bias let the layer choose how much normalisation to keep. If γj=1\gamma_j = 1 and βj=0\beta_j = 0, the normalised values have mean 0 and variance σ2/(σ2+ϵ)\sigma^2/(\sigma^2 + \epsilon), which is essentially 1 when ϵ\epsilon is small compared with the variance.

Two properties

The first property is that the output is unchanged if the whole vector is scaled and shifted:

LN(a h+b 1)=LN(h)for any a>0 and any b,\mathrm{LN}(a\,\mathbf{h} + b\,\mathbf{1}) = \mathrm{LN}(\mathbf{h}) \quad \text{for any } a \gt 0 \text{ and any } b,

where 1\mathbf{1} is the all-ones vector and ϵ\epsilon is taken as negligible. Scaling every entry by aa scales both hj−μh_j - \mu and σ\sigma by aa, so the ratio is unchanged. Adding bb to every entry shifts μ\mu by bb and leaves hj−μh_j - \mu alone. This is the sense in which layer normalization removes the overall scale and offset of each example. The second property is that the size of the output is set by the layer's parameters, not by its input: with γj=1\gamma_j = 1 and ϵ\epsilon negligible, the normalised values always have squared length dd, however large or small the input was.

Gradients

Because the mean and variance depend on every feature, the derivative of each output with respect to each input touches all of them. Differentiating through μ\mu and σ\sigma gives a projection-like term that removes the component of the gradient along the all-ones direction and along the current normalised vector. You do not need to write this out to use the layer, since automatic differentiation computes it, but it explains why layer normalization changes the geometry of training in a way that a plain per-feature scale does not.

Placement in a transformer

In a transformer block, layer normalization is applied around each sublayer, that is, the attention block and the feedforward block, each wrapped in a residual connection. There are two common arrangements. In the original 2017 design (post-norm), the sublayer output is added to its input and then normalised. In the pre-norm design, the input is normalised before the sublayer, and the sublayer output is added to the un-normalised residual stream. Pre-norm keeps a clean path for gradients through the residual stream, and it is much easier to train at great depth without careful learning-rate warmup. Most large recent models use a pre-norm arrangement.

Worked examples

Example
Normalising one token vector

Take a hidden vector with d=4d = 4 features, h=[1,2,3,6]\mathbf{h} = [1, 2, 3, 6]. Set γ=1\boldsymbol{\gamma} = \mathbf{1}, β=0\boldsymbol{\beta} = \mathbf{0}, and ignore ϵ\epsilon for now.

  1. Mean: μ=(1+2+3+6)/4=3\mu = (1 + 2 + 3 + 6)/4 = 3.
  2. Deviations from the mean: [−2,−1,0,3][-2, -1, 0, 3]. Squares: [4,1,0,9][4, 1, 0, 9], which sum to 14.
  3. Variance: σ2=14/4=3.5\sigma^2 = 14/4 = 3.5, so σ=3.5≈1.8708\sigma = \sqrt{3.5} \approx 1.8708.
  4. Normalised output: [−2,−1,0,3]/1.8708≈[−1.069,−0.535,0,1.604][-2, -1, 0, 3]/1.8708 \approx [-1.069, -0.535, 0, 1.604].
  5. Check: the outputs sum to about 0 and their squares sum to 1.143+0.286+0+2.571=4.01.143 + 0.286 + 0 + 2.571 = 4.0, which is dd, as expected for unit variance.
  6. Now set γ=2\gamma = 2 and β=0.5\beta = 0.5 for every feature. The output becomes [−1.638,−0.569,0.500,3.707][-1.638, -0.569, 0.500, 3.707]. The learned gain and bias have moved the centre and spread to whatever the next layer needs.
Example
Scale and shift do not matter

Compare h=[1,2,3,6]\mathbf{h} = [1, 2, 3, 6] with h′=10 h+5=[15,25,35,65]\mathbf{h}' = 10\,\mathbf{h} + 5 = [15, 25, 35, 65]. The second vector has a much larger scale and offset.

  1. For h′\mathbf{h}': mean μ′=35\mu' = 35, deviations [−20,−10,0,30][-20, -10, 0, 30], squares [400,100,0,900][400, 100, 0, 900], variance σ′2=1400/4=350\sigma'^2 = 1400/4 = 350, and σ′≈18.708\sigma' \approx 18.708.
  2. Normalised output: [−20,−10,0,30]/18.708≈[−1.069,−0.535,0,1.604][-20, -10, 0, 30]/18.708 \approx [-1.069, -0.535, 0, 1.604].
  3. That is exactly the output for h\mathbf{h}. The layer removed the scale factor 10 and the offset 5 completely.
  4. The consequence is that the next layer sees the same input whether the previous layer happened to amplify its activations or not. The learned gain γ\boldsymbol{\gamma} is then the only place the scale is set, which keeps training stable.
Example
Why batch size one breaks batch normalization

Suppose the batch has a single example, with feature value hj=6h_j = 6 for feature jj.

  1. Batch norm computes the mean and variance of feature jj over the batch. The batch has one value, so the mean is 66 and the variance is 00.
  2. The normalised value is (6−6)/0+ϵ=0(6 - 6)/\sqrt{0 + \epsilon} = 0. Every feature becomes 0, whatever the input was, so the layer carries no information about this example.
  3. Layer normalization on the same single vector [1,2,3,6][1, 2, 3, 6] still gives [−1.069,−0.535,0,1.604][-1.069, -0.535, 0, 1.604], as in the first example. The row has four values, so its variance is well defined.
  4. This is why layer normalization is standard in sequence models, where a batch can be small or contain only one long sequence during generation.
0.511.522.533.5400.511.522.53variance σ²multiplier 1 / √(σ² + ε)
  • damping factor with ε = 0.25 (exaggerated)
  • damping factor with ε = 0
The division by the standard deviation is damped by ε. The real ε is 10⁻⁵, far smaller than shown here, but the effect is the same: a near-zero variance cannot blow up the output.

Tradeoffs and failure modes

Layer normalization is robust, but it is not free, and its choices interact with the rest of the architecture.

SituationProblemBetter choice
Images with large batchesLayer norm throws away the per-channel statistics that batch norm uses wellBatch norm, or group norm when batches are small
Very deep transformers trained with post-normGradients can vanish or explode near the output without careful warmupPre-norm placement, or a scaled initialisation
Feature vectors with a few huge outliersOne large feature inflates the variance and squashes the restClipping, or an RMS-based variant that skips the mean
Recurrent networks processing one step at a timeBatch statistics are unavailable, and running averages drift across stepsLayer norm applied to each step's hidden state
Inference on a single exampleBatch norm needs stored running statistics that must match trainingLayer norm, which is identical in training and inference

Some practical warnings:

  • Layer norm erases information about the overall scale. That is usually what you want, but it means the layer cannot use the size of an activation as a signal. If the magnitude matters for the task, a gain or an extra feature must carry it.
  • Placement matters more than people expect. Moving the norm from before a sublayer to after it can change whether a deep model trains at all. Check the arrangement when you adapt an architecture.
  • Epsilon is not a free knob. Very small values can produce large outputs on near-constant inputs, and very large values slightly distort the normalisation. The default works in practice, and changing it is rarely the fix for a training problem.
  • Keep the gain and bias. Dropping γ\boldsymbol{\gamma} and β\boldsymbol{\beta} forces every layer to output zero mean and unit variance exactly, which removes the capacity the layer needs.

History

Batch normalization appeared first. Sergey Ioffe and Christian Szegedy proposed it in 2015 to reduce what they called internal covariate shift, and it quickly became standard for convolutional image models. Its dependence on batch statistics was the obvious weak point for recurrent networks and for sequence models, where a single long sequence or a batch of one is common.

Jimmy Lei Ba, Jamie Ryan Kiros and Geoffrey Hinton proposed layer normalization in 2016 as a fix for that. Their paper showed gains on recurrent networks, where the per-example statistics made it straightforward to apply at every time step. It was not an immediate hit in the broader community, in part because batch norm was already working well on the image benchmarks of the time.

The transformer changed that. Vaswani and colleagues used layer normalization around every sublayer in the 2017 "Attention Is All You Need" architecture, and the transformer's spread through language, vision and speech made layer normalization a default component. Later work moved the normalisation to the pre-norm position and experimented with simpler variants, such as ones that normalise by root mean square without subtracting the mean. Those variants keep the same role: they fix the scale of each token's vector so that the layers that follow can learn.

Check yourself

QuestionA hidden vector is [2,4,6,8][2, 4, 6, 8]. With γ=1\gamma = 1, β=0\beta = 0 and ϵ\epsilon negligible, what does layer normalization output?Show answer

The mean is 5, and the deviations are [−3,−1,1,3][-3, -1, 1, 3]. The variance is (9+1+1+9)/4=5(9 + 1 + 1 + 9)/4 = 5, so σ=5≈2.236\sigma = \sqrt{5} \approx 2.236. The output is [−1.342,−0.447,0.447,1.342][-1.342, -0.447, 0.447, 1.342]. The vector is evenly spaced, so the output is symmetric about 0. Its squared values sum to 4, which is dd, as in the worked example.

QuestionWhy does layer normalization give the same result for an input and for that input multiplied by 3 plus 7, while batch normalization in general does not?Show answer

Layer normalization's statistics are computed from the entries of the vector itself. Multiplying by 3 scales its deviations and its standard deviation by 3, so the ratio is unchanged. Adding 7 moves the mean and leaves the deviations alone. Batch normalization computes its statistics for each feature across the batch, so a transformation that changes only one example's values changes the batch mean and variance and therefore the output for every example in the batch.

QuestionYou train a transformer with post-norm and find that the loss diverges unless you use a long warmup. What is a likely cause, and what change would you test?Show answer

In post-norm, the normalisation sits on the residual path, so gradients must pass through every normalisation layer on the way back, and their size can grow or shrink with depth. A plausible cause is this gradient imbalance at large depth. Test the pre-norm arrangement, which keeps an un-normalised residual path from output to input, and compare the loss curves with the same warmup.

QuestionA model processes one token at a time during generation, and its batch size is 1. Why would batch normalization be a poor choice here, and what does layer normalization offer instead?Show answer

Batch normalization would need statistics from other examples in the batch, which do not exist with a batch of one. The variance would be zero, and the output would collapse. It could use stored running statistics from training, but those may not match the distribution seen at generation time. Layer normalization uses the features of the current token only, so it behaves identically in training and inference, and it does not depend on batch size.

Sources