Skip to content

4.5 The transformer block

ready≈ 13 hoursNeeds: 4.4, 3.4, 3.7Unlocks: 4.6, 5.6, 6.8
  1. 1 Learn
  2. 2 Bridge & derive
  3. 3 Explore (Transformer block walkthrough, RoPE viewer)
  4. 4 Do
  5. 5 Check

The residual stream. A transformer is a stack of identical blocks, each of the form x←x+attn⁡(norm⁡(x))\mathbf{x} \leftarrow \mathbf{x} + \operatorname{attn}(\operatorname{norm}(\mathbf{x})), then x←x+mlp⁡(norm⁡(x))\mathbf{x} \leftarrow \mathbf{x} + \operatorname{mlp}(\operatorname{norm}(\mathbf{x})). Attention moves information between positions; the MLP processes each position on its own. Both only add to the stream, so, as with ResNets in 3.7, gradients have a direct path through every layer. Putting the norm before each sublayer (pre-norm) rather than after the addition, as the original paper did, trains deep stacks without careful warmup (Xiong et al. 2020). UDL §12.4 and the original paper’s figure 1 draw the post-norm order, so expect the readings to differ from the block you build here (UDL §12.4).

Multiple heads. One attention pattern per layer is limiting: a token may need to look at the previous word and at the subject of the sentence at once. Multi-head attention splits the dd query, key and value features into hh groups of d/hd/h, runs attention in each group independently, concatenates the results and mixes them with an output matrix Wo\mathbf{W}_o. The cost and parameter count are the same as for one head of width dd (Vaswani et al. 2017, §3.2.2).

Modern components. Current open models such as LLaMA replace LayerNorm by RMSNorm, which only rescales and skips the mean (Zhang & Sennrich 2019). They replace the ReLU MLP by SwiGLU, where one projection, passed through SiLU, gates another elementwise (Shazeer 2020). And they encode positions by rotating queries and keys instead of adding a position vector to the input (CS336 lecture 3).

Rotary embeddings. Attention alone sees a set (4.4). RoPE splits each query and key into pairs of features and rotates pair ii by the angle mθim\theta_i, where mm is the position and θi=10000−2i/d\theta_i = 10000^{-2i/d}. Rotating both vectors changes their dot product only through the difference of their angles, so the score depends on the relative position n−mn - m and the token contents, never on absolute positions (Su et al. 2021).

RoPE scores depend only on relative positionstep 1 of 5
  1. R(α)=(cos⁡α−sin⁡αsin⁡αcos⁡α),q~m=R(mθ) q,k~n=R(nθ) k\mathbf{R}(\alpha) = \begin{pmatrix}\cos\alpha & -\sin\alpha\\ \sin\alpha & \cos\alpha\end{pmatrix},\qquad \tilde{\mathbf{q}}_m = \mathbf{R}(m\theta)\,\mathbf{q},\quad \tilde{\mathbf{k}}_n = \mathbf{R}(n\theta)\,\mathbf{k}

Transformer block walkthrough

Residual stream, norms, MLP

Static view on small screens. Open this page on a laptop to interact.

token

residual stream in: x T × d = 5 × 8

Each token is a d-dimensional vector. Every sublayer reads from this stream and adds its result back to it.

‖stream‖ for "time": in 2.96 → after attention 4.01 → out 3.98 parameters in this block 656 (any number of heads)

A real pre-norm block (d = 8, d_ff = 16, random weights) run on five tokens. Click the stages in order and watch the selected token's vector; the rows marked in colour are the residual stream, which only ever has things added to it. Changing the number of heads changes how the d columns are grouped, not the number of parameters.

A pre-norm block with d = 8 runs on five tokens. A list of ten stages, from the residual stream in through RMSNorm, Q/K/V, RoPE, per-head attention, the output projection, the residual addition, the second norm, SwiGLU and the final addition, can be clicked in order. For each, a panel names the tensor shape and draws the selected token’s vector as bars; the attention stage also shows each head’s weight matrix as a heatmap. Controls pick the token, the number of heads and new weights. Keyboard: Tab to the token buttons and the stage list; press Enter to select.

RoPE viewer

Sinusoidal encodings and RoPE as rotation

Static view on small screens. Open this page on a laptop to interact.

θ1 = 1.00Δ = 41°θ2 = 0.10Δ = 40°θ3 = 0.01Δ = 4°θ4 = 1e-3Δ = 0°
query at m = 3, key at n = 10, offset n − m = 7 score q·k = 3.6719
score of a vector with itself vs offset (−64 … 64), d = 32
offset 0
sinusoidal absolute encoding (Vaswani et al.): 48 positions × 32 dims

RoPE treats the features as pairs and rotates pair i of every query and key by its position times θᵢ: fast rotation for the first pairs, very slow for the last. Rotations preserve lengths, and the score depends only on the angle between the two vectors in each pair, which is (n − m)·θᵢ: press "Shift both" and the score does not change. The fast pairs resolve nearby offsets and the slow ones distant offsets. The heatmap shows the older alternative, which adds a fixed pattern of sines and cosines of the absolute position to the input; each pair rotates at its own speed down the positions, like RoPE's angles.

Four circles show the four feature pairs of an 8-dimensional query (blue) and key (orange) after RoPE, with sliders for the query and key positions and a button that shifts both by 10. The readout shows the offset and the score q·k. Below, a curve plots the score of a vector with itself against the offset from −64 to 64, and a heatmap shows the sinusoidal absolute position encoding for 48 positions and 32 dimensions. Keyboard: Arrow keys adjust the position sliders; Tab to the shift button.
Multi-head attention, RMSNorm, SwiGLU, RoPE stubs/m4_5_block.py

Loading starter file…

Prefer your own editor? Edit exercises/stubs/m4_5_block.py and run mlc check 4.5. The tests are identical; import the results on the progress page.

Hints · rope 0/3 revealed
Hints · split_heads 0/3 revealed
Hints · block 0/3 revealed

Then check your block against PyTorch (locally; needs pip install torch, CPU is fine):

Terminal window
cd exercises && python projects/block_vs_pytorch.py

It builds the same block from PyTorch’s rms_norm, scaled_dot_product_attention and silu, with RoPE written in the complex-number form of Meta’s LLaMA code. The reference solution agrees to about 10⁻¹⁵.

1. What is the residual stream?
2. Why several heads instead of one?
3. RoPE rotates queries and keys by position. What does the score then depend on?
4. How does RMSNorm differ from LayerNorm?
  • not yet: All tests pass (0/?)
  • not yet: Checkpoint quiz ≥ 80%
Finish the items above first.
Learner log: time spent and points of confusion

Every confusion you note becomes a fix before the module is marked stable. Export it from the progress page and attach it to an issue.