Final 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=γf⊙x−μd(x)σd2(x)+ε+βfε=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_{f}\odot\frac{x-\mu_d(x)}{\sqrt{\sigma_d^2(x)+\varepsilon}}+\beta_{f}\\\varepsilon&=10^{-5}\end{aligned}
in
x12x_{12} [B batch, T positions, 768 d]
out
hfinalh_{\mathrm{final}} [B batch, T positions, 768 d]
Parameters1,536

1,536 parameters per instance.

ComponentParameters
Learned gain768
Learned bias768
Per-instance total1,536

Not checked against a checkpoint.

Sources

In codenorm(h, 'ln_f')

Open pinned code ↗

Direct evidence

The final norm follows the layer loop.

model.py 28–167 ↗ · 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

… lines 39–162 omitted …

        for layer, past in enumerate(pasts):
            h, present = block(h, 'h%d' % layer, past=past, hparams=hparams)
            presents.append(present)
        results['present'] = tf.stack(presents, axis=1)
        h = norm(h, 'ln_f')

Transformers registers ln_f once on the base model.

modeling_gpt2.py 492–497 ↗ · huggingface/transformers @ 71c6f699ac9b

Excerpt
        self.h = nn.ModuleList([GPT2Block(config, layer_idx=i) for i in range(config.num_hidden_layers)])
        self.ln_f = nn.LayerNorm(self.embed_dim, eps=config.layer_norm_epsilon)