Exercises — Self-attention mechanism in detail
This page tests everything from the parent note. Work each problem on paper first, then open the collapsible solution. Levels run from L1 Recognition (do you know the pieces?) up to L5 Mastery (can you reason about the whole machine under pressure?).
Every symbol used here was built in the parent note. A quick reminder of the cast, so line one makes sense:
The one-line machine:
The figure below traces the shapes through that machine — keep it beside you while you solve, because most L1–L2 slips are really shape slips. Read it left to right: enters (an block, so = sequence length, = embedding dimension), gets projected into , the table appears (, one row per query), scaling and softmax reshape that table into , and produces the output . Notice the blow-up in the middle — that is the source of the cost you will meet in Exercise 4.2.

Prerequisite refreshers if any step feels shaky: 3.2.05-Attention-mechanism-basics, 4.1.01-Transformer-architecture-overview.
L1 — Recognition
Exercise 1.1 — Name the shapes
Let (five words, so = sequence length) and (embedding dimension), with . State the shape of: (a) , (b) , (c) , (d) , (e) the softmax output , (f) the final output .
Recall Solution 1.1
A shape is just (number of rows) (number of columns). Read it off from what each object is.
- (a) : five word-vectors of length → .
- (b) : takes a length- vector and returns a length- vector → .
- (c) : .
- (d) : — every word against every word.
- (e) : softmax is applied entrywise per row, shape unchanged → .
- (f) : .
Exercise 1.2 — Which matrix asks the question?
For the sentence "it was tired", the model is trying to figure out what "it" refers to. Which learned matrix produces the vector that "goes shopping" for the answer — , , or ? And which produces the vector that "advertises" a word as findable?
Recall Solution 1.2
The word doing the looking is the query, so its shopping vector is → asks the question. Every candidate word advertises through its key → offers itself. ( is neither the question nor the advertisement — it is the content handed over once a match is made.)
L2 — Application
Exercise 2.1 — Compute a score row by hand
Two query/key vectors live in space: Compute the three raw scores . Which key does align with best, and why does that make sense?
Recall Solution 2.1
A dot product is "multiply matching slots, add them up" — it is large when two vectors point the same way.
- .
- .
- . Best match is with score . That is no accident: is identical to , so they point in exactly the same direction — the strongest possible alignment. This is the geometric meaning of "high dot product = high relevance."
Exercise 2.2 — Softmax a scaled row
Take the scores from 2.1, scale by , then apply softmax. Give the three attention weights to two decimals and confirm they sum to . (Recall: each output weight is one entry of the attention matrix — here we are computing the single row for query .)
Recall Solution 2.2
Scale first: . Exponentiate: , , . Sum . Divide each — the results are , the three entries of row 1 of : They sum to . Notice how softmax amplified the gap: raw scores became weights — the top key now dominates far more than its raw lead suggested. That amplification is exactly why we use and not plain division.
Exercise 2.3 — Why did we scale?
In 2.2 we divided by before softmax. Redo the softmax on the unscaled scores and compare the top weight. What did scaling buy us?
Recall Solution 2.3
Unscaled: , sum . The top weight jumped from (scaled) to (unscaled) — the distribution got sharper. With larger this sharpening runs away: softmax becomes almost one-hot, and gradients in its flat tails vanish. Dividing by tames scores back toward unit variance so learning stays healthy. (See 5.3.03-Gradient-flow-in-deep-networks.)
L3 — Analysis
Exercise 3.1 — A full 2-word pass
Let Compute , then , scale by , softmax each row, and give the final output to two decimals.
Recall Solution 3.1
With identity projections, . And . Scores: . Scale by : . Softmax row 0 on : , sum → . Row 1 is the mirror . Row 0 output , row 1 . Because swaps the two coordinates, each word ends up carrying mostly the other word's original content — a clean demonstration that values decide what gets moved, independent of who matched whom.
Exercise 3.2 — Reading an attention matrix
A trained head gives, for "The cat which was fluffy sat": (the row for the query word "sat", columns = The, cat, which, was, fluffy, sat). What has this head learned, and which parent-note claim does it confirm?
Recall Solution 3.2
The weights add to . The overwhelming mass () sits on "cat", the grammatical subject, even though "fluffy" () is physically closer to "sat". This is a subject–verb link learned by /: the verb's query aligns with the noun's key. It confirms the parent's Example 2 claim — self-attention captures long-range dependencies directly, with no decay over distance, unlike an RNN that must carry the subject through every intervening step.
L4 — Synthesis
Exercise 4.1 — Permutation blindness
Show that plain self-attention treats "dog bites man" and "man bites dog" as the same set of relationships in the sense that permuting the input rows permutes the output rows identically — i.e. attention is permutation-equivariant. Then explain which mechanism from the chapter fixes this.
Recall Solution 4.1
Let be a permutation matrix (it just reorders rows; note ). Feed instead of :
- , likewise , .
- Scores: — the score table is reindexed on both axes.
- Why softmax commutes with the reindexing. Softmax acts one row at a time and only reorders columns within a row. Multiplying on the left by shuffles which rows we have; multiplying on the right by shuffles the columns inside each row identically. Since softmax of a row is a function of that row's entries only (and reindexing a row's entries just reindexes softmax's outputs the same way), applying softmax after the shuffle equals shuffling after softmax. Crystallized as the identity: Concretely: row of is row of with its columns permuted by , so its softmax is row of with columns permuted by — exactly row of .
- Output: unpack the multiplication carefully, using in the middle. So permuting inputs merely permutes outputs the same way — the operation has no idea about order. The fix in this chapter is 4.1.04-Positional-encoding: add position-dependent signals to so that and differ even when the words are identical, breaking the symmetry.
Exercise 4.2 — Cost of a longer document
Self-attention costs . You double the sequence length and also double the model dimension . By what factor does the attention cost grow? Then contrast with the memory for storing the score matrix.
Recall Solution 4.2
Compute cost scales as . New cost → 8×. The score matrix has shape , so its memory scales as (independent of ): doubling alone gives 4× the stored scores. This term is the wall that motivates efficient attention variants — see 4.2.02-Computational-complexity-of-transformers.
L5 — Mastery
Exercise 5.1 — Prove the scaling variance claim
The parent asserts: if each and are independent with mean and variance , then . Prove it, stating each independence assumption you use, and conclude why (not ) is the right divisor.
Recall Solution 5.1
Write the dot product as a sum: . Step 1 — mean of one term. By independence of : . Step 2 — variance of one term. By definition . Since has mean , ; identically . Now (The zero-mean fact is exactly what turns into ; without it we'd have an extra term.) Step 3 — variance of the whole sum. The product-terms are independent of one another (each uses a different coordinate ), and for independent quantities variances add: This is the claimed result: . Step 4 — the divisor. Variance is , so the standard deviation (the typical size of a score) is . To rescale a random quantity back to unit spread you divide by its standard deviation, not its variance. Dividing by gives restoring unit variance so softmax stays well-behaved. Dividing by instead would over-shrink to variance . ∎
Exercise 5.2 — Softmax gradient vanishing
Consider a single query with two keys and raw (scaled) scores . Let be the softmax weight on the first key. Compute as a function of , then , and show it collapses to as . Explain in one sentence why this is the vanishing-gradient danger the scaling factor guards against.
Recall Solution 5.2
Softmax of : — the logistic sigmoid . Its derivative: . As : , so . (Symmetrically as .) One sentence: once scores are pushed far apart the softmax saturates, its slope goes to zero, and gradients cannot flow back through the attention weights — precisely why unscaled large- scores kill learning, and why keeps modest.
Exercise 5.3 — Design a masking rule
You want a causal attention where word may only attend to words (no peeking ahead). Describe exactly what you add to the score matrix before softmax, and prove that a future position receives weight after softmax.
Recall Solution 5.3
Add a mask matrix where for and for , forming before softmax. Proof that future weight vanishes: for a forbidden entry, the scaled score becomes . In softmax the numerator is , so Thus every future position gets exactly zero weight while the allowed positions still form a valid distribution summing to (the entries contribute to the denominator too). In practice is a large negative number like , giving weight indistinguishable from .
Related deep dives: 4.1.03-Multi-head-attention, 4.1.04-Positional-encoding, 4.2.02-Computational-complexity-of-transformers.