The Transformer Block

Dive into Deep Learning · §11.1

The Transformer Block: Pre-Norm, SwiGLU, and Signal Propagation
residual stream · pre-norm vs. post-norm · token collapse · RMSNorm & QK-Norm · SwiGLU · 12d² census

Why Stacking Attention Alone Fails at Depth

Motivation

  • No per-token nonlinearity: Without a position-wise FFN between attention layers, linear projections collapse to a single low-rank map on each token’s channels.
  • Token collapse & starved gradients: Stacking L = 32 post-norm blocks with Xavier initialization collapses token spread to \sim 10^{-4} and drops the query gradients of block 32, \|\partial \mathcal{L} / \partial \mathbf{W}_q^{(32)}\|_F, to \sim 10^{-9}.

Token Mixing vs. Channel Mixing on a Residual Stream

Block Anatomy

  • Shared residual stream \mathbf{X} \in \mathbb{R}^{B \times n \times d}: Rather than overwriting representations, each sublayer reads from the stream, computes an update in \mathbb{R}^{B \times n \times d}, and adds it back.
  • Multi-head attention (token mixing): The only operator where sequence positions 1, \dots, n communicate (4d^2 parameters).
  • Position-wise FFN (channel mixing): Applies an identical MLP to each token vector \mathbf{x}_i \in \mathbb{R}^d independently, transforming the context gathered by attention (8d^2 parameters, or two-thirds of the block).
image/svg+xml Matplotlib v3.11.2, https://matplotlib.org/

Normalization Placement: Post-Norm vs. Pre-Norm

Normalization Placement

  • Post-norm (2017 / BERT): Places normalization on the main residual stream itself: \mathbf{H} = \mathrm{Norm}_1(\mathbf{X} + \mathrm{Attn}(\mathbf{X})), \quad \mathbf{Y} = \mathrm{Norm}_2(\mathbf{H} + \mathrm{FFN}(\mathbf{H}))
  • Pre-norm (GPT-2 / Llama / Qwen): Moves normalization onto each sublayer’s input branch so the main stream runs uninterrupted: \mathbf{H} = \mathbf{X} + \mathrm{Attn}(\mathrm{Norm}_1(\mathbf{X})), \quad \mathbf{Y} = \mathbf{H} + \mathrm{FFN}(\mathrm{Norm}_2(\mathbf{H}))

Post-Norm and Pre-Norm Differ by Two Lines of Code

Implementation

Our diagnostic MiniBlock uses identical weights for both placements, switching only whether norm1 and norm2 wrap the residual sum or the branch inputs:

def forward(self, X):
    if self.pre_norm:                      # Pre-norm: normalize each branch input
        Y = self.norm1(X)
        X = X + self.attention(Y, Y, Y)
        return X + self.ffn(self.norm2(X))
    X = self.norm1(X + self.attention(X, X, X))  # Post-norm: normalize the stream
    return self.norm2(X + self.ffn(X))

Because an untrained L-block stack is a deterministic random function, we can measure how both placements propagate signal variance, inter-token diversity, and gradients at initialization (t = 0).

Why Post-Norm Squeezes Tokens Together Across Depth

Mechanism of Token Collapse

  • Decompose each token vector \mathbf{x}_i = \boldsymbol{\mu} + \boldsymbol{\delta}_i into the sequence mean \boldsymbol{\mu} = \frac{1}{n}\sum_j \mathbf{x}_j and token-specific deviation \boldsymbol{\delta}_i.
  • Random attention reinforces \boldsymbol{\mu}: Uniform initial weights add \mathbf{W}_o\mathbf{W}_v\boldsymbol{\mu} to every token while deviations \boldsymbol{\delta}_i cancel.
  • Post-norm rescales downward: Dividing every token by the same factor restores the stream’s length but shrinks \boldsymbol{\delta}_i relative to \boldsymbol{\mu} at every layer (LayerNorm centers channels, not tokens).

Predicting the Exponential Rate of Token Collapse

Mathematical Derivation

  • Let \rho = n\|\boldsymbol{\mu}\|^2 / \sum_{i=1}^n \|\boldsymbol{\delta}_i\|^2 be the ratio of common-to-distinct token energy, so relative token spread is s = (1 + \rho)^{-1/2}.
  • With per-projection variance gain g^2 = d\sigma^2, each post-norm block amplifies \rho \mapsto (1 + g^4)\rho: s_k \approx \left(1 + \frac{(1 + g^4)^k}{63}\right)^{-1/2}

