Layer Normalization › The Layer Normalization Formula

Michael BrenndoerferUpdated June 11, 20259 min read
Language AI HandbookAll chapters
Part 15 of 67Transformer Blocks
Chapter 104Layer Normalization › The Layer Normalization Formula
Reading section 3 of 16 · The Layer Normalization Formula · 9 minSection 3 of 16 · 9 min

Book contents

Section 3 of 16 · 9 min read

Layer Normalization › The Layer Normalization FormulaOne section · Sections in this chapter3 / 16 ↓
Reading tools Definitions & inline links

Choose your expertise level to adjust how many terms are explained. Beginners see more tooltips, experts see fewer to maintain reading flow. Hover over underlined terms for instant definitions.

Article links

Make inline references clickable

To understand layer normalization, let's start with a fundamental question: what does it mean for a neural network layer to have "unstable" activations, and how can we fix it?

The Problem: Activation Scale Drift

Imagine a token's hidden representation as a vector of 768 numbers (a typical transformer dimension). During training, these numbers can drift: some become very large, others very small, and their collective distribution shifts unpredictably. This creates two problems. First, downstream layers must constantly adapt to changing input statistics, making learning inefficient. Second, when values grow too large or too small, gradients either explode or vanish, destabilizing training entirely.

The solution is elegant: before each token's representation moves to the next layer, we transform it to have a predictable, standardized distribution. Specifically, we want the 768 features to have zero mean and unit variance. This "resets" the scale at every layer, preventing drift from accumulating.

The key insight is that we don't need to look outside the current token to achieve this. The token's own 768 values carry all the information we need to compute a mean and a standard deviation. Subtract the mean, divide by the standard deviation, and you have a normalized representation that is stable regardless of how the upstream weights evolved during training.

In practice, this normalization is applied at multiple points within each transformer block. This ensures that neither the attention mechanism nor the feed-forward network ever sees wildly out-of-distribution inputs. The cumulative effect over many layers is dramatic: networks with layer normalization can train stably with learning rates that would cause catastrophic divergence in networks without it.

Step 1: Finding the Center

The first step is computing where the current distribution is centered. Given a hidden state vector x=[x1,x2,…,xd]\mathbf{x} = [x_1, x_2, \ldots, x_d] representing one token, we calculate its mean:

μ=1d∑i=1dxi\mu = \frac{1}{d} \sum_{i=1}^{d} x_i

where:

  • μ\mu: the arithmetic mean of all dd features in this token's representation
  • dd: the hidden dimension (e.g., 768 for BERT-base, 4096 for LLaMA-7B)
  • xix_i: the value of the ii-th feature

This tells us the "center of mass" of the representation. If μ=2.5\mu = 2.5, the features are shifted toward positive values; if μ=−1.3\mu = -1.3, they lean negative. The goal is to shift this center to zero.

Step 2: Measuring the Spread

Next, we need to know how spread out the values are. A representation where all values cluster tightly around the mean is very different from one where values are scattered widely. We capture this with variance:

σ2=1d∑i=1d(xi−μ)2\sigma^2 = \frac{1}{d} \sum_{i=1}^{d} (x_i - \mu)^2

where:

  • σ2\sigma^2: the variance, measuring how much the features deviate from their mean
  • (xi−μ)2(x_i - \mu)^2: the squared deviation of each feature from the mean

Squaring ensures that positive and negative deviations don't cancel out. If σ2\sigma^2 is large, the features are spread out; if small, they're tightly clustered. We'll use the standard deviation σ=σ2\sigma = \sqrt{\sigma^2} to rescale the values to unit variance.

Notice that we use the population variance (dividing by dd) rather than the sample variance (dividing by d−1d - 1). This is a deliberate choice: we're not trying to estimate the variance of an underlying population; we're computing the exact variance of the dd values in front of us. Using dd rather than d−1d - 1 gives us an unbiased estimator for the squared deviation within this specific vector, which is what we need for a deterministic normalization operation.

Step 3: The Normalization Transform

With mean and variance in hand, we can now standardize each feature:

x^i=xi−μσ2+ϵ\hat{x}_i = \frac{x_i - \mu}{\sqrt{\sigma^2 + \epsilon}}

where:

  • x^i\hat{x}_i: the normalized value of the ii-th feature
  • ϵ\epsilon: a tiny constant (typically 10−510^{-5}) added to prevent division by zero if variance is extremely small

This two-part transformation is exactly what you'd do to standardize any dataset: subtract the mean (centering at zero), then divide by the standard deviation (scaling to unit variance). The result x^i\hat{x}_i has zero mean and approximately unit variance across the dd features.

