Unit 2 · Architecture

Lesson 06 · Available to read

Self-Attention and Multi-Head Attention in Depth

The mathematics of attention step by step: queries, keys, values, scaled dot-products, causal masks and multiple heads.

Lesson 5 gave the intuition: every token looks at the others and pulls in what's relevant. Now we open the box. By the end of this lesson you'll be able to compute attention by hand for a tiny example — and you'll understand every symbol in the most famous formula in modern AI:

Attention(Q, K, V) = softmax(QKᵀ / √d) · V

Queries, keys and values

Attention borrows an idea from databases and search. Each token produces three different vectors from its current residual-stream vector x, using three learned weight matrices:

  • Query q = x · W_Q — what am I looking for?
  • Key k = x · W_K — what do I contain? (my label)
  • Value v = x · W_V — what will I hand over if someone attends to me?

A useful analogy is a library: your query is the question you bring, each book's key is its catalogue entry, and the value is the book's actual content. You compare your question to every catalogue entry, then read mostly from the best matches.

Keys and values are separate on purpose: what makes a token relevant (key) isn't necessarily the information it should contribute (value).

Each token's vector is projected into a query, key and value; query·key scores are scaled, softmaxed and used to blend the values.
Each token's vector is projected into a query, key and value; query·key scores are scaled, softmaxed and used to blend the values.

The four steps

For one token attending over the sequence:

  1. Score — dot product of its query with every key: scoreⱼ = q · kⱼ. A large dot product means "this key matches what I'm looking for".
  2. Scale — divide by √d, where d is the key dimension. Without this, dot products of long vectors get very large, softmax becomes nearly one-hot, and gradients vanish.
  3. Normalize — softmax over the scores, giving attention weights that are positive and sum to 1.
  4. Blend — output = Σⱼ weightⱼ × vⱼ, a weighted average of the values.

Doing this for all tokens at once is just matrix multiplication: stack the queries into Q, keys into K and values into V, and the formula above computes every token's output in one go — which is exactly what GPUs are good at.

A worked example

Three tokens, key dimension d = 2. We compute the output for token 3, whose query is q = (1, 0).

  • keys: k₁ = (1, 0), k₂ = (0, 1), k₃ = (1, 1)
  • values: v₁ = (1, 0), v₂ = (0, 1), v₃ = (1, 1)

Step 1 — scores: q·k₁ = 1, q·k₂ = 0, q·k₃ = 1. Step 2 — scale by √2 ≈ 1.414: (0.707, 0, 0.707). Step 3 — softmax: e^0.707 ≈ 2.028, e⁰ = 1, so the sum ≈ 5.056 and the weights ≈ (0.401, 0.198, 0.401). Step 4 — blend: 0.401·(1, 0) + 0.198·(0, 1) + 0.401·(1, 1) ≈ (0.80, 0.60).

Token 3 drew mostly on tokens 1 and 3, whose keys matched its query, and a little on token 2.

The causal mask

A language model must predict the next token without peeking at it. During training, the whole sequence is processed in parallel, so we need to stop each position from attending to positions after it.

The trick: before the softmax, set every score where key position > query position to −∞. Since e^(−∞) = 0, those positions get exactly zero weight. The resulting attention matrix is lower-triangular.

A 6×6 attention matrix for 'The cat sat on the mat': each row sums to 1 and future positions are masked out.
A 6×6 attention matrix for 'The cat sat on the mat': each row sums to 1 and future positions are masked out.

This causal mask is what makes a decoder-only transformer a next-token predictor — and it's why, in Lesson 5's example, "it" couldn't see "tired".

Multi-head attention

One attention operation produces one weighting pattern per token. But a token may need several kinds of information at once: its grammatical subject, the previous word, the entity a pronoun refers to.

Multi-head attention runs h attention operations in parallel, each with its own smaller W_Q, W_K, W_V (dimension d/h). Their outputs are concatenated and mixed by an output matrix W_O.

Multi-head attention runs several attention heads in parallel, concatenates their outputs and mixes them with W_O.
Multi-head attention runs several attention heads in parallel, concatenates their outputs and mixes them with W_O.

With d = 4,096 and 32 heads, each head works in 128 dimensions — the total cost is about the same as one big head, but the model gets 32 different ways to look. Researchers have found heads that track the previous token, copy repeated patterns ("induction heads"), or link pronouns to their referents. No one designs these roles; they are learned.

Cost: the quadratic catch

For a sequence of n tokens, the score matrix QKᵀ is n × n. Doubling the context length quadruples the attention compute and memory. This is the main reason long context windows are hard and expensive — the subject of Lesson 7.

Self-attention vs. cross-attention

Everything above is self-attention: queries, keys and values all come from the same sequence. In encoder–decoder models, cross-attention takes queries from one sequence (the translation being written) and keys/values from another (the source sentence). Multimodal models use the same idea to let text attend to image features.

The takeaway

Attention lets each token ask a question (query), compare it with every earlier token's label (key), and collect a weighted blend of their content (value): softmax(QKᵀ/√d)·V — with a causal mask to hide the future and many heads running in parallel.

Practice

0 of 8 attempted

  1. 1Recall

    State in one phrase each what the query, key and value of a token represent.

    Saved in this browser

  2. 2Calculate

    Using the lesson's keys and values (k₁=(1,0), k₂=(0,1), k₃=(1,1); v₁=(1,0), v₂=(0,1), v₃=(1,1)) and d = 2, compute the attention output for a token whose query is q = (0, 2).

    Saved in this browser

  3. 3Explain in your own words

    Why do we divide the scores by √d before the softmax? What would go wrong without it?

    Saved in this browser

  4. 4Multiple choice

    In a causal attention matrix for a 5-token sequence, how many query–key pairs are allowed (not masked)?

  5. 5Explain in your own words

    Explain how the causal mask is implemented and why setting scores to −∞ (rather than, say, 0) is the right choice.

    Saved in this browser

  6. 6Calculate

    A model has d = 5,120 and 40 attention heads. What is the dimension of each head? If the context length goes from 8,000 to 32,000 tokens, by what factor does the size of each attention score matrix grow?

    Saved in this browser

  7. 7Apply

    Write a short paragraph, as if teaching a friend, explaining multi-head attention using an analogy of your own (not the library one).

    Saved in this browser

  8. 8Recall

    Write the attention formula from memory and label each part.

    Saved in this browser

See what unlocked