Transformer block
Pre-MLP LayerNorm
×learnednorm(x, 'ln_2')
Center and scale each position’s features, then apply learned gain and bias.
- in
- [B batch, T positions, 768 d]
- out
- [B batch, T positions, 768 d]
- parameters
- 1,536 · × 12 blocks = 18,432
Parameters
1,536 parameters per instance.
| Component | Calculation | Parameters |
|---|---|---|
| Learned gain | 768 | |
| Learned bias | 768 | |
| Per-instance total | 1,536 | |
Each normalization instance owns its learned gain and bias vectors.
Across 12 independent blocks: parameters.
Derived from the configured feature width; checkpoint tensors have not been independently counted.
Explanation
Codemodel.py 28–38, 128 · modeling_gpt2.py 254, 303–305
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 m = mlp(norm(x, 'ln_2'), 'mlp', nx*4, hparams=hparams) self.ln_2 = nn.LayerNorm(hidden_size, eps=config.layer_norm_epsilon) residual = hidden_states
hidden_states = self.ln_2(hidden_states)
feed_forward_hidden_states = self.mlp(hidden_states)Sources2
Direct evidence
The second normalization appears directly inside the MLP call.
openai · openai/gpt-2 / src/model.py
Pinned revision 9b63575ef427 ↗ · lines 28–128
Read code 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–127 omitted …
m = mlp(norm(x, 'ln_2'), 'mlp', nx*4, hparams=hparams)Direct evidence
A second nn.LayerNorm instance precedes the MLP.
transformers · huggingface/transformers / src/transformers/models/gpt2/modeling_gpt2.py
Pinned revision 71c6f699ac9b ↗ · lines 254–305
Read code excerpt
self.ln_2 = nn.LayerNorm(hidden_size, eps=config.layer_norm_epsilon)… lines 255–302 omitted …
residual = hidden_states
hidden_states = self.ln_2(hidden_states)
feed_forward_hidden_states = self.mlp(hidden_states)