Skip to main content

Attention exercises

Extended practice, worked solutions, and transfer

← Back to the exercise catalogue

Attention

Preparation: the Q/K/V exercises use Q/K/V projections, matrix shapes, and NumPy; tensors is an optional shape reference. Score, softmax, and aggregation exercises rely on scaled dot-product attention; the attention-score scaling lesson develops the variance derivation used in AT-D. The Q/K/V and AT-A–AT-C exercises do not require prior study of causal masking; CA-A introduces and works through that invariant itself.

Q/K/V competencies assessed: recognizing the roles, reconstructing projections, explaining how they are learned, predicting parameter-change effects, and transferring the reasoning to cross-attention. The existing weighted-sum task remains the aggregation calculation.

Current scope: CA-A (causal masking, shifted targets and prefix invariance) is owned by the dedicated Causal masking practice page. This collection focuses on the Q/K/V and attention exercises: three progressive formative activities with stable IDs AT-A, AT-B and AT-C shared with the French version cover multi-head attention calculation, shape tracing, then claim diagnosis and intervention prediction. AT-D derives raw-score variance under explicit independence assumptions and explains the role of 1/√dₖ; AT-E is an optional extension that calculates gradients through one attention row, independent of the multi-head sequence. Multi-head-specific masking variants and advanced invariants remain to be developed. Suggested order: CA-A first, then AT-A, AT-B and AT-C.

Exercise — from Q/K scores to the attention output

Consider one query and two key/value pairs:

\[ q=(1,0),\quad k_1=(1,0),\quad k_2=(0,1),\quad v_1=(10,0),\quad v_2=(0,20). \]

  1. Compute the scores \(qk_1^\top\) and \(qk_2^\top\).
  2. Apply scaling with \(d_k=2\).
  3. Compute the softmax weights (approximately).
  4. Compute the weighted combination of the values.
  5. Explain why the weights are not an absolute measure of semantic relevance.

Review how to compute the scores, weights, and output.

Show the worked solution

The raw scores are \((1,0)\). After division by \(\sqrt{2}\), they are approximately \((0.707,0)\). Softmax gives approximately \((0.67,0.33)\). The output is therefore \(0.67(10,0)+0.33(0,20)\approx(6.7,6.6)\).

Q and K determine the weights; V determines the aggregated content. The weights are relative to the accessible keys in this row, not a universal measure of relevance or causality.

Calculate an aggregation by hand

A position receives attention weights \((0.75,\,0.25)\) and the value vectors are \(v_1=(2,0)\) and \(v_2=(0,4)\). Calculate the output. If you swap \(v_1\) and \(v_2\) while keeping the weights fixed, does the output stay the same?

Show the reasoning

The output is the weighted sum: \(0.75(2,0)+0.25(0,4)=(1.5,1)\). After swapping the values it becomes \(0.75(0,4)+0.25(2,0)=(0.5,3)\). Weights determine the relative contribution of positions; values determine the aggregated content. Weights alone therefore do not determine the output.

Exercise — distinguish a weighted mixture from selection

This exercise has moved to the dedicated scaled dot-product attention practice page, so the lesson’s comprehension questions and applications stay together.

Exercise — project a sequence into Q, K, and V

Consider three positions, each represented by a 4-dimensional vector. The matrices W_Q and W_K project to dimension 2, while W_V projects to dimension 3.

  1. Before running the code, infer the shapes of Q, K, and V.
  2. Run the calculation and check the resulting shapes.
  3. Explain why changing W_V does not change scores computed from Q and K.
Show the NumPy calculation and expected result
import numpy as np

# Three input positions, each represented by a 4-dimensional vector
X = np.array([
    [1.0, 0.5, 0.2, 0.1],
    [0.1, 0.9, 0.8, 0.3],
    [0.4, 0.2, 0.7, 0.9],
])
T, d_model = X.shape

# Learned projections: keys/queries have dimension 2; values dimension 3
W_Q = np.array([[0.5, 0.1], [0.2, 0.8], [0.1, 0.3], [0.9, 0.4]])
W_K = np.array([[0.2, 0.7], [0.4, 0.1], [0.6, 0.5], [0.3, 0.2]])
W_V = np.array([[1.0, 0.0, 0.2], [0.0, 1.0, 0.5], [0.5, 0.2, 0.0], [0.1, 0.8, 0.4]])

