Exercises — Transformers — attention mechanism, self-attention
Level 1 — Recognition
L1.1 — Name the roles
Each input vector is multiplied by three learned matrices to make three vectors. Name each vector and give its one-line "job description."
Recall Solution
- — the Query: what am I looking for?
- — the Key: what do I advertise to others?
- — the Value: what content do I pass on if selected?
"Self"-attention means all three come from the same sequence.
L1.2 — Spot the axis
In , along which axis is softmax applied, and why?
Recall Solution
Row-wise, i.e. across keys / positions. Each row of holds one query's scores against every key. Softmax on that row turns those scores into weights that sum to 1, giving a probability distribution over "which tokens to read." It is not applied over the feature dimension.
L1.3 — Which are the learned parameters?
Of these, which are learned and which are computed on the fly from inputs: , , , ?
Recall Solution
- Learned (fixed after training, same for every input): , (also , ).
- Computed on the fly (change with each input): , .
Level 2 — Application
L2.1 — Score a single pair
Given and with , compute the scaled score .
Recall Solution
Raw dot product: . Scale: .
L2.2 — Two-token softmax
For token 1 you have unscaled scores with . Scale by , then compute via softmax.
Recall Solution
Scaled: , . Check: they sum to 1, as attention weights must.
L2.3 — Blend the values
Continuing L2.2, with and , compute the output .
Recall Solution
Interpretation: token 1 mostly grabs (its query matched key 1) but mixes in a third of — a soft lookup, not a hard pick. See the geometry below.

L2.4 — Full pipeline, one number
Two tokens, : ; keys ; values . Compute .
Recall Solution
Raw scores: , . Scale by : , . Softmax: , (mirror of L2.2). Output:
Level 3 — Analysis
L3.1 — Standard deviation of a score
Each component of and is independent with mean 0 and variance 1, and . What is the standard deviation of the unscaled dot product , and what does dividing by do to it?
Recall Solution
is a sum of independent products, each with variance (since for zero-mean unit-variance independent factors). Variances add: Dividing by scales the std by , giving std — exactly the "keep variance near 1" goal from the parent note. Linked idea: Gradient vanishing/saturation.
L3.2 — Permutation equivariance by example
Tokens A and B produce outputs . If you swap the input order to B, A (same vectors, swapped positions), what happens to the outputs? What does this reveal about attention's sense of order?
Recall Solution
The outputs swap identically: the model returns — the same vectors in swapped slots. Because every score depends only on which vectors meet, not where they sit, self-attention is permutation-equivariant. Consequence: it has no built-in notion of order, which is why Positional Encoding must be added to inject "who came first."
L3.3 — Why dot product and not, say, Euclidean distance?
The score uses . Argue why a dot product is a sensible "relevance" measure here and connect it to cosine similarity.
Recall Solution
The dot product , where is the angle between them. It is large and positive when the two vectors point the same way () — precisely "these two are relevant." It is smooth and differentiable (unlike a hard match) so gradients flow, and it's one cheap matrix multiply for all pairs at once (parallelism). Distance would need extra normalisation and doesn't factor into a single matmul as cleanly. See Dot product & cosine similarity.
Level 4 — Synthesis
L4.1 — Multi-head dimension bookkeeping
A model uses with heads. Each head runs scaled dot-product attention with per-head dimension . Find , the total width after concatenating all heads, and confirm the output projection has the right shape to return to .
Recall Solution
Each head outputs a -wide vector per token. Concatenating heads gives width . Then maps , i.e. , returning to . Note the total compute stays comparable to one big head — that's the elegance. See Multi-Head Attention.
L4.2 — Aerospace anomaly, direct connection
An engine telemetry sequence has 200 timesteps. You predict an anomaly at that was caused by a pressure drop starting at . (a) How many attention "hops" separate query from key in self-attention? (b) Contrast with an RNN. Why does this matter for Time-series anomaly detection (aerospace telemetry)?
Recall Solution
(a) One hop. Query dots directly with key ; the path length is 1 regardless of the 60-step gap. (b) An RNN must thread the signal through 60 sequential hidden-state updates, each blurring/diluting it (long-range forgetting). Self-attention's single direct connection preserves the signal with no information loss, so the model can put a large and flag the true cause.
L4.3 — Build a 3-token attention matrix shape
For tokens with and : give the shapes of , , , , the softmaxed weight matrix, and the final output .
Recall Solution
- (rows = tokens, cols = ).
- .
- — all pairwise scores; row = token 's scores.
- softmax (row-wise) keeps shape .
- — same width as the values, one output row per token.
Level 5 — Mastery
L5.1 — Quantify softmax saturation
Take a single query with scores against two keys. Unscaled they are (as if pushed them apart). (a) Compute the softmax weights unscaled. (b) Now scale by and recompute. (c) In one sentence, explain the gradient consequence.
Recall Solution
(a) Unscaled: , so — nearly one-hot. (b) Scaled scores: and . Then , — a healthy blend. (c) In the unscaled case the second weight is , so — gradients to that token vanish; scaling by keeps both weights sizeable, so learning signal flows to both. This is the Gradient vanishing/saturation fix in action.

L5.2 — Full 2-token attention, both outputs, from raw dot products
. ; ; . Compute and end-to-end.
Recall Solution
Token 1. Raw scores: , . Scale by : , . Softmax: , . Output: .
Token 2. Raw scores: , . By the same arithmetic (mirror): , . Output: .
Each token attends mostly to itself (its query matches its own key), mixing in ~20% of the other — a clean symmetric example.
L5.3 — Design a masked score (extension)
In an autoregressive setting, token must not peek at future tokens . Without changing softmax, how do you force for all future ? Verify your fix on token 1 of L5.2 with token 2 masked.
Recall Solution
Set the future scores to before softmax (add a mask of to those entries). Since , those weights become exactly 0 and the surviving weights renormalise. Check on token 1 with masked: scaled scores , . Softmax: , . Output: — token 1 now reads only itself, as required.