Linear algebra for LLMsPart 6: The rest of the transformer

The residual stream

5 min

One transformer block

x←x+Attn⁡(Norm⁡(x))\displaystyle x \leftarrow x + \operatorname{Attn}(\operatorname{Norm}(x))
x←x+MLP⁡(Norm⁡(x))\displaystyle x \leftarrow x + \operatorname{MLP}(\operatorname{Norm}(x))

Each sublayer reads a normalized copy of xx and adds its result back. This “pre-norm” layout is what GPT-2 and Llama use. xx keeps its shape (B,T,d)(B, T, d) through every block.

Write

Block: x+=Attn⁡(Norm⁡(x))x \mathrel{+}= \operatorname{Attn}(\operatorname{Norm}(x)), then x+=MLP⁡(Norm⁡(x))x \mathrel{+}= \operatorname{MLP}(\operatorname{Norm}(x)).

Unrolled, it's one big sum

xfinal=x0+∑ℓ=1L(aℓ+mℓ)\displaystyle x_{\text{final}} = x_0 + \sum_{\ell=1}^{L} \big(a_\ell + m_\ell\big)
+ + =

The final vector is the embedding plus what every attention (aℓa_\ell) and MLP (mℓm_\ell) sublayer wrote. Nothing is overwritten; information is only added. (The numbers are Part 1’s toy example.)

A shared space that everyone reads and writes

In a transformer

Every matrix that reads the stream (WQ,WK,WVW_Q, W_K, W_V, the MLP’s up and gate projections) projects it; every matrix that writes (WOW_O, the MLP’s down projection) maps back into the same dd dimensions. Layers communicate by writing into directions that later layers read: the projections of Part 3. Interpretability work studies the stream exactly this way.

Why add instead of replace

∂ (x+f(x))∂x=I+∂f∂x\displaystyle \frac{\partial\,(x + f(x))}{\partial x} = I + \frac{\partial f}{\partial x}

The identity II gives the gradient a straight path back to every earlier layer, whatever ff does. Without it, gradients would have to pass through every layer’s Jacobian (Part 8) in turn and could shrink or explode over dozens of layers.

Write

∂(x+f(x))/∂x=I+∂f/∂x\partial(x + f(x))/\partial x = I + \partial f/\partial x: a direct gradient path.

✏️ Your turn

Count the writers

A model has 32 blocks, each with one attention and one MLP sublayer. How many vectors are added together in its final residual stream, counting the embedding?

Work it out on paper, then go to the next card to check.

Answer: 65

1+2×32=65\displaystyle 1 + 2 \times 32 = 65

The embedding plus 64 sublayer outputs. A final norm and the unembedding then read the result.

📌 Recap

The residual stream in one card

  • x+=Attn⁡(Norm⁡(x))x \mathrel{+}= \operatorname{Attn}(\operatorname{Norm}(x)); x+=MLP⁡(Norm⁡(x))x \mathrel{+}= \operatorname{MLP}(\operatorname{Norm}(x)).
  • Final xx = embedding + every sublayer’s output.
  • All layers read from and write into the same dd-dimensional space.
  • The identity path keeps gradients flowing.

Write

The four lines above.