The subtraction by μ\mu ensures the output is centered at zero, removing any bias in the representation. The division by σ2+ϵ\sqrt{\sigma^2 + \epsilon} ensures that features with large variance are scaled down to unit range, and features with small variance are scaled up. This compression of the dynamic range is what prevents activations from exploding across layers.

Step 4: Restoring Flexibility with Learnable Parameters

Layer normalization need not be restrictive. Forcing every representation to have exactly zero mean and unit variance might seem limiting: what if the optimal representation for some layer needs a different distribution?

The solution is to add learnable parameters that can undo the normalization if needed:

yi=γi⋅x^i+βiy_i = \gamma_i \cdot \hat{x}_i + \beta_i

where:

  • yiy_i: the final output for the ii-th feature
  • γi\gamma_i: a learned scale parameter for feature ii (initialized to 1)
  • βi\beta_i: a learned shift parameter for feature ii (initialized to 0)

These parameters are learned during training, just like weights and biases. If the network discovers that feature ii should have mean 3.5 and standard deviation 2.0, it can learn γi=2.0\gamma_i = 2.0 and βi=3.5\beta_i = 3.5 to recover that distribution. This means layer normalization never reduces the network's representational power: it starts from a stable baseline but can learn any distribution it needs.

The initialization of γ=1\gamma = 1 and β=0\beta = 0 is deliberate. At the start of training, layer normalization acts as a pure standardization with no modification: the output is exactly the normalized input. As training progresses, γ\gamma and β\beta adjust to whatever distribution the subsequent layers find most useful. This means the network starts with the stability benefits of normalization and gradually adapts to the specific distribution requirements of the task, without ever losing the ability to represent the original data.

The Complete Formula

Putting all the pieces together, layer normalization maps a hidden state vector x\mathbf{x} of dimension dd into:

LayerNorm(x)=γ⊙x−μσ2+ϵ+β\text{LayerNorm}(\mathbf{x}) = \gamma \odot \frac{\mathbf{x} - \mu}{\sqrt{\sigma^2 + \epsilon}} + \beta

where:

  • x=[x1,x2,…,xd]\mathbf{x} = [x_1, x_2, \ldots, x_d]: the input vector representing one token's hidden state
  • μ=1d∑i=1dxi\mu = \frac{1}{d} \sum_{i=1}^{d} x_i: the mean across all features
  • σ2=1d∑i=1d(xi−μ)2\sigma^2 = \frac{1}{d} \sum_{i=1}^{d} (x_i - \mu)^2: the variance across all features
  • ϵ\epsilon: a small stability constant (typically 10−510^{-5} or 10−610^{-6})
  • γ=[γ1,γ2,…,γd]\gamma = [\gamma_1, \gamma_2, \ldots, \gamma_d]: learned scale parameters, initialized to ones
  • β=[β1,β2,…,βd]\beta = [\beta_1, \beta_2, \ldots, \beta_d]: learned shift parameters, initialized to zeros
  • ⊙\odot: element-wise multiplication

The formula reads naturally: subtract the mean, divide by the standard deviation (with a safety epsilon), then apply a learned scale and shift.

Why Features, Not Samples?

The key insight that distinguishes layer normalization from batch normalization is the dimension over which we compute statistics. Batch normalization asks: "What's the typical value of feature ii across all samples in this batch?" Layer normalization asks: "What's the typical value across all features for this particular token?"

For transformers, the layer normalization approach is far more natural. Each token is processed independently, and we want stable statistics regardless of what other tokens or samples happen to be in the batch. This independence also means layer normalization works identically during training and inference, with no need for running statistics or batch size considerations.

To make this concrete, consider a transformer with hidden dimension 512. Batch normalization would compute 512 separate statistics (one per feature dimension), each estimated from however many tokens appear at the same position across the batch. Layer normalization computes 2 statistics (one mean and one variance) from the 512 features of a single token. The batch normalization statistics are estimates that improve with larger batches; the layer normalization statistics are exact computations that require no batch at all. During inference when you process one sequence at a time, layer normalization requires no special handling; batch normalization in inference mode must use stored running statistics from training, which may not accurately represent the test distribution.

Out[5]:
Visualization
Diagram showing batch normalization highlighting a column across batch samples.
Batch normalization computes statistics across samples (blue column). For each feature, the mean and variance are estimated over all batch samples. This requires a meaningful batch size and produces statistics that change across sequence positions.
Diagram showing layer normalization highlighting a row across features.
Layer normalization computes statistics across features (orange row). For each token, the mean and variance are computed over all feature dimensions. Statistics are exact and independent of batch size or other samples.