VerifiedarXiv:1607.0645031 min
Training · Normalization

Layer Normalization

Normalize each example across its own features, not across the batch.

Batch normalization standardizes each neuron's input with a mean and variance taken over the mini-batch. Layer normalization takes the mean and variance over all the neurons of one layer, for one example at a time, so it works at batch size 1, computes the same thing at training and test time, and applies unchanged at every step of a recurrent network.

Explaining the paperLayer NormalizationBa, Kiros, Hinton · University of Toronto · 2016 · arXiv:1607.06450 ↗

Jimmy Ba, Jamie Kiros and Geoffrey Hinton posted it in July 2016 as a fix for recurrent networks. Eleven months later the Transformer put a layer norm after every sub-layer.

A layer norm takes a vector, subtracts its mean, divides by its standard deviation, and then multiplies by a learned gain and adds a learned bias, one of each per element. PyTorch ships it as nn.LayerNorm. BERT, GPT-2 and GPT-3 use it, and LLaMA and Mistral use a simplified version called RMSNorm. The 2016 paper that introduced it defines the operation in one equation, derives a table of transformations the operation ignores, analyses how normalization changes the effective learning rate, and tests it on six tasks, most of them recurrent networks.

The method is a response to batch normalization, which a year earlier had made deep feedforward networks train much faster. Batch norm computes its statistics over the training cases in a mini-batch. Layer norm computes the same statistics over the units of a layer instead, which the paper calls a transpose of batch norm. The page follows that change through: what batch norm needs and where it breaks, the layer-norm formula with a worked example, the paper's invariance table (which you can test in a figure), what normalization does to the learning rate, why recurrent networks gain the most, the experiments, and what Transformers and RMSNorm later changed.

What batch normalization needs

Start with an ordinary layer. Neuron ii takes the previous layer's output h\mathbf{h}, forms a summed input (its pre-activation), and applies a nonlinearity ff such as tanh or ReLU:

ai=wi⊤h,hi′=f(ai+bi)a_i = \mathbf{w}_i^\top \mathbf{h}, \qquad h_i' = f(a_i + b_i)
(1)

Both normalization methods in this paper operate on the summed inputs aia_i, before ff. Batch normalization rescales each one using that neuron's own mean and standard deviation over the data:

aˉi=giσi (ai−μi),μi=Ex ⁣[ai],σi=Ex ⁣[(ai−μi)2]\bar a_i = \frac{g_i}{\sigma_i}\,(a_i - \mu_i), \qquad \mu_i = \mathbb{E}_{\mathbf{x}}\!\left[a_i\right], \qquad \sigma_i = \sqrt{\mathbb{E}_{\mathbf{x}}\!\left[(a_i - \mu_i)^2\right]}aˉi=giσi (ai−μi),μi=Ex ⁣[ai],σi=Ex ⁣[(ai−μi)2]\begin{gathered} \bar a_i = \frac{g_i}{\sigma_i}\,(a_i - \mu_i), \\ \mu_i = \mathbb{E}_{\mathbf{x}}\!\left[a_i\right], \qquad \sigma_i = \sqrt{\mathbb{E}_{\mathbf{x}}\!\left[(a_i - \mu_i)^2\right]} \end{gathered}
(2)

The expectations are over the whole training distribution, which no training step can afford to compute, so in practice μi\mu_i and σi\sigma_i are estimated from the current mini-batch, and gig_i is a learned gain. Each neuron gets one mean and one standard deviation per step, computed from the NN cases in the batch.

With a small batch the estimate is poor. Take a batch of two cases in which neuron ii receives 0.30.3 and 1.11.1. The batch mean is 0.70.7, both cases sit 0.40.4 from it, so the (biased) standard deviation is 0.40.4 and the normalized values are exactly −1-1 and +1+1. Any two different values give −1-1 and +1+1, so at N=2N=2 the layer passes on only which of the two cases was larger. At N=1N=1 the variance is zero and the formula divides zero by zero.

The paper names three settings where this dependence on the batch causes problems:

How layer normalization works

Lay out a layer's summed inputs for one mini-batch as a grid with one row per neuron (HH rows) and one column per training case (NN columns). Batch normalization standardizes each row: one neuron, its values across the batch. Layer normalization standardizes each column: one case, its values across all HH neurons of the layer. The statistics become

μ=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}μ=1H∑i=1Hai,σ=1H∑i=1H(ai−μ)2\begin{gathered} \mu = \frac{1}{H}\sum_{i=1}^{H} a_i, \\ \sigma = \sqrt{\frac{1}{H}\sum_{i=1}^{H} (a_i - \mu)^2} \end{gathered}
(3)