# Each projection transforms all positions independently
Q = X @ W_Q
K = X @ W_K
V = X @ W_V

assert Q.shape == (T, 2)
assert K.shape == (T, 2)
assert V.shape == (T, 3)
print("Q:", Q.shape, "K:", K.shape, "V:", V.shape)

Expected output: Q=(3, 2), K=(3, 2), V=(3, 3). The projections act independently on each position; the three matrices share the same number of rows here, but need not share the same number of columns.

Changing W_V can change V and the resulting aggregated output, but it does not change the scores or weights, which depend on Q and K.

Exercise — calculate Q, K, and V, then isolate the effect of V

Consider one input representation, using the row-vector convention:

\[ x_t=\begin{bmatrix}1&2\end{bmatrix},\qquad W_Q=\begin{bmatrix}1&0\\0&1\end{bmatrix},\qquad W_K=\begin{bmatrix}0&1\\1&0\end{bmatrix},\qquad W_V=\begin{bmatrix}1&1\\0&1\end{bmatrix}. \]

  1. Calculate \(q_t=x_tW_Q\), \(k_t=x_tW_K\), and \(v_t=x_tW_V\) by hand.
  2. Replace only \(W_V\) with \(W'_V=\begin{bmatrix}2&0\\0&1\end{bmatrix}\). Calculate \(v'_t\).
  3. Which of Q, K, V, the scores, and the weights can change? Justify your answer from the mechanism’s dependencies.
  4. Explain why the aggregated output may change even when the weights stay the same.

Review the projection formulas and the shapes of Q, K, and V.

Show the worked solution

The matrix products are:

\[ q_t=x_tW_Q=\begin{bmatrix}1&2\end{bmatrix},\qquad k_t=x_tW_K=\begin{bmatrix}2&1\end{bmatrix},\qquad v_t=x_tW_V=\begin{bmatrix}1&3\end{bmatrix}. \]

With the new value projection:

\[ v'_t=x_tW'_V=\begin{bmatrix}2&2\end{bmatrix}. \]

Only V changes directly. Q and K remain identical, so the scores and weights computed from Q and K remain identical too. However, the weighted sum operates on the V vectors: changing those vectors may therefore change the aggregated content. This does not mean the output must change in every case, since some variations may cancel.

The matrices are deliberately small and fictional so that the multiplications can be checked by hand; they are not parameters from a trained model.

Exercise — predict the effect of changing a projection

Consider the same input \(X\) and standard attention, without biases. For each intervention, state whether \(Q\), \(K\), \(V\), the scores, the weights, and the aggregated output can change. Keep all other parameters fixed.

Intervention Quantities that may change Invariants
Change \(W_Q\) only
Change \(W_K\) only
Change \(W_V\) only

Justify each row from the functional dependencies.

Show the reasoned solution
  • \(W_Q\) only: Q may change; scores computed from Q and K may therefore change, followed by the weights and output. K and V remain invariant.
  • \(W_K\) only: K may change; scores, weights, and output may therefore change. Q and V remain invariant.
  • \(W_V\) only: V and generally the aggregated output may change. Q, K, scores, and weights remain invariant.

“May change” does not mean “must change”: a particular perturbation can be cancelled by the data or aggregation weights. The output depends on both weights and values.

Focused preparation: this question uses the attention gradient paths. First consult the Q/K/V deep dive, “Gradient paths through attention”. The other projection exercises do not require this derivation.

Exercise — connect the projections to learning

In the standard mechanism, \(W_Q\), \(W_K\), and \(W_V\) are trained from the model’s final loss. Answer without assuming that separate Q, K, or V targets are provided.

  1. Why is projection learning indirect?
  2. Through which operations does the gradient associated with Q and K propagate?
  3. Through which operation does the gradient associated with V propagate?
  4. For \(Q=XW_Q\) with fixed \(X\) and no bias, what is the form of \(\partial\mathcal L/\partial W_Q\)? Give the corresponding expressions for K and V.
Show the reasoned solution

