4.1.5 · D3Transformer Architecture

Worked examples — Multi-head attention

2,442 words11 min readBack to topic

This page is the drill floor for Multi-head attention. The parent note told you the machinery; here we run it against every kind of input the machine can meet — small dimensions, single tokens, one head vs. many, degenerate scores, cross-attention shapes, and an exam twist. Nothing is skipped, so you never hit a case you didn't already practise.

Before we start, one tiny reminder of the two ideas we lean on constantly (both come from Query-Key-Value Intuition and Self-Attention):

Recall What the softmax and the score actually mean

A score measures "how much should token listen to token ?" It is a plain number (can be negative). The softmax turns a whole row of scores into positive weights that add up to — like slicing a pie so token decides what fraction of its attention each other token gets.

Every symbol below: = number of tokens (rows), = width of each token's vector, = number of heads, = width of the query/key space inside one head, and = width of the value space inside one head (the length of what each head actually outputs). In the standard transformer , and we use that throughout.


The scenario matrix

The cases below are chosen so that between them they hit every corner of multi-head attention: the tiniest dimensions, the boundary cases where a piece of the formula does nothing, the limiting values of the softmax, and a real-world / exam flavour.

# Cell class What makes it special Example
A Single head, tiny dims , — strip away parallelism to see the core Ex 1
B Two heads, splitting — watch split and re-concatenate Ex 2
C Degenerate scores: all equal softmax outputs uniform weights Ex 3
D Limiting scores: one huge softmax → one-hot (a hard pick) Ex 4
E Zero / negative scores shows scores may be negative, weights never are Ex 5
F Scaling matters compare with vs. without Ex 6
G Real-world word problem pronoun co-reference, one head specialises Ex 7
H Cross-attention shapes query length key length (Cross-Attention) Ex 8
I Exam twist: count parameters "how many learnable numbers?" Ex 9

Example A — Single head, the bare core

  1. Scores . Why this step? The dot product of query with key is how well they align — the raw "listen to " number. Diagonal is (self-match), off-diagonal (orthogonal, no match).

  2. Scale by . Why? Large dot products push softmax into extreme regions where gradients vanish; dividing keeps them tame. Scores become on the diagonal, off it.

  3. Softmax each row. Why? Turn scores into a pie of attention that sums to . Row 1 = : By symmetry row 2 = .

  4. Weighted sum of values. Why? The output of token is the pie-weighted blend of the value rows.

Verify: each output row is a convex mix of and , so both coordinates lie inside ✓. Row 1 leans toward , row 2 toward — exactly the "close to but blurred" forecast ✓.


Example B — Two heads split then re-join

Forecast: with a single token, attention can't gather anything from neighbours, so concatenation just rebuilds a 4-vector; with nothing changes → output .

  1. Single-token softmax. Why? With each row has one score; . Attention is forced to be the identity here — a real degenerate case, so each head just outputs its own value vector.

  2. Read off each head's output. Why? Because attention is the identity, and — exactly the slices the select-matrices picked.

  3. Concatenate heads. Why? We stack the two 2-D outputs side by side to rebuild : .

  4. Apply . Why? mixes heads; the identity is the "do-nothing" mix, useful to isolate the concat step. Output .

Verify: dimension check ✓. Single token means self-attention is an identity, so the value passes through unchanged ✓.


Example C — Degenerate scores: everything equal

Forecast: identical scores mean "no token is preferred" — attention must be uniform ( each), so the output is the plain average .

  1. Softmax of equal scores. Why? When all match, are equal and cancel: . This is the maximum-entropy, "I don't know who matters" case.

  2. Weighted sum. Why? Blend the values: .

Verify: weights sum to () ✓. Output is the arithmetic mean, which is what uniform attention must give ✓.


Example D — Limiting scores: one huge value

Forecast: the third score dwarfs the others, so softmax should collapse to "almost all attention on token 3" → output near .

  1. Softmax. Why? Exponentials magnify gaps. .

  2. Weighted sum. Why? Blend: .