Every neuron in the layer shares this one μ\mu and σ\sigma, and every case gets its own pair. No other example enters the computation, which settles all three problems at once. A batch of one is enough. Training and test run the same arithmetic, because there are no batch statistics to estimate during training and freeze for later. And an RNN can apply the same normalization at step 3, step 30 or step 3,000, because each step's statistics come from that step's own summed inputs.

Batch norm is like grading each exam question on a curve against the whole class: one adjustment per question, pooled over students. Layer norm curves each student against the spread of that student's own scores: one adjustment per student, pooled over questions. The analogy holds for the axis and stops there; it says nothing about why either choice helps training. In code the two differ only in the axis of the reduction:

# A: summed inputs for a mini-batch, shape [N cases, H units]
# batch norm: one mean/std per UNIT, taken down the batch     (axis 0)
bn = (A - A.mean(0)) / A.std(0)                    # needs N >= 2
# layer norm: one mean/std per CASE, taken across its units   (axis 1)
ln = (A - A.mean(1, keepdims=True)) / A.std(1, keepdims=True)  # any N

Figure 1 draws the grid. Switch between the two modes and drag the batch size down to 1. The outlined group in layer-norm mode is a column of H=6H = 6 values whatever NN is. In batch-norm mode the group is a row of NN values, and at N=1N = 1 it holds a single number with zero variance.

Figure 1 · which axis is normalized
6
Summed inputs as a grid: rows are features, columns are batch cases. In layer-norm mode a single case (a column) is normalized across its features, independent of the batch. In batch-norm mode a single feature (a row) is normalized across the batch, and at N=1 it collapses. Click to pick the highlighted group.

Gain, bias and a worked example

Standardizing forces every layer's summed inputs to mean 0 and variance 1. A layer whose next nonlinearity works best with inputs centered at 2, or spread over a range of 5, would lose that. So, as in batch norm, each unit gets a learned gain gig_i and bias bib_i, applied after standardizing and before the nonlinearity. The paper writes the whole thing in vector form for a recurrent layer, whose summed inputs at step tt combine the previous hidden state and the current input:

at=Whhht−1+Wxhxt\mathbf{a}^t = W_{hh}\mathbf{h}^{t-1} + W_{xh}\mathbf{x}^t
ht=f ⁣[gσt⊙(at−μt)+b]\mathbf{h}^t = f\!\left[\frac{\mathbf{g}}{\sigma^t} \odot \left(\mathbf{a}^t - \mu^t\right) + \mathbf{b}\right]
(4)

The ⊙\odot is elementwise multiplication and μt,σt\mu^t, \sigma^t are Eq. (3) applied to at\mathbf{a}^t. The gain and bias put back the two degrees of freedom that standardizing removed, per unit, so the layer can still represent any scale and offset it needs. They are initialized to g=1\mathbf{g} = 1 and b=0\mathbf{b} = 0, so a freshly initialized layer norm is a pure standardizer. (The appendix states this initialization with the names of the two parameters swapped, in a way that would erase the input. Section 6 and every implementation use gain 1, bias 0; the Provenance panel below has the details.)

The paper also writes all three methods it compares in one template:

hi=f ⁣(giσi (ai−μi)+bi)h_i = f\!\left(\frac{g_i}{\sigma_i}\,(a_i - \mu_i) + b_i\right)
(5)

The methods differ only in where μi\mu_i and σi\sigma_i come from: batch norm takes them per unit over the batch, layer norm per case over the units, and weight normalization (Salimans and Kingma, 2016) sets μi=0\mu_i = 0 and σi=∥wi∥2\sigma_i = \lVert \mathbf{w}_i \rVert_2, the length of the neuron's incoming weight vector, which involves no data.

A concrete pass, with H=4H = 4. One case's summed inputs are a=[ 2.0, −1.0, 0.5, 1.5 ]\mathbf{a} = [\,2.0,\ -1.0,\ 0.5,\ 1.5\,]. The mean is μ=3/4=0.75\mu = 3/4 = 0.75. The deviations are [ 1.25, −1.75, −0.25, 0.75 ][\,1.25,\ -1.75,\ -0.25,\ 0.75\,], their squares average to 5.25/4=1.31255.25/4 = 1.3125, and σ=1.3125≈1.146\sigma = \sqrt{1.3125} \approx 1.146. Dividing gives

a^=a−μσ≈[ 1.09, −1.53, −0.22, 0.65 ]\hat{\mathbf{a}} = \frac{\mathbf{a} - \mu}{\sigma} \approx [\,1.09,\ -1.53,\ -0.22,\ 0.65\,]