The projections have no independent targets: they are adjusted to reduce the model’s prediction loss. The gradient to Q and K passes through compatibility-score computation and normalization; the gradient to V passes through weighted aggregation. For a linear projection \(Q=XW_Q\), the chain rule gives:

\[ \frac{\partial\mathcal L}{\partial W_Q} =X^\top\frac{\partial\mathcal L}{\partial Q}. \]

Likewise, \(\partial\mathcal L/\partial W_K=X^\top(\partial\mathcal L/\partial K)\) and \(\partial\mathcal L/\partial W_V=X^\top(\partial\mathcal L/\partial V)\). These are local linear-layer gradients; the gradients of Q, K, and V come from the complete attention and network computation.

Exercise AT-E — Backpropagate through one attention row

Consider one query, two keys, and two scalar values, with no mask:

\[ q=1,\qquad k_1=\ln 3,\quad k_2=0,\qquad v_1=2,\quad v_2=4,\quad d_k=1. \]

The output is \(O=AV\), and the toy objective is \(\mathcal L=O\). This is a scalar upstream signal chosen to study local backpropagation, not a language-model loss.

  1. Compute the scores, weights \(A\), and output \(O\).
  2. Using \(G_O=\partial\mathcal L/\partial O=1\), compute \(G_V=\partial\mathcal L/\partial V\) and \(G_A=\partial\mathcal L/\partial A\).
  3. Apply the row-wise softmax formula to obtain \(G_S=\partial\mathcal L/\partial S\).
  4. Backpropagate through \(S=qK^\top/\sqrt{d_k}\) to compute \(\partial\mathcal L/\partial q\) and the two components of \(\partial\mathcal L/\partial K\).
  5. Check that the components of \(G_S\) sum to zero. Why is this consistent with softmax invariance to a common score shift?
Show the worked solution
  1. The scores are \((\ln3,0)\). Their softmax is \(A=(3/4,1/4)\), so \(O=(3/4)2+(1/4)4=5/2\).
  2. From \(O=AV\), we obtain \(G_V=A^\top G_O=(3/4,1/4)\) and \(G_A=G_OV^\top=(2,4)\).
  3. The weighted mean of the components of \(G_A\) is \((3/4)2+(1/4)4=5/2\). Therefore, \[ G_S=A\odot\left(G_A-\frac52\right) =\left(-\frac38,\frac38\right). \]
  4. Since \(d_k=1\) and \(q=1\): \[ \frac{\partial\mathcal L}{\partial q} =G_SK=-\frac38\ln3\approx-0.412, \qquad \frac{\partial\mathcal L}{\partial K} =G_S^\top q=\left(-\frac38,\frac38\right). \]
  5. The components of \(G_S\) sum to zero. A common shift of the scores does not change the softmax weights, so the derivative in that direction must be zero.

The path to V goes directly through the aggregation \(O=AV\). The paths to Q and K first pass through scores and then softmax. In a full layer, these local gradients are propagated further to the projection matrices and input representations.

Exercise — transfer Q/K/V to cross-attention

A decoder consults representations produced by an encoder. Let \(X_D\) denote decoder states and \(X_E\) encoder states.

  1. Write Q, K, and V for cross-attention.
  2. If only \(X_D\) changes, which projections are directly affected?
  3. If only \(X_E\) changes, which projections are directly affected?
  4. Explain why the single-input formula \(Q=XW_Q\), \(K=XW_K\), \(V=XW_V\) describes self-attention but not this cross-stream provenance.
  5. In MQA and GQA, what changes about the number or sharing of K/V heads? Which functional distinction between Q/K and V remains?
Show the reasoned solution

In cross-attention, Q comes from the querying stream, while K and V come from the stream being queried:

\[ Q=X_DW_Q,\qquad K=X_EW_K,\qquad V=X_EW_V. \]

With parameters fixed, changing \(X_D\) directly affects Q; changing \(X_E\) directly affects K and V. Scores and output may then change as a consequence. The functional distinction remains, but the projections no longer share a common input. In MQA, multiple query heads share one K/V head; in GQA, groups of query heads share K/V heads. The number or sharing of K/V heads changes, but the functional distinction remains: Q/K determine weights and V supplies aggregated content. Describe the exact parameterization rather than mechanically copying the standard case.

Exercise — Causal masking and prefix invariance