Verify: as the top score , softmax (a hard "pick token 3"), giving exactly . Our number rounds to ✓. This is the hard-attention limit.

The figure below plots exactly this collapse: as the gap between the top score and the others grows, the weight on the dominant token climbs toward . The magenta dot marks Example D's gap of , already glued to the ceiling.

Figure — Multi-head attention

Example E — Zero and negative scores

Forecast: token 2's score is higher, so it wins most attention; despite the negative score, both weights stay positive → output between 100 and 200, nearer 200.

  1. Softmax with a negative score. Why? is small but positive — that's the whole point of the exponential: it maps any real number (even ) to a positive weight.

  2. Weighted sum. Why? Blend: .

Verify: weights positive and sum to ✓. Result , close to as forecast ✓. A negative score just means "listen less," never "listen a negative amount."


Example F — Why the scaling exists

Forecast: unscaled the gap is huge → softmax nearly one-hot on token 1 (very "peaky", gradients die). Scaled, the gap shrinks to → softer, healthier weights.

  1. Unscaled softmax. Why? Show the pathology. . The gap gives .

  2. Scaled softmax. Why? Divide scores by : , gap . .

Verify: scaled leaves real weight () on token 2, so gradients flow to it; unscaled leaves essentially , freezing learning ✓. This is exactly why the parent's formula divides by .


Example G — Real-world: pronoun co-reference

Forecast: "cat" has by far the top score, so this head should place most of "it"'s attention on "cat" — that's the head doing its co-reference job.

  1. Softmax over the 6 scores. Why? Convert this head's opinions into a probability of who "it" refers to.

  2. Interpret. Why? of "it"'s attention lands on "cat" — the head has learned co-reference. Other heads meanwhile handle syntax or position (that's the Self-Attention division of labour the parent describes).

Verify: all six weights sum to ✓; "cat" is the argmax and dominates ✓. This is what Attention Visualization would show as a bright line from "it" → "cat."


Example H — Cross-attention: different lengths

Forecast: scores form a "who-listens-to-whom" grid with one row per query token and one column per key token → . Output has one row per query token → .

  1. Project. Why? Query comes from the decoder, key/value from the encoder: , .

  2. Scores . Why? Each of the 3 query rows dots against each of the 5 key rows → shape . (Not square — that's the hallmark of cross-attention.)

  3. Softmax over the key axis (the 5 columns) → still , each row sums to 1. Why? Each target token distributes its attention over the 5 source tokens.

  4. Times ( times ) . Why? Inner dimension cancels; output length follows the query side.

Verify: shape algebra ✓, and after concat ✓. In self-attention makes this grid square; cross-attention is the general case.


Example I — Exam twist: count the parameters

Forecast: the four big matrices are each effectively , so the total should be about .

  1. Per-head projections. Why? Each has entries. Same for . Across heads: Note , so all heads' together equal one matrix — the "stacked projection" trick.

  2. Output projection . Why? adds weights.

  3. Total. Why? Sum: .

Verify: exactly ✓ — a clean "" rule of thumb you can quote in an exam. (Compare Linear Projections in Neural Networks for where these matrices live.)


Recall

Reveal after guessing:

Equal scores for all tokens produce what attention weights?
Uniform, each — the plain average of the values.
As one score while others stay fixed, softmax approaches what?
A one-hot vector — hard attention onto the single dominant token.
Can a softmax weight ever be negative?
No — for every real , so all weights are strictly positive and sum to .
In cross-attention with 3 query tokens and 5 key tokens, the score matrix shape is?
(rows = queries, columns = keys).
Total learnable weights of one MHA block with (no biases)?
.
Why divide scores by ?
To stop large dot products from making softmax nearly one-hot, which would kill gradients.

See also: Transformer Encoder Layer, Positional Encoding, and the Hinglish walkthrough.