Lesson 21 of 23 · Transformer block
Learn an update, then add it to the state.
Your win: calculate both residual additions in a pre-norm block and explain their shape requirement.
The identity route and the learned route meet
A residual sublayer has the pattern \(X+F(X)\), or \(X+F(\operatorname{Norm}(X))\) in a pre-norm block. The sublayer learns a correction \(F\) while the identity route carries \(X\) directly to the addition.
Numbers substituted: one token
Suppose a token's state and attention update are
If the feed-forward update is \(\mathbf f=(-0.1,0.5,0.2)\), then
Scale the learned update while the identity path stays fixed
Addition forces the output width
This is why multi-head attention uses \(W_O\) to return to \(d_{\text{model}}\), and why the feed-forward network projects its expanded hidden width back down before addition.
Code checkpoint · the complete pre-norm block skeleton
The identity path is visible in the repeated x + ... form. Each sublayer receives a normalized view, but its update is added to the unnormalized running state.
Show both residual updates
class TransformerBlock(nn.Module):
def forward(self, x):
x = x + self.attention(self.attn_norm(x))
x = x + self.feed_forward(self.ffn_norm(x))
return xTrace it: Point to the two identity routes and the two learned routes in these three lines.
Retrieval check
What shape must an attention update have before adding it to \(X\in\mathbb R^{B\times T\times d_{\text{model}}}\)?
Practice before moving on
- Add \((2,-1,4)\) and \((-0.5,2,1)\).
- If the learned update is the zero vector, what does a residual sublayer output?
- For \(X\) of shape \(2\times5\times8\), what shape must \(O_{\text{attn}}\) have?
- Why is a raw concatenated head tensor sometimes reshaped before residual addition?
- Write the two residual equations of a pre-norm decoder block.
- Explain the phrase “learn a correction” using \(X+F(X)\).
Check solutions
- \((1.5,1,5)\).
- \(X\), because \(X+0=X\).
- \(2\times5\times8\).
- The head and feature axes must be concatenated to recover model width, followed by \(W_O\) in standard attention.
- \(Y=X+\operatorname{Attn}(\operatorname{Norm}(X))\); \(X^{(\ell+1)}=Y+\operatorname{FFN}(\operatorname{Norm}(Y))\).
- \(F(X)\) specifies the change to add rather than an entirely new replacement state.
Primary sources: He et al., Deep Residual Learning; Xiong et al., pre-norm analysis.