Pre-LN, as depicted
\(Y=X+F(\operatorname{Norm}(X))\)
Normalize before the sublayer.
Lesson 16 of 23 · Transformer block
Your win: calculate a normalized token vector and distinguish LayerNorm, RMSNorm, Pre-LN, and Post-LN.
For one token vector \(\mathbf x\in\mathbb R^d\), calculate statistics across its \(d\) features:
Ignoring tiny \(\varepsilon\) and taking \(\gamma=1,\beta=0\):
For \((1,2,3)\), \(\operatorname{RMS}=\sqrt{14/3}\approx2.160\), so the unscaled output is approximately \((0.463,0.926,1.389)\). Unlike LayerNorm, its mean is not forced to zero.
RMSNorm rescales each token across its feature axis. The batch and sequence axes stay separate, and the output keeps the same \([B,T,D]\) shape.
\(Y=X+F(\operatorname{Norm}(X))\)
Normalize before the sublayer.
\(Y=\operatorname{Norm}(X+F(X))\)
Normalize after residual addition.
LayerNorm vs RMSNorm asks what computation? Pre-LN vs Post-LN asks where is it placed?
MiniMind uses RMSNorm. Notice that mean(dim=-1) reduces only the feature axis, independently for every batch item and token.
class RMSNorm(nn.Module):
def __init__(self, width, eps=1e-6):
super().__init__()
self.eps = eps
self.weight = nn.Parameter(torch.ones(width))
def forward(self, x):
rms = torch.rsqrt(
x.float().pow(2).mean(dim=-1, keepdim=True) + self.eps
)
return (x.float() * rms * self.weight).to(dtype=x.dtype)Trace it: For x.shape == [2, 3, 8], what is the shape of rms after keepdim=True?
The full MiniMind block owns an input_layernorm before attention and a post_attention_layernorm before the feed-forward route. Both compute their statistics in float32, then cast the normalized result back to the incoming dtype for the residual path.
residual = hidden_states
hidden_states, present = self.self_attn(
self.input_layernorm(hidden_states), position_embeddings,
past_key_value, use_cache, attention_mask
)
hidden_states = hidden_states + residual
hidden_states = hidden_states + self.mlp(
self.post_attention_layernorm(hidden_states)
)Shape check: each norm maps [B, T, D] -> [B, T, D]; the two residual additions therefore remain elementwise valid.
Answer once before reopening the code; use the feedback to correct your explanation.
Which axis supplies the mean and variance for one token?
STAGE 4 · PROVE IT
Primary sources: Ba et al., Layer Normalization; Zhang and Sennrich, RMSNorm; Xiong et al., Pre-LN vs Post-LN.