Equations · Ba, Kiros and Hinton, “Layer Normalization” (2016)

The LayerNorm formula, explained

LayerNorm rescales each token's feature vector to mean 0 and variance 1, then applies a learned scale and shift. Unlike BatchNorm, it does not look at other examples in the batch.

LayerNorm⁡(x)=γ⊙x−μσ2+ϵ+β,μ=1d∑i=1dxi,σ2=1d∑i=1d(xi−μ)2\operatorname{LayerNorm}(\mathbf{x}) = \boldsymbol{\gamma} \odot \frac{\mathbf{x} - \mu}{\sqrt{\sigma^2 + \epsilon}} + \boldsymbol{\beta}, \quad \mu = \frac{1}{d}\sum_{i=1}^{d} x_i, \quad \sigma^2 = \frac{1}{d}\sum_{i=1}^{d} (x_i - \mu)^2

Open in the decoder →

Term by term

  1. x\mathbf{x}

    One token's feature vector, of length dd.

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

    The mean of that vector's entries.

  3. σ2\sigma^2

    The variance of the entries. Here σ\sigma is a standard deviation, not the sigmoid.

  4. σ2+ϵ\sqrt{\sigma^2 + \epsilon}

    The standard deviation, with a small ϵ\epsilon (about 10−510^{-5}) so a constant vector does not cause division by zero.

  5. γ⊙…+β\boldsymbol{\gamma} \odot \ldots + \boldsymbol{\beta}

    A learned per-feature scale and shift, applied elementwise, so the layer can undo the normalization where that helps.

A small worked example

x=(1,2,3)\mathbf{x} = (1, 2, 3): μ=2\mu = 2, σ2=1+0+13=0.667\sigma^2 = \frac{1 + 0 + 1}{3} = 0.667, σ≈0.816\sigma \approx 0.816. Normalized: (−1.22,0,1.22)(-1.22, 0, 1.22). With γ=1\boldsymbol{\gamma} = \mathbf{1} and β=0\boldsymbol{\beta} = \mathbf{0}, that is the output.

In code

import numpy as np

def layer_norm(x, gamma, beta, eps=1e-5):
    mu = x.mean(-1, keepdims=True)
    var = x.var(-1, keepdims=True)
    return gamma * (x - mu) / np.sqrt(var + eps) + beta

Every symbol in it

x∈Rd\mathbf{x} \in \mathbb{R}^{d}Bold lowercase (vector)μ\muMu∑i=1Nxi\sum_{i=1}^{N} x_iSummationab\frac{a}{b}Fractionσ(z)\sigma(z)Sigma (lowercase)Var⁡[X]\operatorname{Var}[X]Variancedk\sqrt{d_k}Square rootϵ\epsilonEpsilonγ\gammaGammaβ1,β2\beta_1, \beta_2Betaa⊙b\mathbf{a} \odot \mathbf{b}Hadamard (elementwise) product

Other equations