Layer

Pre-attention LayerNorm

×

Center and scale each position’s features, then apply learned gain and bias.

μd(x)=1d∑j=1dxjσd2(x)=1d∑j=1d(xj−μd(x))2y=γ1⊙x−μd(x)σd2(x)+ε+β1ε=10−5\begin{aligned}\mu_d(x)&=\frac{1}{d}\sum_{j=1}^d x_j\\\sigma_d^2(x)&=\frac{1}{d}\sum_{j=1}^d(x_j-\mu_d(x))^2\\y&=\gamma_{1}\odot\frac{x-\mu_d(x)}{\sqrt{\sigma_d^2(x)+\varepsilon}}+\beta_{1}\\\varepsilon&=10^{-5}\end{aligned}
in
xnx_n [B batch, T positions, 768 d]
out
xattnx_{\mathrm{attn}} [B batch, T positions, 768 d]
Parameters1,536 × 12 layers

1,536 parameters per instance.

ComponentParameters
Learned gain768
Learned bias768
Per-instance total1,536

One in each of the 12 layers, each with its own weights.

Not checked against a checkpoint.

Sources

In codenorm(x, 'ln_1')

Open pinned code ↗

Direct evidence

Original LayerNorm implementation and ε = 10⁻⁵.

model.py 28–38 ↗ · openai/gpt-2 @ 9b63575ef427

Excerpt
def norm(x, scope, *, axis=-1, epsilon=1e-5):
    """Normalize to mean = 0, std = 1, then do a diagonal affine transform."""
    with tf.variable_scope(scope):
        n_state = x.shape[-1].value
        g = tf.get_variable('g', [n_state], initializer=tf.constant_initializer(1))
        b = tf.get_variable('b', [n_state], initializer=tf.constant_initializer(0))
        u = tf.reduce_mean(x, axis=axis, keepdims=True)
        s = tf.reduce_mean(tf.square(x-u), axis=axis, keepdims=True)
        x = (x - u) * tf.rsqrt(s + epsilon)
        x = x*g + b
        return x

PyTorch delegates the operation to nn.LayerNorm with the checkpoint epsilon.

modeling_gpt2.py 252–273 ↗ · huggingface/transformers @ 71c6f699ac9b

Excerpt
        self.ln_1 = nn.LayerNorm(hidden_size, eps=config.layer_norm_epsilon)

… lines 253–271 omitted …

        residual = hidden_states
        hidden_states = self.ln_1(hidden_states)