This exercise now lives on the dedicated Causal masking practice page, which is the canonical home for the causal-masking questions, worked solution and test interpretation.

Exercise — Compute a multi-head attention by hand

Preparation: the four computation steps of one head in scaled dot-product attention; head slicing and reassembly in the reference block walkthrough. The exercise covers a single query position of a \(T=2\)-position sequence, with \(d=4\) and \(H=2\) heads (\(\text{head\_dim}=2\)), no mask. The scores below are already scaled.

For the query under study:

  • Head 0: scaled scores \((\ln 3,\,0)\); \(V\) slice: \(v_1=(2,0)\), \(v_2=(0,4)\).
  • Head 1: scaled scores \((0,\,\ln 3)\); \(V\) slice: \(v_1=(0,2)\), \(v_2=(4,0)\).

The output projection is set to \(w_o=I_4\) for this exercise.

  1. Compute the attention weights of each head.
  2. Compute each head’s output.
  3. Write the reassembled vector attended in \(\mathbb{R}^{4}\).
  4. Do head 0’s weights depend on head 1’s scores? Does its output depend on head 1’s values?
  5. Which operation is the first to mix information across heads? Why is \(w_o=I_4\) a special case?
Show hints
  1. Each head applies its own softmax to its own scores.
  2. A head’s output is the weighted sum of its \(V\) slice.
  3. Reassembly concatenates the slices: head 0 into columns \(0\) to \(1\), head 1 into columns \(2\) to \(3\).
  4. Go back to the computation’s dependencies, not to the intuition of a single attention.
Show the worked solution
  1. Head 0: \(e^{\ln 3}=3\) and \(e^0=1\), sum \(4\), so the weights are \((3/4,\,1/4)\). Head 1: \((1/4,\,3/4)\).
  2. Head 0’s output: \(\frac34(2,0)+\frac14(0,4)=(1.5,\,1)\). Head 1’s output: \(\frac14(0,2)+\frac34(4,0)=(3,\,0.5)\).
  3. attended\(=(1.5,\,1,\,3,\,0.5)\): head 0’s two components, then head 1’s.
  4. No, and no: each head reads only its own \(Q\), \(K\) and \(V\) slices; its scores and output depend only on those slices.
  5. The output projection \(w_o\): it is the first operation whose weights read columns coming from both heads. With \(w_o=I_4\), every column stays within its head and no mixing occurs: that is an exercise choice, not the general case. In the real block, \(w_o\) is learned and mixes columns across heads.

Common errors:

  • Adding the two heads’ outputs instead of juxtaposing them: reassembly concatenates, it does not add.
  • Normalizing all four scores together: each head has its own softmax over its two scores.
  • Believing one head’s weights depend on the other head or on its values: until \(w_o\), heads are independent.

Success criterion: exact weights and outputs per head; reassembly by juxtaposition; head isolation up to \(w_o\).

Exercise — Trace the shapes of a multi-head attention

Preparation: the shape trace from the Transformer collection (TF-A) or the block walkthrough for head slicing; scaled dot-product attention for one head’s shapes (\(T\times T\) then \(T\times d_v\)).

A batch contains \(B=2\) sequences of \(T=3\) positions, with \(d=6\) and \(H=2\) heads. Complete the missing shapes:

Object Shape
Input \(x\) \((2,3,6)\)
\(Q\) (same for \(K\), \(V\)) ?
Slice of \(Q\) for head 0 (whole batch) ?
Head 0’s scores for one batch element ?
Head 0’s weights for one element (after causal mask and softmax) ?
Head 0’s output (whole batch) ?
attended (heads reassembled) ?
Output of the projection \(w_o\) ?

Then answer:

  1. What is \(\text{head\_dim}\)? By which factor are one head’s scores scaled?
  2. If \(H\) goes to \(3\) (with \(d=6\)), which shapes change, and which stay \((3,3)\)?
  3. If \(H=4\), is the configuration realizable in the reference block? Why?
  4. Does the total number of attention parameters change when \(H\) changes?
Show hints
  1. The projections stay \((d,d)\); heads are column slices.
  2. Scores compare queries and keys of the same width: count positions, not features.
  3. \(\text{head\_dim}=d/H\) must be an integer in the reference block.
