Transformer Decoder Explained
← /learn

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.

Head:

Maths

For a single head with head dimension dhead=dmodel/nheadsd_{\text{head}} = d_{\text{model}} / n_{\text{heads}}:

Q=XWq,K=XWk,V=XWv[S,dhead]scores=QK⊤dhead[S,S]weights=softmax⁡(scores+M)each row sums to 1output=weights⋅V[S,dhead]\begin{aligned} Q &= X W_q, \quad K = X W_k, \quad V = X W_v && [S, d_{\text{head}}] \\ \text{scores} &= \frac{Q K^{\top}}{\sqrt{d_{\text{head}}}} && [S, S] \\ \text{weights} &= \operatorname{softmax}(\text{scores} + M) && \text{each row sums to } 1 \\ \text{output} &= \text{weights} \cdot V && [S, d_{\text{head}}] \end{aligned}

where MM is the causal mask: Mij=0M_{ij} = 0 for j≤ij \le i and −∞-\infty for j>ij \gt i, so position ii can never attend to a later token.

Multi-head attention runs HH of these in parallel on disjoint slices of dmodeld_{\text{model}}, concatenates the per-head outputs, and projects through WoW_o:

headh=Attention⁡ ⁣(XWq(h), XWk(h), XWv(h))output=[head0 ∥ head1 ∥ ⋯ ∥ headH−1]Wo[S,dmodel]\begin{aligned} \text{head}_h &= \operatorname{Attention}\!\left(X W_q^{(h)},\, X W_k^{(h)},\, X W_v^{(h)}\right) \\ \text{output} &= \left[\text{head}_0 \,\|\, \text{head}_1 \,\|\, \cdots \,\|\, \text{head}_{H-1}\right] W_o && [S, d_{\text{model}}] \end{aligned}

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.

Q1An 8-character window: in one head’s 8 × 8 attention pattern, how many weights does the causal mask force to exactly zero?
Reveal the answer

Answer: 28 (exact)

28: every entry above the diagonal, S(S−1)/2S(S-1)/2 of them. Row ii may look at positions 1 to ii only, so the mask adds −∞-\infty to the later scores and the softmax turns them into exact zeros.

The causal mask →

Commit to a number, then reveal.

Q2Each head here is 8 numbers wide. What does the code multiply every score by before the softmax?
Reveal the answer

Answer: 0.354 (counted right within 5%)

1/dk=1/8≈1/\sqrt{d_k} = 1/\sqrt{8} \approx 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).

Scaled dot-product attention →

Commit to a number, then reveal.

Q3With the trained weights, block 1’s second head: what share of each row’s attention lands on the current character and the one before it?
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.

What the trained heads do →

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.