Transformer block
Pre-attention LayerNorm
×learnednorm(x, 'ln_1')
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 · modeling_gpt2.py 252, 272–273
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 self.ln_1 = nn.LayerNorm(hidden_size, eps=config.layer_norm_epsilon) residual = hidden_states
hidden_states = self.ln_1(hidden_states)Sources2
Direct evidence
Original LayerNorm implementation and ε = 10⁻⁵.
openai · openai/gpt-2 / src/model.py
Pinned revision 9b63575ef427 ↗ · lines 28–38
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 xDirect evidence
PyTorch delegates the operation to nn.LayerNorm with the checkpoint epsilon.
transformers · huggingface/transformers / src/transformers/models/gpt2/modeling_gpt2.py
Pinned revision 71c6f699ac9b ↗ · lines 252–273
Read code 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)