which has mean 0 and variance 1. At the initial g=1,b=0g = 1, b = 0 this vector goes straight into ff. If training later sets the first unit's gain to 2 and its bias to 0.5, that unit outputs f(2×1.09+0.5)=f(2.68)f(2 \times 1.09 + 0.5) = f(2.68). The forward pass for one case:

# layer norm on one case's summed inputs a, shape [H]
mu    = a.mean()                    # average over the H units
var   = ((a - mu) ** 2).mean()      # biased: divide by H, not H - 1
a_hat = (a - mu) / sqrt(var + eps)  # mean 0, variance 1 (eps: code only)
h     = f(g * a_hat + b)            # per-unit gain g and bias b, then f
# parameters: g, b (H each), init g = 1, b = 0. mu and var are not
# parameters; autograd differentiates through them like any other op.

The variance in the listing divides by HH, the biased estimator, as Eq. (3) does. The listing also has an ϵ\epsilon inside the square root that the paper's equations do not; every implementation adds a small one so that a case whose HH inputs are all equal does not divide by zero. PyTorch's module does the same thing on the last dimension of a tensor and stores the gain and bias as weight and bias:

import torch, torch.nn as nn
ln = nn.LayerNorm(512)            # weight = ones(512), bias = zeros(512)
x  = torch.randn(1, 512)          # a batch of ONE case is fine
y  = ln(x)                        # stats over the last dim: 512 values
print(y.mean().item(), y.std(unbiased=False).item())   # ~0.0, ~1.0
print(sum(p.numel() for p in ln.parameters()))         # 1024 = 2 * 512

Figure 2 runs the standardize-then-restore steps on one 8-unit case. At the default gain and bias the bottom row matches the middle row. Moving the gain changes the output's spread and moving the bias shifts its center, while the standardized middle row stays fixed, because it depends only on a\mathbf{a}.

Figure 2 · standardize, then restore
One case's summed inputs a are standardized to â (mean 0, spread 1), then a learned gain and bias set a new spread and center: h = g·â + b. At g=1, b=0 the output equals the standardized row, so layer norm starts as a pure standardizer.

What layer norm is invariant to

Section 5.1 of the paper asks, for each method, which changes to the weights or the data leave the normalized output exactly the same. If a change has no effect on the output, the loss is flat along it, and training cannot be disrupted by drift in that direction. Table 1 of the paper:

Invariant toWeight matrix re-scaleWeight matrix re-centerWeight vector re-scaleDataset re-scaleDataset re-centerSingle case re-scale
Batch normyesnoyesyesyesno
Weight normyesnoyesnonono
Layer normyesyesnoyesnoyes

“Weight matrix” means all of the layer's incoming weights WW at once, “weight vector” means one row wi\mathbf{w}_i (the incoming weights of a single neuron), “dataset” means every training case, and “single case” means one training case alone. Figure 3 computes every cell of the table. A toy layer maps 4 training cases through a 5×45 \times 4 weight matrix, and the same summed inputs are normalized three ways. Pick a transformation and a strength, and each row reports how far its 20 outputs moved. At the default, scaling case 1 by δ=1.93\delta = 1.93 moves the batch-norm outputs by up to 0.40 and the weight-norm outputs by up to 1.18, and leaves the layer-norm outputs unchanged.

Figure 3 · test the invariance table
δ=1.93
A layer of 5 units on a batch of 4 cases. Outlines are each method's outputs before the transformation, filled bars after it; a row turns teal when all 20 outputs are unchanged and amber when any moved. Pick one of the paper's six transformations and drag its strength; at strength 0 nothing changes. Every nonzero setting reproduces Table 1.

Two columns are layer norm's alone. The first is re-scaling a single case. Multiply one input x\mathbf{x} by δ>0\delta > 0 and every summed input of that case, ai=wi⊤xa_i = \mathbf{w}_i^\top \mathbf{x}, is multiplied by δ\delta. The mean of those summed inputs is multiplied by δ\delta, so is their standard deviation, and the factor cancels in the ratio:

hi′=f ⁣(giδσ (δai−δμ)+bi)=hih_i' = f\!\left(\frac{g_i}{\delta\sigma}\,(\delta a_i - \delta\mu) + b_i\right) = h_i
(7)

With the worked example, tripling the input gives a=[ 6, −3, 1.5, 4.5 ]\mathbf{a} = [\,6,\ -3,\ 1.5,\ 4.5\,], μ=2.25\mu = 2.25 and σ≈3.437\sigma \approx 3.437, and the same a^\hat{\mathbf{a}} as before. Batch norm has no such property: its statistics pool the whole batch, so scaling one case changes the mean and variance that every case in the batch is normalized with. Layer norm behaves like a camera that sets the exposure separately for each photo: a dim shot and a bright copy of the same scene come out the same. (The analogy breaks for a negative δ\delta, which flips the sign of every a^i\hat a_i.) Figure 4 shows the cancellation on one case.

