Attention
Q/K/V, scores, mask, softmax, output. The headline act.
Check yourself ↓ three questions and what to remember, at the end
Attention is computed one query row at a time. Below, one row of the pattern is built exactly as the code builds it: a dot product with every key, a scale, the causal mask, a softmax in three steps, and a weighted sum of the value rows; then it moves on to the next row, and at the end the heads are joined and projected.
Loading the animation…
Concept
Attention is how the decoder looks back at earlier tokens. For every
position i, it asks: "given what I'm computing here, which earlier
positions matter, and how much?"
The trick is that we never compute "look back at position j" by
hand-coding it. Each position broadcasts three vectors:
- a query — what this position is asking about,
- a key — what this position can answer with,
- a value — what this position has to offer.
Then for every pair (query at i, key at j) we compute a similarity
score (dot product). Apply a softmax across the row, and you have a
probability distribution over which positions to read from. Take the
weighted average of their values, and that's the attention output.
To keep the decoder causal — so position i can only see positions
≤ i — we add a "mask" that pushes future scores to −∞ before the
softmax. Future weights end up at zero.
Try it below. The four panels are the actual values from one block of the toy decoder. Hover any query row in the scores or weights matrix to highlight the keys it pays attention to.
Maths
For a single head with head dimension :
where is the causal mask: for and for , so position can never attend to a later token.
Multi-head attention runs of these in parallel on disjoint slices of , concatenates the per-head outputs, and projects through :
Each head can specialise in a different relationship — one might track which token came right before, another which token shares an opening parenthesis, and so on. This toy model, trained on one book, learns simple habits: in block 1 both heads look mostly at the current letter and the one before it, and in block 2 one head sends each space back to the start of the window (the landing page shows all four heads). Switch any widget's weights to random init to see where training started: rows spread almost evenly.
Code
The attention head, in TypeScript, is shorter than its description:
// src/lib/transformer/attention.ts (excerpt)
export function singleHeadAttention(Q, K, V) {
const seqLen = Q.length;
const d_head = Q[0]?.length ?? 0;
const scale = 1 / Math.sqrt(Math.max(1, d_head));
const Kt = transpose(K);
const raw = matmul(Q, Kt);
const scores = raw.map((row) => row.map((v) => v * scale));
const mask = causalMask(seqLen); // -Inf above diagonal
const weights = softmaxRows(scores, mask); // row-wise stable softmax
const output = matmul(weights, V);
return { scores, weights, output };
}
Multi-head simply slices the model dimension into n_heads groups, runs
singleHeadAttention on each, concatenates, and projects through
W_o. The widget above hits /api/compute/attention, which calls the
exact function verify-maths checks against the PyTorch fixtures.
Check yourself
Commit to an answer before you reveal it: a wrong guess you can explain teaches more than a right one you skimmed. Every number in the answers comes from the same tested model as the chapter’s.
Reveal the answer
Answer: 28 (exact)
28: every entry above the diagonal, of them. Row may look at positions 1 to only, so the mask adds to the later scores and the softmax turns them into exact zeros.
Commit to a number, then reveal.
Reveal the answer
Answer: 0.354 (counted right within 5%)
0.354. Dot products of wider vectors are larger, and without the scale the softmax would saturate onto one position and stop passing gradient back (Training, chapter 8 shows that happening).
Commit to a number, then reveal.
Reveal the answer
Answer: 90% (counted right within ± 10%)
90% on average, over 3,839 windows of the book: the head has learnt to read the last two characters, the strongest clue to the next one. Switch the widget to random init and its rows spread almost evenly.
Commit to a number, then reveal.
Comments
Be the first to leave a comment on this section.
Sign in (top-right) to leave a comment.