The previous chapter gave the idea; this one follows the shapes. Tracking dimensions is the difference between understanding multi-head attention as a picture and understanding it well enough to build. There is no new concept here — just careful bookkeeping, and one neat implementation trick.
The dimensions in play
Four numbers describe the data inside an attention layer:
- — the batch size, how many sequences we process at once.
- — the sequence length, the number of tokens.
- — the model dimension, the width of each token's vector.
- — the number of heads, with per-head dimension .
The input to the layer is a block of shape : for each of sequences, tokens, each a -vector.
One projection, then a reshape
Conceptually each head has its own . In practice we do not run separate small multiplications. We apply one big projection of shape to get all the queries at once — output shape — and then reshape that last dimension into :
Nothing is computed differently; we have simply relabelled the numbers as " heads of numbers each." A final transpose puts the heads next to the batch, giving — which reads as " independent little attention problems, each of tokens in dimension ." The same is done for keys and values.
This is the practical heart of multi-head attention: the heads are a reshaped view of a single projection, not separately coded operations. That is why multi-head attention costs about the same as one full-width head and runs just as efficiently on a GPU — it is the same matrix multiplies with one extra axis.
The per-head computation, by shape
With queries, keys and values all shaped , the attention from Module 3 runs on the last two axes, identically for every pair:
- Scores : multiplying by its transpose gives an score grid per head → shape .
- Scale by and add the causal mask (the same lower-triangular mask, broadcast across batch and heads).
- Softmax over the last axis, so each of the rows sums to 1.
- Blend values: multiply the weights by the values → back to .
Every head has done a full scaled, masked attention, all as batched matrix multiplies.
Fanning back in
Now reverse the reshape. Transpose the heads back beside the head-dimension and merge them:
This is the concatenation of the heads — again just a relabelling of axes. Finally apply the output projection (shape ), mixing the heads' contributions, to produce the layer's output at shape — exactly the shape we started with, ready to be added back to the residual stream.
The round trip in one view
The shape you start with is the shape you end with — the layer enriches each token's vector without changing its size, which is exactly what lets you stack these blocks as deep as you like. A count worth carrying: four projections (), each , make up the parameters of a multi-head attention layer.