Layer

×

A pre-normalized residual update: read the stream, compute attention, add; read again, compute the feed-forward, add.

xn+1=Layer⁡n(xn){\htmlData{light=block}{x_{n+1}}}=\operatorname{Layer}_{n}(x_{n})
in
xnx_{n} [B batch, T positions, 768 d]
out
xn+1x_{n+1} [B batch, T positions, 768 d]
Parameters7,087,872 × 12 layers

7,087,872 parameters per layer, across its learned components

ComponentCalculationParameters
Pre-attention LayerNorm768 + 7681,536
Masked multi-head self-attention2,362,368
Pre-MLP LayerNorm768 + 7681,536
Position-wise feed-forward network4,722,432
Per-instance total7,087,872

One of 12 independent layers.

Not checked against a checkpoint.

Each of the 12 layer addresses owns independent weights. The implementation names the first and last addresses h.0 and h.11.

Sources

In codeblock(h, 'h%d' % layer, past=past, hparams=hparams)

Open pinned code ↗

Direct evidence

The released layer performs both pre-normalized residual writes and returns the updated stream.

model.py 123–130 ↗ · openai/gpt-2 @ 9b63575ef427

Excerpt
        a, present = attn(norm(x, 'ln_1'), 'attn', nx, past=past, hparams=hparams)
        x = x + a
        m = mlp(norm(x, 'ln_2'), 'mlp', nx*4, hparams=hparams)
        x = x + m
        return x, present

The maintained implementation preserves the same two residual branches.

modeling_gpt2.py 272–307 ↗ · huggingface/transformers @ 71c6f699ac9b

Excerpt
        residual = hidden_states
        hidden_states = self.ln_1(hidden_states)
        attn_output, _ = self.attn(
            hidden_states,
            past_key_values=past_key_values,
            attention_mask=attention_mask,
            use_cache=use_cache,
            **kwargs,
        )

… lines 281–281 omitted …

        hidden_states = attn_output + residual

… lines 283–302 omitted …

        residual = hidden_states
        hidden_states = self.ln_2(hidden_states)
        feed_forward_hidden_states = self.mlp(hidden_states)
        # residual connection
        hidden_states = residual + feed_forward_hidden_states