Worked examples — Self-attention mechanism in detail
This page is a workout gym for the parent note. There we built the formula Here we run it through every kind of input it can meet — big scores, tiny scores, ties, a single word, a degenerate all-zero query, a masked (causal) case, and a real sentence. If you have not yet seen why , , exist, or why we divide by , read the parent first; this page assumes those pieces are already earned.
Two symbols we reuse constantly, restated in plain words:
- A dot product is one number that says "how much do these two arrows point the same way?" Big positive = aligned, = perpendicular (unrelated), negative = opposite. This is the similarity score of attention.
- Softmax turns a list of numbers into a list of positive weights that sum to : . Think of it as "vote shares" — every position gets a slice of a pie that always totals .
The scenario matrix
Every input a self-attention layer meets falls into one of these case classes. Below, each example is tagged with the cell(s) it covers.
| # | Case class | What is special | Covered by |
|---|---|---|---|
| C1 | Ordinary spread | Scores differ moderately → soft, mixed weights | Ex 1 |
| C2 | Tie / symmetry | Two keys equally relevant → equal split | Ex 2 |
| C3 | Large scores (peaky) | Big or big values → near one-hot; shows why we scale | Ex 3 |
| C4 | Degenerate query = 0 | Query vector is all zeros → all scores equal → uniform average | Ex 4 |
| C5 | Single token, | Limiting smallest sequence → attends to itself, weight | Ex 5 |
| C6 | Negative alignment | A key points opposite the query → down-weighted, never negative | Ex 6 |
| C7 | Causal mask | Future positions forbidden () → decoder-style attention | Ex 7 |
| C8 | Real word problem | A full sentence, semantic reasoning | Ex 8 |
| C9 | Exam twist | "What must be?" shape-inference puzzle | Ex 9 |
We visit all nine cells. Numbers in every worked example are checked in the appendix.
The picture above is the whole machine in one glance: a query arrow (red) is compared to each key arrow by dot product, those numbers go through softmax to become a pie of weights, and the weights mix the value vectors into one output. Every example below is just this pipeline with different arrows.
Example 1 — Ordinary spread (C1)
Forecast: Guess before computing — will "cat" attend mostly to itself, or spread out? Write down a guess.
- Scores : with we get . Why this step? The dot product is our similarity meter. aligns fully with and (both have a in the first slot), and is perpendicular to .
- Scale by : . Why this step? Without scaling, larger inflates dot products and softmax becomes razor-sharp; keeps variance near (proved in parent).
- Softmax: , , ; sum . Why this step? Turns raw alignment into a pie of weights totaling so we can average.
- Aggregate: Why this step? The output is a weighted blend of values, pulling most from positions "cat" and "mat".
Recall Answer
Output for "cat" . It attended // — a genuine spread, exactly the "ordinary" case.
Verify: Weights sum to ✓. Output lies inside the convex hull of the rows of (each coordinate between the min and max of that column of ) — a weighted average can never escape its inputs. ✓
Example 2 — Tie / symmetry (C2)
Forecast: By symmetry, guess the split before reading on.
- Scores: , . Identical. Why this step? The query leans equally toward both axes, so both keys score the same.
- Scale & softmax: identical inputs → regardless of scaling. Why this step? Softmax of equal numbers is always uniform; scaling a constant leaves it constant.
Recall Answer
A perfect split.
Verify: For any two equal scores , . ✓ This is the tie cell — ties always split evenly, no matter the magnitude.
Example 3 — Large scores show why we scale (C3)
Forecast: Which version gives sharper, more one-hot weights?
- Unscaled softmax of : , so . Why this step? Big raw scores make softmax nearly one-hot — almost all weight on one key.
- Scaled by : inputs become . , sum , . Why this step? Scaling pulls scores back to a healthy range, so weights stay soft and gradients survive (near-one-hot rows have almost-zero gradient — see gradient flow).
Recall Answer
Unscaled: (peaky, gradient-starved). Scaled: (healthy). Same information, very different learnability.
Verify: and . ✓ The scaling is not cosmetic — it is the difference between a trainable and a frozen layer.
Example 4 — Degenerate query (C4)
Forecast: A zero query has no direction to prefer. Guess the weights.
- Scores: for every (zero dotted with anything is ). Why this step? This is the degenerate boundary — the query expresses no preference at all.
- Softmax of . Why this step? Equal scores → uniform weights; the output becomes the plain average of all values.
Recall Answer
Uniform — self-attention gracefully falls back to "average everyone" when the query says nothing. No crash, no divide-by-zero.
Verify: and . ✓ This proves the layer is defined even on degenerate input.
Example 5 — Single token, (C5)
Forecast: With only itself to look at, where can attention go?
- Scores: a single number . Why this step? There is exactly one key, so the score list has length .
- Softmax of a single value is always : . Why this step? — the pie has one slice, so it takes the whole pie regardless of .
- Aggregate: . Why this step? The output equals the token's own value — self-attention on a lone token is the identity on .
Recall Answer
Output . The smallest sequence is a fixed point: a single token passes its value straight through.
Verify: for any ; output . ✓ Limiting-case sanity confirmed.
Example 6 — Negative alignment (C6)
Forecast: Can a weight ever be negative? Guess yes or no.
- Scores: , . Why this step? Opposite arrows give a negative dot product — the meter reads "anti-aligned".
- Softmax: , , sum , so . Why this step? The exponential of a negative number is a small positive number — softmax can shrink a weight toward zero but can never make it negative.
Recall Answer
. The opposing key is heavily down-weighted yet keeps a small positive share — attention is a soft gate, not a switch.
Verify: and both weights . ✓ Weights are always in ; this is why softmax and not a raw signed normalization.
Example 7 — Causal mask (C7)
Forecast: What happens to the weight on the (forbidden) future position ?
- Mask the future: set , giving . Why this step? The mask enforces that a token predicts using only past+present — this is how the decoder stays causal.
- Softmax: , so position gets weight . On the survivors : , sum , . Why this step? Setting the score to before softmax is the clean way to drop a position — it exits the pie entirely, and the remaining weights still sum to .
Recall Answer
. The forbidden future is exactly zero and the past re-normalizes among itself.
Verify: , , sum , future weight . ✓
Example 8 — Real word problem (C8)
Forecast: Which noun wins — trophy or suitcase?
- Softmax of : , , , sum . Why this step? The learned projections have made the query for "it" align with the subject noun; softmax then amplifies that lead.
- Read the winner: "trophy" holds of the weight. Why this step? Coreference resolution is the argmax of the attention row — the output for "it" becomes almost entirely the value vector of "trophy".
Recall Answer
"it" resolves to trophy with attention. Swap "big" → "small" and the trained scores would flip to favor suitcase — the meaning drives the weights.
Verify: . ✓ The largest score dominates but never fully — the smaller words keep tiny positive shares (soft attention).
Example 9 — Exam twist: shape inference (C9)
Forecast: Guess before computing.
- Split rule: . Why this step? Multi-head attention divides the embedding across heads so total compute matches a single full-size head.
- Score shape: , , so . Why this step? Inner dimension cancels; the surviving is every-query-vs-every-key.
Recall Answer
; score matrix is . The entries are exactly the $O(n^2)$ cost of attention.
Verify: and . ✓