All formulas

Machine learning building blocks

Layer normalization

ml.layer-normAlso called layer norm, layernorm, layer normalization, ln

yi=γixi−μσ2+ϵ+βiy_i = \gamma_i\frac{x_i - \mu}{\sqrt{\sigma^2 + \epsilon}} + \beta_i

whereμ=1n∑j=1nxj\mu = \frac{1}{n}\sum_{j=1}^{n} x_j

whereσ2=1n∑k=1n(xk−μ)2\sigma^2 = \frac{1}{n}\sum_{k=1}^{n} (x_k - \mu)^2

Normalizes a feature vector to zero mean and unit variance, using the population (biased) variance, then applies a per-feature scale γ and shift β. Defaults match torch.nn.LayerNorm: γ = 1, β = 0, ε = 1e-5.

Notation

xx

features of one example

x ∈ ℝn

γ\gamma

per-feature scale

γ ∈ ℝn · default 1 in every entry

β\beta

per-feature shift

β ∈ ℝn · default 0 in every entry

ϵ\epsilon

added to the variance before the square root

ε ≥ 0 · default 1e-5 · also common: 1e-6, 1e-12, 0

nn

number of entries

Size, at least 2

yy

Result: the normalized features

vector

Worked examples

Each result is solved exactly and confirmed by two independent computations.

  1. Given

    x=[1,3],ϵ=0x = [1, 3], \epsilon = 0

    Result

    y=(−1,1)\displaystyle y = \left(-1, 1\right)
  2. Given

    x=[1,2,3,4],ϵ=0x = [1, 2, 3, 4], \epsilon = 0

    Result

    y=(−355,−55,55,355)\displaystyle y = \left(- \frac{3 \sqrt{5}}{5}, - \frac{\sqrt{5}}{5}, \frac{\sqrt{5}}{5}, \frac{3 \sqrt{5}}{5}\right)

    ≈ (-1.3416407865, -0.4472135955, 0.4472135955, 1.3416407865)

  3. Given

    x=[0,2],γ=[2,2],β=[1,−1]x = [0, 2], \gamma = [2, 2], \beta = [1, -1]

    Result

    y=(1−2001000010100001,−1+2001000010100001)\displaystyle y = \left(1 - \frac{200 \sqrt{1000010}}{100001}, -1 + \frac{200 \sqrt{1000010}}{100001}\right)

    ≈ (-0.999990000075, 0.999990000075)

Common mistakes

  • Uses the sample variance (divides by n − 1)

    Layer normalization uses the population variance; torch.var and pandas default to n − 1.

    Fix: Divide the squared deviations by n (torch.var(..., unbiased=False), numpy.var).

  • Adds ε to the standard deviation

    ε is added after the square root, σ + ε, instead of inside it, √(σ2 + ε).

    Fix: Add ε to the variance and then take the square root.

Notes

  • ε guards against division by zero. Its default differs between libraries, which changes the result when the variance is small.

Source

  • Ba et al. 2016

    Ba, Jimmy Lei; Kiros, Jamie Ryan; Hinton, Geoffrey E. Layer Normalization. arXiv:1607.06450, 2016.

    arxiv.org