Show the worked solution

\(Q\), \(K\) and \(V\) have shape \((2,3,6)\). Head 0’s slice: \((2,3,3)\). Head 0’s scores for one batch element: \((3,3)\); so are the weights after the causal mask and softmax. Head 0’s output (whole batch): \((2,3,3)\). attended: \((2,3,6)\). \(w_o\)’s output: \((2,3,6)\).

  1. \(\text{head\_dim}=6/2=3\); one head’s scores are divided by \(\sqrt{3}\): a head’s key width is \(\text{head\_dim}\), not \(d\).
  2. The slices become \((2,3,2)\); one head’s scores stay \((3,3)\) (three queries compared with three keys); attended stays \((2,3,6)\). The scaling factor goes from \(1/\sqrt{3}\) to \(1/\sqrt{2}\): a head’s weights can change.
  3. \(H=4\) would give \(\text{head\_dim}=1.5\), not an integer: the reference block’s column slicing requires \(H\) to divide \(d\). Per-head projection implementations do not have exactly this constraint.
  4. No: in the reference block the projections stay \((d,d)\) and heads are slices of them; only the number of slices changes (cf. TF-B).

Common errors:

  • Giving a head’s scores the width \(\text{head\_dim}\): scores cross queries and keys, so their shape is \((T,T)\).
  • Scaling scores by \(\sqrt{d}\): a head’s key width is \(\text{head\_dim}\).
  • Adding a head axis to the reassembled tensor: the reference block reassembles by columns into a \((B,T,d)\) tensor.

Exercise — Diagnose multi-head claims and predict interventions

Preparation: scaled dot-product attention and Q/K/V projections after AT-A and AT-B; the block walkthrough for the reference parameterization. “The reference block” means the pre-LN block of the walkthrough.

Stage 1 — Classify claims. Classify each statement as valid, invalid, or architecture-dependent, and justify your choice.

A. Each head computes its own weights from its own \(Q\) and \(K\) slices. B. Heads exchange information before the output projection \(w_o\). C. In the reference block, one head’s scores are scaled by \(1/\sqrt{\text{head\_dim}}\), not by \(1/\sqrt{d}\). D. A head’s weights depend on the values of its \(V\) slice. E. Doubling the number of heads doubles the size of each head’s scores. F. An attention with \(H\) heads of width \(\text{head\_dim}=d/H\) is equivalent to a single head of width \(d\). G. Every model has as many query heads as key/value heads.

Show hints
  1. Separate one head’s computation from reassembly and \(w_o\).
  2. For the scale, recall a head’s key width.
  3. For statement G, reread the MQA and GQA note in the Q/K/V lesson.
Show the worked solution
  • A — Valid: each head computes its scores and its softmax on its own slices.
  • B — Invalid: heads stay isolated until \(w_o\), the first operation that mixes columns from several heads.
  • C — Valid for the reference block: a head’s key width is \(\text{head\_dim}\); scaling follows the key width. The precise convention depends on the parameterization.
  • D — Invalid: the weights depend on the \(Q\) and \(K\) slices; the \(V\) slice supplies the aggregated content.
  • E — Invalid: a head’s scores cross queries and keys, shape \((T,T)\); when \(H\) changes, it is \(\text{head\_dim}\) that changes, not the shape of the scores.
  • F — Invalid: \(H\) heads compute \(H\) score matrices from dot products of width \(\text{head\_dim}\); a single head of width \(d\) would compute different dot products. These are not the same functions.
  • G — Architecture-dependent: the standard formulation balances query and key/value heads, but MQA and GQA share K/V heads across several query heads to reduce inference-time KV-cache cost.

Common error: describing multi-head attention as “several attentions at the same scale”: each head works in a subspace of width \(\text{head\_dim}\), with its own scaling factor and its own normalization.

Stage 2 — Predict interventions. Start from the reference block at standard initialization. For each intervention, predict what changes and what stays invariant:

  1. Head 1’s \(V\) slice is set to zero, and nothing else. What happens to head 1’s weights? Its output? The reassembled tensor? The block output?
  2. The reassembly order is swapped: head 0’s output lands in head 1’s columns, and conversely. What happens to each head’s weights and outputs? The reassembled tensor? \(w_o\)’s output?
  3. \(H\) goes from \(2\) to \(3\), with \(d=6\) and the same projection matrices. Does the number of attention parameters change? \(\text{head\_dim}\)? The scaling factor? Can a head’s weights change? The shape of the reassembled tensor?
