Transformer Block: Putting the Pieces Together
About 30 min
Goal
By the end of this lesson, you can assemble a reusable pre-norm Transformer block and verify the attention, normalization, residual, feed-forward, shape, and causal contracts that make its two updates compose correctly.
You have already met every major part of a Transformer block. Now the task is to connect them without turning the block into a black box.
A pre-norm block can be read as two learned updates to one continuing residual stream:
x1 = x + attention(norm1(x))
out = x1 + mlp(norm2(x1))
The first branch can mix information across token positions. In the decoder-style block used for the Level 5 build, that mixing is causal. The second branch transforms features independently at each position. Both branches must return to the residual-stream shape (B,T,C) before addition.
Step through the two residual updates
Keep both skip paths visible. At each stage, check which tensor is transformed, which tensor travels unchanged, and why the two inputs to + must have the same shape.
x · (B,T,C)Starts both the skip path and the attention branch.xKeep the current stream unchanged.(B,T,C)update · (B,T,C)x1 = x + attention(norm1(x))unchanged x + attention updatex1Keep the updated stream unchanged.(B,T,C)update · (B,T,C)output = x1 + mlp(norm2(x1))unchanged x1 + MLP update(B,T,C)Same interface, after two learned updates.Read the forward pass as two updates
A complete block can look surprisingly short:
def forward(self, x):
x = x + self.attn(self.ln1(x))
x = x + self.ff(self.ln2(x))
return x
Read the first line as:
current stream
→ normalize features
→ compute an attention update
→ add that update back to the unchanged stream
Read the second line the same way, except the learned update comes from the feed-forward network.
That gives a useful division of labor:
attention branch: "which allowed positions should contribute information?"
MLP branch: "how should this position's current features be transformed?"
residual path: "keep a direct route while adding each learned correction"
The feed-forward network may temporarily widen the feature dimension:
self.ff = nn.Sequential(
nn.Linear(n_embd, 4 * n_embd),
nn.GELU(),
nn.Linear(4 * n_embd, n_embd),
)
L5.12 used a smaller C → 2C → C network with ReLU so the position-wise feed-forward idea was easy to inspect. Here the block moves one step closer to common Transformer implementations: the hidden layer temporarily expands to 4C, a historically common design choice rather than a rule, and GELU supplies the nonlinearity. GELU plays the same broad role as ReLU but changes values smoothly instead of clipping every negative value directly to zero.
The final projection back to n_embd is not cosmetic. Residual addition is elementwise, so the branch output and the stream it joins must have the same (B,T,C) shape.
Predict
Trace one token without losing the sequence view
Suppose position 2 enters the block with a feature vector that already carries information from earlier layers.
In the first branch, LayerNorm prepares its features. Attention then builds an update by mixing information from positions that the attention rule allows. In the decoder-style block used here, position 2 may use positions 0, 1, and 2 but not a later position.
The first residual addition produces x1. The second branch starts from x1, normalizes it, applies the same MLP structure independently at every token position, and adds that update back.
The important point is that same shape does not mean same values. Every named boundary can stay (B,T,C) while the representation values change.
It also means a correct final shape proves only that the interfaces fit. It does not prove that:
- future positions were blocked when causality is required;
- LayerNorm used the intended feature axis;
- heads were split and rejoined correctly;
- the attention update used the intended Q/K/V semantics.
When reading or debugging a block, locate the two residual additions first. Then inspect the branch feeding each addition.
Use the Lab as boundary evidence
Open the Lab and run it unchanged.
The first code cell builds a small reusable block and checks three contracts:
- block output has the same shape as block input;
- every output value is finite;
- future attention probability is exactly zero.
The second code cell exposes named boundaries and a backward-pass check. Confirm that the block input, normalized inputs, attention update, residual outputs, and MLP update all return to (2,4,12) where residual addition requires it. It also verifies that gradients are finite and that an invalid head split fails early.
Then make one controlled break: change the final feed-forward projection from n_embd channels to n_embd - 2. Predict which residual addition fails first, run the cell, and restore the original width.
Loading lab…
Do not diagnose “the Transformer block” as one object. Name the first broken boundary: normalization, attention visibility/head shape, residual addition, or MLP width.
Under the Hood
This course uses a pre-norm block for the decoder-style implementation path: normalization happens before attention and before the feed-forward branch. Transformer implementations can place normalization differently. The transferable skill is tracing exactly which tensor each operation receives and returns.
Quick Check
Explain it back
Explain the block as two learned residual updates. For each update, name the unchanged skip path, the transformed branch, the shape that must rejoin, and one semantic invariant that shape checks alone cannot prove.
Check your explanation
A strong answer mentions:
- First residual update: keep the unchanged
(B,T,C)skip stream and add a normalized attention branch returning to(B,T,C). - Second residual update: keep that stream as a skip path and add a normalized MLP branch returning to
(B,T,C). - Shape checks cannot prove causality; the attention branch must not use forbidden future positions.
Key Takeaways
- A pre-norm Transformer block can be read as two learned updates to one residual stream.
- Attention mixes information across allowed positions; the MLP transforms features per position.
- Both branches return to
(B,T,C)before residual addition. - Shape checks and causal checks catch different classes of mistakes.
- Debug the first broken boundary instead of treating the whole block as one opaque object.
Next Lesson
Next, L5.14 — Transformer Families: Encoder, Decoder, and Encoder-Decoder keeps this shared machinery but changes which positions may communicate and what job the architecture performs.
References
- Vaswani et al., Attention Is All You Need.
- PyTorch, LayerNorm.
- PyTorch, MultiheadAttention.
Completion is stored locally on this device.