Measured Token Spread Matches the Analytical Law

Empirical Verification

  • Post-norm + Xavier (C0): Token spread decays exponentially across depth, falling to \sim 10^{-4} by block 32 (slightly below the attention-only dotted curve because GELU’s positive mean adds a small shared vector in the FFN too).
  • Post-norm + \mathcal{N}(0, 0.02^2) (C2): Small weights keep g^4 \approx 0.01, holding token spread at 0.97 through 32 layers at width d = 256.
  • Pre-norm + Xavier (C1): Even with large Xavier weights (g = 1), pre-norm preserves substantial token diversity (s_{32} \approx 0.37) without exponential collapse.

Pitfall: Fixed Weight Scale 0.02 Grows With Model Width

Width Scaling Pitfall

  • For \mathbf{W} \in \mathbb{R}^{d \times d} with fixed entry variance \sigma^2 = 0.02^2, the per-projection variance gain grows linearly with width d: g^2 = d \sigma^2 = 0.0004\,d
  • A fixed \sigma = 0.02 is only small for d \ll 2{,}500; at frontier widths (d = 4{,}096), g^2 = 1.64 > 1 collapses post-norm stacks even faster than Xavier.

Token Collapse Starves Query and Key Gradients

Backward Signal Propagation

  • Vanishing \mathbf{W}_q, \mathbf{W}_k gradients at the top: When incoming tokens \mathbf{x}_1, \dots, \mathbf{x}_n at block 32 are nearly identical, perturbing \mathbf{W}_q or \mathbf{W}_k shifts all attention scores equally and leaves the softmax weighted average unchanged (\|\nabla_{\mathbf{W}_q^{(32)}} \mathcal{L}\|_F \sim 10^{-9}).
  • Not backward attenuation: The post-norm \mathbf{W}_q gradient is largest at block 1 (\sim 10^{-2}) and shrinks with the square of the token spread; \mathbf{W}_v and \mathbf{W}_o gradients at block 32 match pre-norm in order of magnitude. Pre-norm (C1) loses a factor of about 30 over 32 blocks, not more than six orders of magnitude.

Pre-Norm Unrolled Stream and 1/√(2L) Residual Scaling

Pre-Norm Variance Control

  • Unrolling L pre-norm blocks reveals an uninterrupted identity highway: \mathbf{X}^{(L)} = \mathbf{X}^{(0)} + \sum_{\ell=1}^{L} \bigl(\mathrm{Attn}_\ell(\mathrm{Norm}(\mathbf{X}^{(\ell-1)})) + \mathrm{FFN}_\ell(\mathrm{Norm}(\mathbf{H}^{(\ell)}))\bigr)
  • GPT-2’s 1/\sqrt{2L} scaling rule: Scaling the initial std of the two residual write matrices per block (W_o and W_2) by 1/\sqrt{2L} keeps cumulative stream variance \sum_{m=1}^{2L} \frac{\sigma^2}{2L} = \sigma^2 = O(1) at any depth L.

RMSNorm: Dropping Mean-Centering for Speed

Normalization Form

Zhang & Sennrich (2019) showed that LayerNorm’s stability comes from bounding root-mean-square magnitude rather than centering the channel mean \mu = \frac{1}{d}\sum_j x_j:

\mathrm{RMSNorm}(\mathbf{x}) = \frac{\mathbf{x}}{\mathrm{RMS}(\mathbf{x})} \odot \boldsymbol{\gamma}, \qquad \mathrm{RMS}(\mathbf{x}) = \sqrt{\frac{1}{d}\sum_{j=1}^{d} x_j^2 + \epsilon}

ours vs. nn.RMSNorm: max deviation 0.0e+00
     x: RMSNorm  0.28  0.57  0.85  1.70 | LayerNorm -1.07 -0.53  0.00  1.60
    3x: RMSNorm  0.28  0.57  0.85  1.70 | LayerNorm -1.07 -0.53  0.00  1.60
x + 10: RMSNorm  0.84  0.91  0.99  1.22 | LayerNorm -1.07 -0.53  0.00  1.60

Scale vs. shift invariance: Both norms are invariant to positive rescaling (\mathbf{x} \mapsto 3\mathbf{x}), whereas adding a constant shift (\mathbf{x} \mapsto \mathbf{x} + 10) alters RMSNorm but leaves LayerNorm unchanged. Dropping \mu and \boldsymbol{\beta} saves one reduction pass over HBM per token.