Figure 4 · one case, scaled by δ
×1.00
Scaling one case by δ scales all of its summed inputs by δ. The top row tracks that raw scaling off the panel and back; the layer-norm output is identical for every δ, because the factor cancels in (a − μ)/σ. An un-normalized layer would pass δ straight through.

The second is re-centering the weight matrix: add the same vector γ\boldsymbol{\gamma} to every row of WW, and optionally scale the matrix by δ\delta, so W′=δW+1γ⊤W' = \delta W + \mathbf{1}\boldsymbol{\gamma}^\top. For a case x\mathbf{x}, the added term contributes the same scalar γ⊤x\boldsymbol{\gamma}^\top\mathbf{x} to every unit's summed input. That raises the layer mean by exactly γ⊤x\boldsymbol{\gamma}^\top\mathbf{x}, the subtraction removes it, the deviations from the mean do not change, and δ\delta cancels against σ\sigma as before:

W′=δW+1γ⊤⟹h′=hW' = \delta W + \mathbf{1}\boldsymbol{\gamma}^\top \quad\Longrightarrow\quad \mathbf{h}' = \mathbf{h}
(6)

Batch norm fails this one because γ⊤x\boldsymbol{\gamma}^\top\mathbf{x} differs from case to case, so it changes the spread of each unit across the batch (at the default strength in Figure 3, by up to 1.64).

