Topic 07 of 62 · Inside the Transformer block
Multi-head attention
MediumWhy run several attention heads side by side instead of one, and what does it cost?
1 · Start with the intuition
One attention head gives each token a single set of weights over the other tokens, so it produces one weighted average. A token often needs more than one relationship at once: in “The animal didn’t cross the street because it was too tired”, the word “it” benefits from both “animal” and “tired”. Multi-head attention runs several smaller attention calculations in parallel. Each head has its own query, key, and value projections, so each can score the sequence differently. Their outputs are placed side by side and passed through one more learned projection to return to the model width.
2 · How the mechanism works
Mechanism step 1 of 4 · no question to answer
Project per head
Each head projects the input into its own smaller query, key, and value vectors of width d_model / h.
Next, we will look at: Attend per head. Move on when this operation makes sense.
Visualizing the behavior
Eight narrow heads in parallel, then one projection (base model)
Derived3 · The governing equation
headᵢ = Attention(X W_Qⁱ, X W_Kⁱ, X W_Vⁱ) MultiHead(X) = Concat(head₁, …, head_h) W_O d_k = d_v = d_model / h
Notation: X holds one row per token. W_Qⁱ and W_Kⁱ have shape d_model × d_k, W_Vⁱ has shape d_model × d_v, and W_O has shape (h · d_v) × d_model. h is the number of heads.
Because each head works in a space of width d_model / h, the total cost stays close to that of a single head working at full width; the paper makes this point directly. In code the heads are not looped over: the projections are computed once at full width and reshaped so every head runs in the same batched matrix operation. What each head ends up attending to is learned from data, not assigned.
4 · Put concrete numbers on it
Worked numbers (from stated assumptions)5 · Common misconception to avoid
Assuming eight heads cost eight times as much as one. Each head is narrower by the same factor, so parameters and compute stay roughly constant.
6 · Self-check & interview synthesis
Explain it in your own words first
Before revealing the reference answer, try answering the opening question aloud in four beats: what it is → how the math works → what trade-off it makes → a concrete number or failure mode.
Follow-up question interviewers often ask next
MediumWhat do grouped-query and multi-query attention change?
Show follow-up reasoning
They keep a separate query projection for every head but share key and value projections across groups of heads (grouped-query) or across all heads (multi-query). That shrinks the keys and values that must be stored during generation.