Query–Key Normalization (QK-Norm) Bounds Logits

Attention Stability

  • Quadratic logit blow-up: If the spectral norms of \mathbf{W}_q and \mathbf{W}_k grow by \lambda during training, attention logits \mathbf{q}_i^\top \mathbf{k}_j / \sqrt{d_h} grow as \lambda^2, saturating softmax.
  • Per-head QK-Norm: Applying width-d_h RMSNorm to queries and keys enforces \|\hat{\mathbf{q}}_i\|_2 = \|\hat{\mathbf{k}}_j\|_2 = \sqrt{d_h}, imposing a hard Cauchy–Schwarz bound: \frac{|\hat{\mathbf{q}}_i^\top \hat{\mathbf{k}}_j|}{\sqrt{d_h}} \le \sqrt{d_h}

Empirical Logit and Entropy Invariance Under QK-Norm

QK-Norm Verification

Scaling \mathbf{W}_q and \mathbf{W}_k by \lambda \in \{1, 4, 16\} on n = 64 random tokens (d_h = 64, uniform entropy \ln 64 \approx 4.16 nats) demonstrates softmax collapse and QK-Norm recovery:

def logit_stats(Q, K):
    """Std of the scaled logits; mean entropy of each query's weights."""
    S = Q @ K.T / math.sqrt(Q.shape[-1])
    entropy = -(F.softmax(S, -1) * F.log_softmax(S, -1)).sum(-1).mean()
    return S.std(), entropy

d, d_h = 256, 64
X = torch.randn(64, d)                                # 64 random tokens
W_q, W_k = torch.randn(2, d, d_h) / math.sqrt(d)      # one head
for lam in (1, 4, 16):
    Q, K = X @ (lam * W_q), X @ (lam * W_k)
    s, h = logit_stats(Q, K)
    s_n, h_n = logit_stats(rms_norm(Q), rms_norm(K))
    print(f'lambda {lam:2d}: logit std {s:5.1f}, entropy {h:.2f} | '
          f'QK-norm: logit std {s_n:.2f}, entropy {h_n:.2f}')

QK-Norm Holds Logit Spread and Entropy Fixed

QK-Norm Verification

lambda  1: logit std   1.0, entropy 3.69 | QK-norm: logit std 1.01, entropy 3.69
lambda  4: logit std  16.3, entropy 0.25 | QK-norm: logit std 1.01, entropy 3.69
lambda 16: logit std 261.4, entropy 0.01 | QK-norm: logit std 1.01, entropy 3.69

Without QK-Norm, a 16\times weight growth inflates logit standard deviation by 16^2 = 256\times and collapses attention entropy to \approx 0.01\text{--}0.03 nats (one-hot); with QK-Norm, logit spread (\approx 1.0) and entropy (\approx 3.7) remain completely invariant.

The Feed-Forward Network as a Key–Value Memory

Channel Mixing

  • Writing the two-layer FFN in terms of rows \mathbf{w}_{1,j} \in \mathbb{R}^d of \mathbf{W}_1 and columns \mathbf{w}_{2,j} \in \mathbb{R}^d of \mathbf{W}_2 reveals a content-addressed memory bank (Geva et al., 2021): \mathrm{FFN}_{\mathrm{GELU}}(\mathbf{x}) = \sum_{j=1}^{4d} \mathrm{GELU}(\mathbf{x}^\top \mathbf{w}_{1,j})\, \mathbf{w}_{2,j}
  • Dominant parameter share: Two d \times 4d matrices hold 8d^2 parameters (3{,}072 detector slots per block in GPT-2 Small).

From GELU MLPs to Gated SwiGLU Networks

Gated Feed-Forward Networks

  • Modern Transformers replace the two-matrix GELU MLP with a bias-free gated SwiGLU network (Shazeer, 2020): \mathrm{FFN}_{\mathrm{SwiGLU}}(\mathbf{x}) = \bigl(\mathrm{SiLU}(\mathbf{x}\mathbf{W}_g) \odot (\mathbf{x}\mathbf{W}_1)\bigr)\mathbf{W}_2
  • Matching the 8d^2 budget: Shrinking hidden width from 4d to d_{\text{ff}} = \operatorname{round}(\frac{8}{3}d) keeps the 3-matrix parameter count at 3 \times d \times \frac{8}{3}d = 8d^2.