The table also has a “no” where batch norm and weight norm have “yes”: layer norm is invariant to scaling the whole matrix, but not one weight vector. Doubling only w1\mathbf{w}_1 doubles only a1a_1, which changes the μ\mu and σ\sigma that all HH units share, so every output of the layer moves (by up to 0.54 in Figure 3 at δ=1.93\delta = 1.93). Batch norm and weight norm compute each unit's statistics from that unit alone, so scaling its weights cancels. Likewise, shifting every input by a constant vector c\mathbf{c} adds wi⊤c\mathbf{w}_i^\top\mathbf{c} to unit ii, a different amount for each unit, which layer norm's single mean cannot remove; batch norm removes it because the shift is the same for every case. (Section 5.1's prose says all three methods are invariant to re-scaling the dataset, which contradicts the paper's own table for weight norm. The table is right, and Figure 3 shows weight norm's outputs scaling with the data.)

Why the weight norm acts as a learning rate

Invariance is a statement about outputs. Section 5.2 asks what normalization does to learning, when two settings of the weights compute the same function but sit at different points of parameter space. It borrows a measure of step size from Amari's natural-gradient work (1998): instead of the Euclidean length of a parameter change δ\delta, measure how much it changes the model's predictions, using the KL divergence (a standard measure of how different two probability distributions are). To second order that is a quadratic form in the Fisher information matrix FF:

ds2=KL ⁣[P(y∣x;θ) ∥ P(y∣x;θ+δ)]≈12 δ⊤F(θ) δds^2 = \mathrm{KL}\!\left[P(y\mid\mathbf{x};\theta)\,\big\|\,P(y\mid\mathbf{x};\theta+\delta)\right] \approx \tfrac{1}{2}\,\delta^\top F(\theta)\,\deltads2=KL ⁣[P(y∣x;θ) ∥ P(y∣x;θ+δ)]≈12 δ⊤F(θ) δ\begin{aligned} ds^2 &= \mathrm{KL}\!\left[P(y\mid\mathbf{x};\theta)\,\big\|\,P(y\mid\mathbf{x};\theta+\delta)\right] \\ &\approx \tfrac{1}{2}\,\delta^\top F(\theta)\,\delta \end{aligned}
(8)

FF is the curvature of that KL distance in parameter coordinates: a large entry means a small step in that direction changes the predictions a lot. (The same matrix bounds the policy step in TRPO.) The paper computes FF for a normalized generalized linear model, meaning one linear layer, an elementwise nonlinearity, and an exponential-family output distribution. It extends the result to deep networks only through a block-diagonal approximation with one block per neuron. Two conclusions follow.

The first is an implicit learning-rate decay. The Fisher block along wi\mathbf{w}_i is multiplied by the gain and divided by the normalization scalar σi\sigma_i, so it shrinks as σi\sigma_i grows. If the norm of wi\mathbf{w}_i doubles, the output stays the same, but σi\sigma_i doubles, and the paper states that the curvature along wi\mathbf{w}_i changes by a factor of 12\tfrac{1}{2}. The same gradient step then changes the function less, so a weight vector with a large norm is harder to rotate, which the paper calls an implicit “early stopping” effect. Read the factor of one half as an illustration. It assumes σi\sigma_i grows in exact proportion to ∥wi∥\lVert\mathbf{w}_i\rVert with the rest of the layer fixed. That holds for weight norm, where σi\sigma_i is the norm, and for batch norm, where σi\sigma_i belongs to unit ii alone. It holds only partly for layer norm, whose σ\sigma pools all HH units.

For layer norm an exact version follows from the first column of Table 1. The output does not change when the whole matrix is multiplied by δ>0\delta > 0, so any loss computed from it satisfies L(δW)=L(W)L(\delta W) = L(W). Differentiating that identity gives two facts. Differentiating with respect to WW gives ∇L(δW)=∇L(W)/δ\nabla L(\delta W) = \nabla L(W)/\delta: the gradient shrinks in proportion to the norm. Differentiating with respect to δ\delta at δ=1\delta = 1 gives ⟨∇L(W),W⟩=0\langle \nabla L(W), W \rangle = 0: the gradient is perpendicular to WW. A plain gradient step W′=W−η∇LW' = W - \eta\nabla L is therefore perpendicular to WW, and by Pythagoras

∥W′∥2=∥W∥2+η2∥∇L∥2  ≥  ∥W∥2\lVert W' \rVert^2 = \lVert W \rVert^2 + \eta^2 \lVert \nabla L \rVert^2 \;\ge\; \lVert W \rVert^2

so the norm grows at every step. The angle a step turns WW is about η∥∇L∥/∥W∥\eta \lVert\nabla L\rVert / \lVert W\rVert, and with the gradient itself scaling as 1/∥W∥1/\lVert W\rVert, the direction effectively learns at rate η/∥W∥2\eta / \lVert W \rVert^2, which falls as the norm grows. Salimans and Kingma derive the same norm growth for weight normalization (Section 2.1 of their paper) and observe that a learning rate that is too large inflates the norm until the effective rate is reasonable. They also say the argument is exact only for plain gradient descent; momentum and Adam (every layer-norm experiment that names an optimizer used Adam) follow it only qualitatively.

Figure 5 runs this on the smallest example that has it: a 2-D weight vector and a loss that depends only on the vector's angle to a target direction, so it is invariant to scaling just like layer norm's loss is to scaling WW. The learning rate is fixed at 0.3 and every run starts 140° from the target. Watch the norm readout and the angle turned per step as you change the starting norm.

Figure 5 · gradient steps on a scale-invariant loss
15
1.00
The loss depends only on the angle between w and the target direction, so every gradient step is perpendicular to w and lengthens it. Play or scrub the 60 plain gradient steps; drag the starting norm. The readout's effective rate lr/‖w‖² falls as the norm grows.

Starting at norm 1, the vector is 9.4° from the target after 15 steps, with its norm grown to 1.24. Starting at norm 3, it is still 42.6° away after all 60 steps, because its effective rate is about nine times smaller. Starting at norm 0.1, the first step is so large relative to the vector that it turns it 87° and inflates the norm to 1.93 in one step, after which the run is slower than one started at norm 0.25 (18° away at step 15, against 0.2°).

The second conclusion concerns the gain. Under the original parameterization, the paper shows, the metric along the magnitude of a neuron's incoming weights scales with the norm of the input; for the normalized model, learning the gain gig_i depends only on the magnitude of the prediction error. So learning a neuron's output scale is more robust to the scale of its input. This result is derived inside the generalized-linear-model setting and is not an exact statement about a deep stack of nonlinear layers.

Layer norm in RNNs and LSTMs

A recurrent network applies the same recurrent matrix to its hidden state at every step. If that tends to multiply the size of the summed inputs by a factor ρ\rho slightly above 1, the size grows like ρt\rho^t: at ρ=1.15\rho = 1.15, a factor of 268 after 40 steps. Slightly below 1, it decays toward zero or, when each step adds fresh input, toward the level that input sustains. The paper links this drift in the summed inputs to exploding and vanishing gradients. That link is heuristic. Gradient explosion is governed by the products of the recurrent Jacobians (for a linear RNN, the singular values of WhhW_{hh}), and normalizing the forward pass controls the forward scale directly and the gradients only indirectly.

Eq. (4) re-standardizes the summed inputs at every step, so the input to the nonlinearity has the same size whatever size the previous step produced: with gain 1 and bias 0 its root-mean-square is exactly 1. In the paper's words, the network becomes invariant to re-scaling all of the summed inputs to a layer, which gives “much more stable hidden-to-hidden dynamics”. One gain vector and one bias vector are shared by all time-steps, and the statistics at step tt depend only on at\mathbf{a}^t, so nothing is stored per step and a test sequence of any length is handled the same way. Recurrent batch normalization (Cooijmans et al., 2016) keeps separate statistics per step instead.

Figure 6 simulates a 24-unit linear recurrent layer:

at=ρ Q ht−1+s ut\mathbf{a}^t = \rho\,Q\,\mathbf{h}^{t-1} + s\,\mathbf{u}^t

The matrix QQ is a fixed random rotation (so ρ\rho is exactly the per-step factor) and ut\mathbf{u}^t is a fixed random input of RMS 1 scaled by the input drive ss. Drag ρ\rho across 1 and the input drive to 0. Without layer norm the state's RMS climbs off the top or sinks toward s/1−ρ2s/\sqrt{1-\rho^2}, and to the floor when s=0s = 0. With layer norm the state sits at 1. The dashed line shows the summed input arriving at the normalization each step, which stays near ρ2+s2\sqrt{\rho^2 + s^2} (one step's growth of a unit-size state plus one step's input) instead of compounding.

Figure 6 · hidden-state size over 40 steps
1.15
0.20
RMS of the hidden state, log scale. Without layer norm it grows or decays geometrically with the per-step factor ρ. With layer norm it is exactly 1 at every step; the dashed line is the summed input the normalization receives on that run. Both runs use the same rotation and inputs.

For LSTMs, which most of the experiments use, the appendix normalizes the recurrent and input projections separately, each with its own gain α\boldsymbol{\alpha} and bias β\boldsymbol{\beta}, and adds a third layer norm on the cell state before the output tanh:

(ftitotgt)=LN(Whht−1;α1,β1)+LN(Wxxt;α2,β2)+b\begin{pmatrix}\mathbf{f}_t\\ \mathbf{i}_t\\ \mathbf{o}_t\\ \mathbf{g}_t\end{pmatrix} = \mathrm{LN}(W_h\mathbf{h}_{t-1};\boldsymbol{\alpha}_1,\boldsymbol{\beta}_1) + \mathrm{LN}(W_x\mathbf{x}_t;\boldsymbol{\alpha}_2,\boldsymbol{\beta}_2) + \mathbf{b}(ftitotgt)=LN(Whht−1;α1,β1)+LN(Wxxt;α2,β2)+b\begin{aligned} \begin{pmatrix}\mathbf{f}_t\\ \mathbf{i}_t\\ \mathbf{o}_t\\ \mathbf{g}_t\end{pmatrix} &= \mathrm{LN}(W_h\mathbf{h}_{t-1};\boldsymbol{\alpha}_1,\boldsymbol{\beta}_1) \\ &+ \mathrm{LN}(W_x\mathbf{x}_t;\boldsymbol{\alpha}_2,\boldsymbol{\beta}_2) + \mathbf{b} \end{aligned}
(20)
ct=σ(ft)⊙ct−1+σ(it)⊙tanh⁡(gt),ht=σ(ot)⊙tanh⁡ ⁣(LN(ct;α3,β3))\mathbf{c}_t = \sigma(\mathbf{f}_t)\odot\mathbf{c}_{t-1} + \sigma(\mathbf{i}_t)\odot\tanh(\mathbf{g}_t), \qquad \mathbf{h}_t = \sigma(\mathbf{o}_t)\odot\tanh\!\big(\mathrm{LN}(\mathbf{c}_t;\boldsymbol{\alpha}_3,\boldsymbol{\beta}_3)\big)ct=σ(ft)⊙ct−1+σ(it)⊙tanh⁡(gt),ht=σ(ot)⊙tanh⁡ ⁣(LN(ct;α3,β3))\begin{gathered} \mathbf{c}_t = \sigma(\mathbf{f}_t)\odot\mathbf{c}_{t-1} + \sigma(\mathbf{i}_t)\odot\tanh(\mathbf{g}_t), \\ \mathbf{h}_t = \sigma(\mathbf{o}_t)\odot\tanh\!\big(\mathrm{LN}(\mathbf{c}_t;\boldsymbol{\alpha}_3,\boldsymbol{\beta}_3)\big) \end{gathered}
(21–22)

In Eqs. (20)–(22), σ\sigma is the logistic sigmoid, not a standard deviation. Normalizing the two projections separately, instead of their sum, standardizes each before they are added, so a projection with large raw values cannot dominate the sum: after normalization each contributes at the scale set by its own gain. The appendix defines the notation as

LN(z;α,β)=z−μσ⊙α+β\mathrm{LN}(\mathbf{z};\boldsymbol{\alpha},\boldsymbol{\beta}) = \frac{\mathbf{z}-\mu}{\sigma}\odot\boldsymbol{\alpha}+\boldsymbol{\beta}
(15)

with μ\mu and σ\sigma as in Eq. (3), so α\boldsymbol{\alpha} is the gain and starts at 1, and β\boldsymbol{\beta} is the bias and starts at 0. The appendix gives a matching GRU variant with four layer norms (Eqs. 26–28), and for the DRAW experiment applies a single layer norm to the LSTM cell state only (Eq. 31).

What the experiments show

The paper tests layer norm on six tasks, five of them recurrent. Unless noted, the gains start at 1 and the biases at 0. Layer norm trains faster on every task. On four the paper also reports a better final result, on handwriting a comparable one, and on MNIST it reports robustness to batch size and faster convergence.

Convolutional networks are the exception, reported from preliminary experiments: layer norm beats no normalization but batch norm beats layer norm. The authors' explanation is that in a fully connected layer the units tend to contribute similarly to the prediction, so one shared mean and variance fits them, while in a convolutional layer the many units whose receptive fields lie near the image boundary are rarely on and have very different statistics. They write that “further research is needed” to make layer norm work well in ConvNets.

The paper motivates normalization, as the batch norm paper did, by “covariate shift”: the inputs to a layer keep changing distribution as the layers below it learn, and fixing their mean and variance should reduce that. Santurkar et al. (2018) tested the explanation for batch norm. They injected noise with non-zero mean and non-unit variance after every batch-norm layer, found almost no difference in training, and argued that batch norm helps by making the loss landscape smoother. Their experiments are on batch norm only. The layer-norm paper proves the invariance table and measures faster training, mostly in recurrent networks; neither result depends on the covariate-shift explanation.

From 2016 layer norm to Transformers and RMSNorm

The Transformer (June 2017) made layer norm standard. It applies a layer norm after every residual addition, LN(x+Sublayer(x))\mathrm{LN}(x + \mathrm{Sublayer}(x)), an arrangement later called Post-LN. Moving the norm inside each residual branch instead, x+Sublayer(LN(x))x + \mathrm{Sublayer}(\mathrm{LN}(x)) (Pre-LN), trains more stably; Xiong et al. (2020) analysed it and showed its gradients are well-behaved at initialization, while calling it “recently proposed”, so the practice predates their paper. In both arrangements the vector being normalized is a token's residual-stream vector of width dmodeld_{\text{model}} (512 in the original Transformer), and the normalization is over that vector, one token at a time.

The 2016 paper applies it at a different spot. There, layer norm standardizes a layer's pre-activation summed inputs and the nonlinearity follows, h=f(LN(a))\mathbf{h} = f(\mathrm{LN}(\mathbf{a})). In a Transformer it standardizes an activation vector with no nonlinearity right after it, using the same statistics.

RMSNorm (Zhang and Sennrich, 2019) drops the mean subtraction and usually the bias, and divides by the root mean square 1H∑iai2\sqrt{\tfrac{1}{H}\sum_i a_i^2} alone. Its authors hypothesized that the re-centering invariance is dispensable, and LLaMA and Mistral use RMSNorm. Without the mean subtraction, RMSNorm loses one of layer norm's invariances: re-centering the weight matrix (Eq. 6) is no longer cancelled. Figure 7 isolates that difference. Add the same offset to every component of a vector and compare the two outputs.

Figure 7 · layer norm vs RMSNorm
+0.80
Add an offset to every component of a vector. Layer norm erases it, because it subtracts the mean. RMSNorm keeps it, because it only divides by the root-mean-square and never re-centers, and it skips computing the mean and the bias to do so.
Provenance Verified against primary literatureHow we verify
Batch Normalization (Ioffe & Szegedy 2015)The per-unit, across-batch normalization that layer norm transposes. Its Eq. (2) form, with expectations over the data estimated from the mini-batch, is the one quoted here.
Weight Normalization (Salimans & Kingma 2016)The third method in Table 1: mu = 0, sigma = ||w||_2. Its Sec. 2.1 proves that plain gradient descent on a scale-invariant weight vector grows the vector's norm every step (Pythagoras) and notes this does not strictly hold with momentum or Adam. Figure 5 on this page applies that algebra to layer norm's whole weight matrix.
Natural gradient (Amari 1998)The KL / Fisher-metric view of a parameter step, Eq. (8). The layer-norm paper applies it to normalized generalized linear models; the idea is Amari's.
Cooijmans et al. (2016)Recurrent batch normalization: separate statistics per time-step and a gain initialized to 0.1, the setup the attentive-reader experiment compares against.
Santurkar et al. (2018)Contest the internal-covariate-shift explanation for batch norm and argue it smooths the loss landscape. The argument is about batch norm; it was not run on layer norm.
Transformer (2017) · Xiong et al. (2020) · RMSNorm (2019)Post-LN in the original Transformer; Pre-LN analysed by Xiong et al., who call it recently proposed; RMSNorm drops the mean subtraction. None of these is in the 2016 paper.
correctionTwo slips in the paper. (1) The appendix defines LN(z; α, β) = ((z − μ)/σ) ⊙ α + β and calls α the gains and β the biases (Eq. 15), so α multiplies. The sentences under the LSTM, GRU and DRAW equations then call α additive and β multiplicative and initialize α to zeros and β to ones. Read against Eq. 15, that multiplies every standardized input by zero, so every LN output would be the constant 1 whatever the input. Taken on its own the sentence is consistent (additive part 0, multiplicative part 1); the names are swapped relative to Eq. 15. Section 6 gives the intended default, gains 1 and biases 0, which is what this page teaches and what nn.LayerNorm does. (2) Section 5.1 says "all the normalization methods are invariant to re-scaling the dataset", but Table 1 marks weight normalization No for that column, and the table is right: a/||w|| scales with the data. Figure 3 on this page reproduces every cell of Table 1.

Questions you might still have

?

Why not just keep using batch normalization?
Batch norm takes each unit's mean and variance over the mini-batch, so it needs a reasonably large batch, computes something different at test time (frozen running averages), and in a recurrent network needs separate statistics per time-step. Layer norm takes the statistics over one case's own units, which removes all three constraints. On convolutional networks batch norm still won in the paper's preliminary experiments.

?

Does layer norm really work at batch size 1?
Yes. The mean and standard deviation come from the H units of the layer on a single case, so one case is enough. The training and test computations are also identical, because there is nothing batch-dependent to estimate and freeze.

?

Where do the gain and bias go, and how are they initialized?
After standardizing and before the nonlinearity: h = f(g * a_hat + b), one gain and one bias per unit. They start at gain 1 and bias 0, so at initialization layer norm is a pure standardizer. The paper's appendix states the initialization with the names swapped in three sentences; gain 1, bias 0 is the intended version.

?

Is this the same LayerNorm as in Transformers?
Same statistics, different spot. The 2016 paper normalizes a layer's summed inputs and then applies the nonlinearity. In a Transformer, LayerNorm is applied to the residual-stream vector with no nonlinearity right after it, first after each residual add (Post-LN, 2017) and later inside each branch (Pre-LN). RMSNorm, used by LLaMA and Mistral, drops the mean subtraction. None of those variants is in the paper.

?

Why does the paper leave layer norm off the softmax layer?
Layer norm makes a layer's output unchanged when its input vector is scaled, but the scale of the logits is what sets the confidence of a softmax prediction. Normalizing the logits would fix every prediction's confidence, so the MNIST experiment applies layer norm only to the hidden layers.

?

Does layer norm work because it reduces internal covariate shift?
That was the motivation the paper inherited from batch norm, and it is contested. Santurkar et al. (2018) showed batch-norm networks train about as well when non-zero-mean, non-unit-variance noise is injected after every batch-norm layer, and argued batch norm smooths the loss landscape instead. Layer norm's properties that are proven in the paper are its invariances; its faster training is an experimental result.

?

What does epsilon do, and why is it missing from the paper?
Real implementations compute (a - mu) / sqrt(var + eps), with eps around 1e-5, so the division stays finite when all H inputs happen to be nearly equal. The paper's equations have no epsilon. For any vector whose variance is much larger than eps, the output barely changes.

Footnotes & further reading

  1. The paper: Ba, Kiros, Hinton, Layer Normalization (University of Toronto, 2016). The invariance table is Table 1; the appendix with the LSTM and GRU equations follows the references.
  2. The method it transposes: Ioffe & Szegedy, Batch Normalization: Accelerating Deep Network Training by Reducing Internal Covariate Shift (2015), explained here.
  3. The third method compared: Salimans & Kingma, Weight Normalization (2016), whose Section 2.1 has the norm-growth argument used in Figure 5; and recurrent batch norm: Cooijmans et al., Recurrent Batch Normalization (2016).
  4. The geometry: Amari, Natural Gradient Works Efficiently in Learning (1998). The covariate-shift dispute: Santurkar et al., How Does Batch Normalization Help Optimization? (2018), and the layer-norm-specific follow-up, Xu et al., Understanding and Improving Layer Normalization (2019).
  5. Later developments: Vaswani et al., Attention Is All You Need (2017), explained here; the Pre-LN analysis, Xiong et al., On Layer Normalization in the Transformer Architecture (2020); and RMSNorm, Zhang & Sennrich, Root Mean Square Layer Normalization (2019), as used in LLaMA and Mistral.