Show hints
  1. A head’s weights read only its \(Q\) and \(K\) slices.
  2. The intervention happens after the heads’ computation, but before \(w_o\).
  3. Reuse TF-B’s reasoning on parameters, then AT-B’s on the scaling factor.
Show the worked solution
  1. Head 1’s weights do not change: they depend on its \(Q\) and \(K\) slices. Its output becomes the zero vector (a weighted sum of zero values). The reassembled tensor keeps its shape: head 0’s columns unchanged, head 1’s columns zero. The block output generally changes: the attention branch now contributes only head 0’s output.
  2. Each head’s weights and outputs are unchanged: the intervention happens after the heads’ computation. The reassembled tensor changes: the slices land in the wrong columns. \(w_o\) applies learned weights to specific columns; applied to a permuted reassembly, it generally produces a different output. Reassembly is not a neutral permutation.
  3. The attention parameters do not change: the projections stay \((d,d)\) and heads are slices of them (cf. TF-B). \(\text{head\_dim}\) goes from \(3\) to \(2\); the scaling factor goes from \(1/\sqrt{3}\) to \(1/\sqrt{2}\); scores divided by a different factor generally give different weights. The reassembled tensor keeps shape \((2,3,6)\).

Common errors:

  • “A zero \(V\) slice kills the head”: the head still produces weights; it is its aggregated content that becomes zero.
  • “Reordering the reassembly has no effect”: \(w_o\) reads specific columns, and the slice-to-column correspondence matters.
  • “Changing \(H\) only changes shapes”: the score scaling factor changes too, and therefore the weights.

Success criterion: correct predictions on all three interventions; distinguishing weights from content; slice-to-column correspondence in reassembly; the effect of \(H\) on the scaling factor.

Exercise AT-D — Why divide scores by √dₖ?

Assume that all components \(q_i\) and \(k_i\) are mutually independent, zero-mean, and have unit variance. Let \(S=q^\top k=\sum_{i=1}^{d_k}q_i k_i\).

  1. Compute \(\mathbb{E}[S]\).
  2. Show that \(\operatorname{Var}(q_i k_i)=1\), then derive \(\operatorname{Var}(S)\).
  3. For \(d_k=64\), compare the standard deviation of \(S\) with that of \(S/\sqrt{d_k}\).
  4. Why does this result not guarantee a variance of exactly 1 in a trained network?
Show hints
  • Use independence between \(q_i\) and \(k_i\) to factor expectations.
  • Also use independence of the products \(q_i k_i\) across dimensions when computing the variance of the sum.
  • Variance is divided by the square of the scaling factor.
Show the worked solution

By independence and zero means, \(\mathbb{E}[q_i k_i]=\mathbb{E}[q_i]\mathbb{E}[k_i]=0\), so \(\mathbb{E}[S]=0\).

Because \(q_i\) and \(k_i\) are independent, zero-mean, and have unit variance: \(\operatorname{Var}(q_i k_i)=\mathbb{E}[q_i^2]\mathbb{E}[k_i^2]=1\). The products are independent across dimensions, so variances add: \(\operatorname{Var}(S)=\sum_{i=1}^{d_k}1=d_k\).

The raw standard deviation is therefore \(\sqrt{d_k}\). For \(d_k=64\), it is 8. After division by \(\sqrt{d_k}=8\), the variance becomes \(d_k/d_k=1\) and the standard deviation is 1.

In a trained Transformer, projected components are not necessarily independent, zero-mean, or unit-variance. The factor \(1/\sqrt{d_k}\) controls scale in the simplified model; it does not guarantee an empirical variance of exactly 1 for every layer, head, and input.

Success criterion: derive the variance under the stated assumptions, calculate the scaling effect, and distinguish the theoretical result from its scope in a trained network.

Further work: exercises on multi-head causal masking, normalization invariants and MQA/GQA variants will complete this collection.


← Back to the exercise catalogue

Language: Français · English