11.1 The Transformer Block
Self-attention (Chapter 10) mixes information across sequence positions: each token's output is a weighted average of value vectors from the positions it attends to. On its own, however, an attention layer applies only linear projections () around the weighted sum. Without a position-wise nonlinearity, residual connections, and normalization, stacking attention layers cannot build hierarchical per-token features or propagate signals reliably across dozens of layers.
The Transformer block (Vaswani et al., 2017) pairs multi-head attention with a position-wise feed-forward network (FFN), wraps each sublayer in an additive residual connection (He et al., 2016), and stabilizes activations with layer normalization (Figure 11.1.1). Three design upgrades separate modern blocks from the original 2017 Transformer:
- Normalization placement: Moving normalization from the residual stream itself post-norm to the input of each sublayer pre-norm preserves an unattenuated identity path across depth.
- Normalization form: Replacing mean-centered
LayerNormwith root-mean-square normalizationRMSNormand optional per-head query--key normalization (QK-Norm) bounds activations and attention logits with less memory-bandwidth overhead. - Gated feed-forward networks: Replacing the two-matrix ReLU/GELU MLP () with a gated
SwiGLUnetwork () improves representation quality at the exact same parameter and FLOP budget.
11.1.1 Components of a Transformer Block#
A Transformer block operates on a shared residual stream (Section 10.7). Rather than overwriting , two consecutive sublayers read from the stream, compute an update, and add their result back:
- Multi-head attention (token mixing) is the only place where sequence positions interact: each token queries the sequence (Section 10.3) and adds the retrieved context vector to its stream.
- Position-wise feed-forward network (channel mixing) applies the same MLP independently to each token vector , transforming the features accumulated by attention. Roughly two-thirds of a dense block's parameters reside in the FFN.
In the pre-norm arrangement used by modern Transformers (Figure 11.1.1), each sublayer normalizes its own input before computing its update:
The transformer block: attention and a position-wise FFN read from the residual stream and add their results back. Left, the 2017 arrangement: normalization sits on the stream itself, after each addition. Right, the modern arrangement: normalization moves onto each branch, and the stream runs uninterrupted from input to output.
11.1.2 Normalization#
11.1.2.1 Pre-Norm vs. Post-Norm#
The original 2017 Transformer (Vaswani et al., 2017) and BERT (Devlin et al., 2018) used post-norm, placing normalization on the residual stream itself after each addition:
Why did modern architectures switch from (11.1.2) to (11.1.1)? We can see the difference directly at initialization without training a single step, using a minimal block MiniBlock whose flag pre_norm switches between the two arrangements:
class MiniBlock(nn.Module):
"""Attention + MLP on a residual stream; norm placement as a flag."""
def __init__(self, num_hiddens, pre_norm):
super().__init__()
self.pre_norm = pre_norm
self.attention = d2l.MultiHeadAttention(num_hiddens, 4)
self.W_1 = nn.Linear(num_hiddens, 4 * num_hiddens)
self.W_2 = nn.Linear(4 * num_hiddens, num_hiddens)
self.norm1 = nn.LayerNorm(num_hiddens, eps=1e-5)
self.norm2 = nn.LayerNorm(num_hiddens, eps=1e-5)
def ffn(self, X): # exact GELU
return self.W_2(F.gelu(self.W_1(X)))
def forward(self, X):
if self.pre_norm:
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))
return self.norm2(X + self.ffn(X))11.1.2.2 Signal Propagation and Token Collapse at Initialization#
Consider passing a batch of random unit-variance token vectors through freshly initialized blocks. The function signal_stats below draws every weight matrix of the stack afresh, with Xavier initialization as in the 2017 Transformer, or with entries if std is given. At each block , we track three quantities:
- Stream standard deviation across all entries of ;
- Token spread, measured as the standard deviation across the sequence positions (which vanishes if all tokens collapse onto the same vector); and
- Query gradient norm flowing back from a unit scalar loss at the top of the stack:
def signal_stats(pre_norm, std=None, num_blks=32, num_hiddens=256):
"""Token spread, stream RMS, and gradient norms of a fresh stack whose
weight matrices are Xavier, or N(0, std^2) if std is given."""
blks = nn.ModuleList([MiniBlock(num_hiddens, pre_norm)
for _ in range(num_blks)])
init = (nn.init.xavier_uniform_ if std is None # the 2017 initialization
else lambda W: nn.init.normal_(W, std=std))
for p in blks.parameters():
if p.ndim == 2:
init(p)
norm = torch.linalg.vector_norm
H = torch.randn(2, 64, num_hiddens)
spread, rms = [], []
for blk in blks:
H = blk(H)
spread.append(norm(H - H.mean(1, keepdim=True)) / norm(H))
rms.append(H.pow(2).mean().sqrt())
(H * torch.randn_like(H)).mean().backward() # generic readout loss
grad_q = [norm(blk.attention.W_q.weight.grad) for blk in blks]
proj = {n: norm(getattr(blks[-1].attention, n).weight.grad).item()
for n in ('W_q', 'W_k', 'W_v', 'W_o')}
return {'spread': torch.stack(spread).tolist(),
'rms': torch.stack(rms).tolist(),
'grad_q': torch.stack(grad_q).tolist(), 'proj': proj}Why does post-norm lose token diversity across depth? Split each token into the part that all tokens share and the part that is its own, , where is the mean over the positions (Figure 11.1.2). At initialization the attention weights are close to uniform, so every token receives nearly the same update : the deviations average out and only the mean is passed on. Each of the two projections multiplies the squared length of its input by , where is the variance of a weight entry, and the random vector is nearly orthogonal to . The energy of the shared part therefore grows by the factor , while the deviations stay as they were. The normalization that follows cannot repair this. It rescales every token by the same factor, which restores the length of the stream but not the balance between the mean and the deviations.
Token collapse in one post-norm block. Each token splits into the shared mean and its own deviation . Nearly uniform attention adds the same update to every token, so only the mean grows. The normalization that follows rescales all tokens by one factor, which shrinks the deviations. Drawn for Xavier initialization (), where is as long as and the factor is .
Let be the ratio of shared to token-specific energy. Each block multiplies by . The token spread, the fraction of the stream's norm that lies in the deviations, is , and independent random tokens start at . After blocks we thus expect
Once the mean dominates, the spread shrinks by the factor per block, which is under Xavier initialization (). Note that the FFN does not appear in (11.1.3). It acts on each token separately and cannot tell the mean from the deviations, so it changes their ratio very little (Exercise 5).
Under pre-norm ((11.1.1)), the residual stream is never divided by a normalization denominator: unrolling blocks gives a direct sum . Because independent sublayer outputs add variance to the stream, the unscaled pre-norm stream RMS grows with depth as (to keep the total variance deposited by all sublayers at any depth , GPT-2 (Radford et al., 2019) scales the initialization standard deviation of each block's residual output projections W_o and W_2 by , as we implement in Section 11.2 and test in Exercise 4). Meanwhile, in post-norm, BERT (Devlin et al., 2018) slows down the collapse (11.1.3) by initializing all linear weights with a smaller standard deviation (so and at ). Let us compare these three configurations (post-norm, pre-norm, and post-norm, std 0.02) across 32 blocks:
arms = {'post-norm': (False, None), 'pre-norm': (True, None),
'post-norm, std 0.02': (False, 0.02)}
stats, predicted = {}, {}
at = lambda xs, ks=(8, 16, 32): ' '.join(f'{xs[k - 1]:.1e}' for k in ks)
for name, (pre_norm, std) in arms.items():
stats[name] = s = signal_stats(pre_norm, std)
print(f'{name}: stream RMS at k=32 {s["rms"][-1]:.2f}')
print(f' token spread at k=8,16,32: {at(s["spread"])}')
if not pre_norm: # rho_0 = 1/63 for 64 random tokens; Xavier: g = 1
g2 = 1 if std is None else 256 * std ** 2
predicted[name] = [(1 + (1 + g2 ** 2) ** k / 63) ** -0.5
for k in range(1, 33)]
print(f' predicted: {at(predicted[name])}')
print(f' W_q grad norm at k=1,8,16,32: {at(s["grad_q"], (1, 8, 16, 32))}')
print(' grad norms at k=32: ' + ' '.join(
f'{n} {g:.1e}' for n, g in s['proj'].items()))post-norm: stream RMS at k=32 1.00
token spread at k=8,16,32: 3.1e-01 2.5e-02 1.2e-04
predicted: 4.4e-01 3.1e-02 1.2e-04
W_q grad norm at k=1,8,16,32: 1.3e-02 2.3e-03 1.8e-05 4.1e-09
grad norms at k=32: W_q 4.1e-09 W_k 4.1e-09 W_v 6.4e-02 W_o 5.9e-02
pre-norm: stream RMS at k=32 5.12
token spread at k=8,16,32: 6.8e-01 5.2e-01 3.8e-01
W_q grad norm at k=1,8,16,32: 6.2e-02 2.0e-02 7.9e-03 2.3e-03
grad norms at k=32: W_q 2.3e-03 W_k 2.3e-03 W_v 8.1e-02 W_o 8.4e-02
post-norm, std 0.02: stream RMS at k=32 1.00
token spread at k=8,16,32: 9.9e-01 9.8e-01 9.7e-01
predicted: 9.9e-01 9.9e-01 9.9e-01
W_q grad norm at k=1,8,16,32: 4.1e-04 4.0e-04 4.0e-04 4.0e-04
grad norms at k=32: W_q 4.0e-04 W_k 4.1e-04 W_v 6.9e-03 W_o 7.1e-03
We plot the measured token spread across blocks next to the prediction (11.1.3) for the two post-norm arms (dotted, with ):
d2l.plot(list(range(1, 33)), [s['spread'] for s in stats.values()]
+ list(predicted.values()), 'block index k', 'token spread',
legend=list(arms) + ['predicted'], yscale='log', ylim=(1e-6, 2),
fmts=('C0-', 'C1-', 'C2-', 'k:', 'k:'), figsize=(4.5, 3.3),
legend_loc='lower left')Under standard Xavier post-norm (post-norm), token spread collapses to nearly zero () by block 32, closely tracking the prediction (11.1.3): all tokens in the sequence have been squeezed into nearly identical vectors. The measured curve runs slightly below the dotted one, which is the small contribution of the FFN. Shrinking the post-norm initialization (post-norm, std 0.02) slows the per-block contraction enough to preserve token spread across 32 blocks. Pre-norm (pre-norm) is not immune, since its attention sublayers also add to the shared mean. But its stream grows with depth, so each update weighs less than the one before, and the spread decays slowly: more than a third of it is left after 32 blocks, even at Xavier scale (the stream RMS meanwhile grows as unless paired with output-projection scaling; Exercise 4).
11.1.2.3 Gradients at Initialization#
Token collapse is a property of the forward pass, but it also decides which weights can learn. We plot the gradient norm of the query projection across block index :
d2l.plot(list(range(1, 33)), [s['grad_q'] for s in stats.values()],
'block index k', 'query projection gradient norm',
legend=list(arms), yscale='log', ylim=(1e-12, 1),
fmts=('C0-', 'C1-', 'C2-'), figsize=(4.5, 3.3),
legend_loc='lower left')In post-norm, the query gradient is largest at block 1, around , and falls to about at block 32. This is the reverse of the vanishing gradients of a deep MLP, where the layers farthest from the loss receive the least. The gradient is not lost on the way back. It is lost because of what the deep blocks see on the way forward: once the tokens entering a block nearly coincide, every key receives the same score and every value is the same, so moving a query changes nothing in the output. The query gradient accordingly shrinks with the square of the token spread, one factor because the scores differ only through the deviations and a second because the values do, and the key gradient shrinks with it. The other weights are not affected. At block 32 the gradients of W_v and W_o have the same order of magnitude in post-norm and pre-norm (the last line printed for each arm above).
In pre-norm, the identity term in carries the gradient from the loss to every block. Its query gradient is not uniform either: it declines by a factor of about 30 over the stack, as the token spread slowly decays. But it stays above where post-norm loses more than six orders of magnitude. Xiong et al. (2020) analyze a different imbalance of post-norm Transformers at initialization, namely large gradients for the parameters near the output, and show that this is why post-norm training depends on a learning-rate warmup while pre-norm trains without one.
11.1.2.4 RMSNorm#
Standard LayerNorm (Section 7.3) centers each token vector by its mean , scales by its standard deviation, and applies learned gain and bias . Zhang and Sennrich (2019) showed that mean-centering and the additive bias contribute little to training stability: what matters is normalizing the root-mean-square magnitude. Dropping and yields RMSNorm:
where is initialized to ones and . Because RMSNorm computes only a single mean-of-squares reduction per token instead of both mean and variance, it performs fewer memory reductions while matching LayerNorm accuracy:
def rms_norm(X, weight=1, eps=1e-5):
return X / torch.sqrt((X * X).mean(-1, keepdim=True) + eps) * weight
x = torch.tensor([1.0, 2.0, 3.0, 6.0])
rmsnorm, layernorm = nn.RMSNorm(4, eps=1e-5), nn.LayerNorm(4, eps=1e-5)
show = lambda v: ' '.join(f'{a:5.2f}' for a in v.tolist())
print(f'ours vs. nn.RMSNorm: max deviation '
f'{(rms_norm(x) - rmsnorm(x)).abs().max():.1e}')
for name, v in (('x', x), ('3x', 3 * x), ('x + 10', x + 10)):
print(f'{name:>6}: RMSNorm {show(rms_norm(v))} | '
f'LayerNorm {show(layernorm(v))}')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
11.1.2.5 Query--Key Normalization (QK-Norm)#
Pre-norm normalizes the input entering the attention sublayer, but inside attention the queries and keys are multiplied by learned projection matrices . If the singular values of and grow during training, the scaled dot-product logits grow quadratically with weight scale, pushing softmax into one-hot saturation where its gradients vanish (Henry et al., 2020; Dehghani et al., 2023).
QK-Norm applies per-head RMSNorm of width to and immediately before computing attention scores. By Cauchy--Schwarz, two vectors of unit RMS have dot product bounded by , so the scaled logit is bounded in magnitude by (and has unit variance for random directions) regardless of how large and grow:
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}')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
When and are scaled by and without QK-Norm, the logit standard deviation jumps quadratically ( and ) and softmax entropy collapses toward zero; with rms_norm applied to and , logit spread and attention entropy remain completely invariant to the weight scale.
11.1.3 The Feed-Forward Network: From GELU to SwiGLU#
The original Transformer feed-forward network is a two-layer MLP that expands channel width from to , applies an elementwise activation ( in Vaswani et al. (2017), in GPT-2 and BERT), and projects back to :
using weight parameters.
Following Dauphin et al. (2017) and Shazeer (2020), modern Transformers replace (11.1.5) with a bias-free SwiGLU gated linear unit, which takes the elementwise product of a -activated gate projection () and a linear up-projection before projecting back down to with :
Because SwiGLU uses three matrices of shape () and (), setting gives , matching both the parameter count and the FLOP count of the GELU MLP:
class FeedForward(nn.Module):
"""Position-wise FFN: GELU MLP or SwiGLU at matched parameter count."""
def __init__(self, num_hiddens, act='swiglu', bias=False):
super().__init__()
assert act in ('swiglu', 'gelu'), f'unknown act: {act!r}'
self.act = act
if act == 'gelu':
width = 4 * num_hiddens
else: # 'swiglu': three matrices; width 8d/3 matches the MLP budget
width = round(8 * num_hiddens / 3)
self.W_g = nn.Linear(num_hiddens, width, bias=bias)
self.W_1 = nn.Linear(num_hiddens, width, bias=bias)
self.W_2 = nn.Linear(width, num_hiddens, bias=bias)
def forward(self, X):
if self.act == 'gelu': # The tanh approximation, as in GPT-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))11.1.4 A Configurable TransformerBlock#
We now assemble TransformerBlock combining pre-norm or post-norm placement (pre_norm), RMSNorm or LayerNorm (norm), SwiGLU or GELU FFN (act), bias toggle (bias), and pluggable attn_factory and ffn_factory hooks (which allow upcoming sections to drop in causal RoPE attention in Section 11.2 or Mixture-of-Experts layers in Section 11.7 without rewriting the block):
class TransformerBlock(nn.Module):
"""Configurable transformer block: attention + FFN on a residual
stream."""
def __init__(self, num_hiddens, num_heads, *, dropout=0, norm='rms',
act='swiglu', pre_norm=True, bias=False, attn_factory=None,
ffn_factory=None):
super().__init__()
assert norm in ('rms', 'layer'), f'unknown norm: {norm!r}'
assert num_hiddens % num_heads == 0
self.pre_norm = pre_norm
make_norm = nn.RMSNorm if norm == 'rms' else nn.LayerNorm
self.norm1 = make_norm(num_hiddens, eps=1e-5)
self.norm2 = make_norm(num_hiddens, eps=1e-5)
self.attention = (d2l.MultiHeadAttention(num_hiddens, num_heads,
dropout, bias=bias)
if attn_factory is None else attn_factory())
self.ffn = (FeedForward(num_hiddens, act, bias=bias)
if ffn_factory is None else ffn_factory())
self.dropout = nn.Dropout(dropout)
def forward(self, X, mask=None, **attn_args):
# attn_args go on to the attention, e.g. the RoPE tables of d2l.GPT
if self.pre_norm:
Y = self.norm1(X)
X = X + self.dropout(self.attention(Y, Y, Y, mask, **attn_args))
return X + self.dropout(self.ffn(self.norm2(X)))
X = self.norm1(X + self.dropout(self.attention(X, X, X, mask,
**attn_args)))
return self.norm2(X + self.dropout(self.ffn(X)))11.1.4.1 Parameter Count#
Comparing the default modern block (RMSNorm, SwiGLU, bias=False) against the 2017/GPT-2 variants (GELU, LayerNorm, bias=True) at confirms that every configuration holds parameters ( in attention and in the FFN):
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
11.1.5 Summary#
A Transformer block separates token mixing (multi-head attention across sequence positions) from channel mixing (a position-wise feed-forward network across the features), adding both updates to a shared residual stream. Pre-norm ((11.1.1)) normalizes only the input to each sublayer and leaves the residual stream an uninterrupted identity path, whereas post-norm ((11.1.2)) normalizes the stream itself; at Xavier scale a deep post-norm stack loses inter-token differences exponentially fast ((11.1.3)) and starves the query and key gradients of its upper blocks, whereas scaling each block's residual output projections (W_o and W_2) by keeps pre-norm stream variance across arbitrary depth . Modern blocks pair RMSNorm ((11.1.4)), which drops LayerNorm's mean subtraction and additive bias, with per-head QK-Norm to bound attention logits via Cauchy--Schwarz regardless of projection weight growth. Finally, SwiGLU ((11.1.6)) replaces the two-matrix feed-forward network with a three-matrix gated product at width , matching the parameter and FLOP budget of a standard FFN.
11.1.6 Exercises#
-
Scale invariance of RMSNorm and its Jacobian. Let act as in (11.1.4) with and .
- Show that for every scalar .
- Differentiate to show that the Jacobian is , and verify that . Why must any radial perturbation parallel to lie in the null space of ?
-
Unrolled residual stream and gradient identity path. Number the sublayers of an -block pre-norm stack as , where odd indices are attention sublayers and even indices are FFN sublayers.
- Unroll (11.1.1) to express explicitly as .
- Apply the chain rule to write as a product of Jacobians, expand the leading terms, and contrast the resulting identity term with the post-norm product where every factor is premultiplied by .
-
QK-Norm inside
TransformerBlock. Write anattn_factorythat wrapsd2l.MultiHeadAttentionand applies an RMSNorm of widthd // hto queries and keys per head before computing attention scores. Verify on a 16-block stack with projection weights multiplied by (or ) that attention entropy remains bounded away from zero. -
Stream variance budget across depth. In the pre-norm arrangement, every sublayer adds an update to the residual stream. Modify
signal_statsso thatW_oandW_2are drawn with std and all other matrices with std , and compare against all matrices at std for . Verify that the final stream RMS grows with without the scaling but stays near a constant under the rule. -
Rate of token collapse. The prediction (11.1.3) has no factor for the FFN, on the argument that only the attention sublayer mixes across tokens while the FFN acts position-wise.
- Modify
MiniBlockso that the attention sublayer is skipped () and only the post-norm FFN runs, and re-runsignal_stats(pre_norm=False)(remove its gradient lines, since no attention weight is used any more). How much token spread is left after 32 blocks? - Now skip the FFN and keep the attention sublayer. How close does the measured spread come to (11.1.3) at ?
- The FFN-only stack does contract a little. Which property of GELU lets a position-wise network add a small vector that all tokens share?
- Modify