Both FFN Variants in One Parameter-Matched Class

FeedForward Implementation

Our FeedForward module switches cleanly between a 4d GELU MLP and an \frac{8}{3}d SwiGLU network at the exact same 8d^2 parameter and FLOP budget:

width = 4 * num_hiddens if act == 'gelu' else round(8 * num_hiddens / 3)

def forward(self, X):
    if self.act == 'gelu':                        # 2 matrices of width 4d -> 8d^2
        return self.W_2(F.gelu(self.W_1(X), approximate='tanh'))
    return self.W_2(F.silu(self.W_g(X)) * self.W_1(X))  # 3 matrices of width 8d/3 -> 8d^2

At d = 256, act='gelu' uses 2 \times 256 \times 1024 = 524{,}288 parameters, while act='swiglu' uses 3 \times 256 \times 683 = 524{,}544 parameters (8.004\,d^2 due to rounding \frac{8}{3}\cdot 256 = 682.67 \to 683).

One Configurable TransformerBlock & Parameter Census

Unified Block & Census

TransformerBlock unifies norm ('rms' or 'layer'), act ('swiglu' or 'gelu'), pre_norm, bias, and pluggable attn_factory / ffn_factory hooks, always holding \approx 12d^2 parameters:

blocks = {'default': TransformerBlock(256, 8),
          'GELU': TransformerBlock(256, 8, act='gelu'),
          '2017': TransformerBlock(256, 8, norm='layer', act='gelu',
                                   pre_norm=False, bias=True)}
for name, blk in blocks.items():
    attn, ffn, total = (d2l.num_params(m)
                        for m in (blk.attention, blk.ffn, blk))
    print(f'{name:>7}: attention {attn:,}, FFN {ffn:,}, total {total:,} '
          f'= {total / 256 ** 2:.2f} d^2')
default: attention 262,144, FFN 524,544, total 787,200 = 12.01 d^2
   GELU: attention 262,144, FFN 524,288, total 786,944 = 12.01 d^2
   2017: attention 263,168, FFN 525,568, total 789,760 = 12.05 d^2

The 12d^2 rule of thumb: In every dense block with H_{\text{kv}} = H, multi-head attention holds 4d^2 parameters (\mathbf{W}_q, \mathbf{W}_k, \mathbf{W}_v, \mathbf{W}_o) and the FFN holds 8d^2 parameters, totaling 12d^2 per layer (7.08\text{M} per block at GPT-2’s d = 768).

Concept Check: Designing a Transformer Block

Check Your Understanding

Work out the following three design questions:

  1. Unfair ablation trap: A researcher replaces a 4d GELU FFN at d = 768 with a SwiGLU FFN but forgets to change the hidden width from 4d = 3{,}072 to \frac{8}{3}d = 2{,}048. How many extra parameters per block did they accidentally add?
  2. QK-Norm scaling: Without QK-Norm, multiplying \mathbf{W}_q and \mathbf{W}_k by \lambda = 8 scales attention logit standard deviation by what factor? What is the factor with QK-Norm?
  3. Depth scaling: In a 32-block pre-norm model, by what factor does GPT-2 scale the initial standard deviation of \mathbf{W}_o and \mathbf{W}_2?

Answers:

  1. +4d^2 \approx 2.36\text{M} extra parameters per block (12d^2 = 7.08\text{M} vs. 8d^2 = 4.72\text{M}, a 50\% FFN size increase), confounding architecture quality with model capacity.
  2. \lambda^2 = 64\times without QK-Norm (driving softmax to one-hot); 1\times (invariant) with QK-Norm.
  3. 1 / \sqrt{2L} = 1 / \sqrt{64} = 1/8 = 0.125, keeping the variance sum of all 2L = 64 residual branches O(1).

Summary: Anatomy and Stability of the Transformer Block

Key Takeaways

  • Token Mixing (4d^2) + Channel Mixing (8d^2): Multi-head attention and SwiGLU FFN (d_{\text{ff}} = \frac{8}{3}d) total 12d^2 parameters per block.
  • Pre-Norm + 1/\sqrt{2L} Output Scaling: Preserves the identity gradient highway while keeping cumulative stream variance O(1) across depth L.
  • RMSNorm & QK-Norm: Fast scale normalization and Cauchy–Schwarz logit bound (\le \sqrt{d_h}).