Module 2 · Lesson 2.1 of 2.5
Self-Attention From First Principles
One attention layer takes a sequence of vectors and returns a new sequence of the same length, where each output row is a weighted mix of information from the other positions. This lesson derives that operation one step at a time, with numbers small enough to check by hand.
Learning goal. By the end you should be able to trace an input vector through projections, scores, weights and a weighted value mixture, give the shape of every intermediate tensor, explain why the √dk scale and the causal mask exist, and compute a small example by hand.
Builds on. Module 1 treated attention as a black box inside prefill and decode. Here we open the box. The KV cache comes back in Lessons 2.4 and 2.5, once we know exactly what K and V are.
Conventions and simplifications. Row-vector convention: a sequence is a matrix whose rows are token positions, and projections are written XW. One attention head, one sequence (no batch dimension), biases omitted, word-level tokens. The main “The sky is” example uses invented 2-component vectors and the same toy projections as Module 1. Detailed panels contain separate worked examples and explicitly wider vectors; none come from a trained model.
Primary source: Vaswani et al., “Attention Is All You Need” (2017), Section 3.2. The derivations and examples below are written for this site.
2.1.1 Why attention?
Consider the prompt “The sky is”. Each token position carries a vector. Attention lets the current position draw information from earlier positions and itself, so its vector can reflect the allowed context. First inspect which positions are available; later we calculate how much each one contributes.
Which examples appear here. Every section of this lesson opens with the shared “The sky is” view, which uses Module 1’s numbers. The alternates sit inside “Detailed derivation and alternate worked example” and are labelled: a three-token toy, “animal was tired” (with “The” prepended in 2.1.6–2.1.7), which has its own matrices; a 16-component ±1 example in 2.1.4; and, in 2.1.1’s motivation, a longer sentence (“The animal was tired because it …”). Matching digits between an alternate and Module 1 are a coincidence, not a link. Lesson 2.4 later uses “The sky is blue” for the cache.
Before transformers, the common answer was a recurrent network. It reads tokens in order and keeps one fixed-size state vector, updated once per token. Information about animal
(position 2) reaches it
(position 6) only by surviving four sequential state updates, and those updates cannot run in parallel across positions during training. A convolution reaches only a fixed window of neighbours per layer.
Self-attention takes a different route. Every position computes a weighted average over the vectors of all positions it is allowed to see, in one step. The weights are computed from the content of the vectors themselves, so the same layer can draw mostly from position 2 for one sentence and from position 9 for another. The path between any two visible positions is one step long, regardless of distance. The price is that every position is compared with every visible position: T positions produce on the order of T2 comparisons.
Which positions can a query position read?
- What this shows
- For a chosen position, which tokens are available to its attention in a causal (left-to-right) language model.
- Try
- Compare the first “The” with the final “.” in this separate long sentence.
- What to notice
- Every visible position is one attention step away, however far back it is. Future positions are unavailable (Section 2.1.6 explains how).
Assumptions: word-level tokens (real tokenizers often split words differently); causal visibility as used by decoder-only language models. This view shows only availability, not how much weight a trained model would actually assign.
What this does not claim. Whether a trained model actually puts high weight on animal
when processing it
depends on the model, the layer and the head. Attention weights show how values were mixed; they are not, by themselves, a reliable explanation of a model's reasoning. The sentence only motivates why positions need access to each other.
2.1.2 Queries, keys and values
Attention needs two different things from every pair of positions (i, j): a number saying how much position i should draw from position j, and a vector saying what position j provides if it is drawn from. Self-attention gets both by projecting each input row three times with three learned matrices.
- X ∈ ℝT×dmodel
- Input to the layer: one row xi per token position. In a real model these are the hidden states coming from the previous layer (or the embeddings, for layer 1).
- T
- Number of positions in the sequence.
- dmodel
- Width of each input row.
- WQ, WK ∈ ℝdmodel×dk
- Learned query and key projections. They must share the output width dk because queries and keys are compared by dot product.
- WV ∈ ℝdmodel×dv
- Learned value projection. dv may differ from dk.
- Q, K, V
- Shapes [T, dk], [T, dk], [T, dv]. Row i of each is qi = xiWQ, ki = xiWK, vi = xiWV.
The roles come from how the results are used, not from anything inside the matrices: Q rows are compared against K rows to produce scores (2.1.3), and the scores decide how the V rows are mixed (2.1.7). Training adjusts all three matrices so that this pipeline helps predict the next token.
Analogy, not mathematics. A query is like a search request, keys are like the labels on stored items, and values are the items' contents. The analogy breaks in two important ways: attention is soft retrieval, returning a weighted blend of every visible value rather than one match, and all three vectors are linear functions of the same input row, with no rule forcing them into these roles.
Toy example. Take T = 3 tokens (“animal”, “was”, “tired”) and dmodel = dk = dv = 2. The third input row is x3 = [1, 1]. Multiplying it by the three toy matrices gives q3 = [1, 2], k3 = [1, 3] and v3 = [1, 1]: one input, three different vectors.
Worked projection: tired
Separate 3-token toy: “animal / was / tired”. The fixed worked row is “tired”, x₃ = [1, 1]. Its matrices and numbers differ from the main “The sky is” model.
- What this shows
- The toy input matrix X, the three learned matrices, and the resulting Q, K, V with the selected row highlighted and its arithmetic written out.
- Try
- Follow the highlighted “tired” row through each matrix and compare its q, k and v.
- What to notice
- The same input row produces three different vectors. Because the projections are linear and x3 = x1 + x2 here, every projection of “tired” is the sum of the projections of “animal” and “was”.
Assumptions: invented toy values; dmodel = dk = dv = 2; biases omitted; one head. Matrices are fixed because in a model they are learned, not chosen per input.
Biases. Some implementations add a bias vector to each projection (XWQ + bQ); many recent decoder models omit them. Leaving them out keeps the arithmetic small and does not change the structure of anything that follows.
Engineering implication. The three projections are three matrix multiplications over all T rows, about T·dmodel·(2dk + dv) multiply-adds. Implementations commonly fuse them into one multiplication by a concatenated weight matrix. The K and V rows computed here are exactly what a KV cache stores during generation (Lesson 2.4): they depend only on the token's own input row, so once computed they can be reused.
2.1.3 Attention scores: S = QKT
We now need the number that says how strongly position i should draw from position j. Attention uses the dot product of query i with key j, for every pair at once.
- sij
- Raw score of query position i against key position j. Row i of S holds one score per key.
- c
- Index over the dk components of the vectors.
- KT
- Transpose of K, shape [dk, T], so [T, dk] × [dk, T] gives [T, T].
Worked example. With q = q3 = [1, 2], k1 = [2, 1] and k2 = [−1, 2]: q · k1 = 1·2 + 2·1 = 4 and q · k2 = 1·(−1) + 2·2 = 3. The third key k3 = [1, 3] scores 7.
Raw scores are not normalised similarity. Since q · k = ‖q‖ ‖k‖ cos θ, a score mixes direction (cos θ) with length. Here k1 has cosine 0.8 with q and length 2.24, while k3 has cosine 0.99 and length 3.16. A longer key can outscore a better-aligned one. The model is free to use vector length as part of the signal; nothing normalises it away.
Attention-score explorer
- What this shows
- One query against the three toy keys: each elementwise product, the sum that forms the raw score, key lengths and cosines, and a bar comparison. The same explorer continues in 2.1.5 with softmax.
- Try
- Switch query rows. Then edit q to [2, 1]: k1 points the same way (cosine 1) yet ties with k3. Try [0, 0] and [−1, −2].
- What to notice
- A score is a sum of per-component products, so one large component can dominate it. Negating q negates every score and reverses the ranking.
Assumptions: this alternate example uses fixed query rows from its own projection matrices. Selecting a row inspects it; it does not edit Q. Shared starting embeddings are changed only in the main projection step.
Engineering implication. S has T2 entries per head and costs T2·dk multiply-adds. At T = 8,192 that is about 67 million scores per head per layer. Storing S in GPU memory and reading it back is expensive, which is why fused kernels such as FlashAttention (Dao et al., arXiv 2205.14135) compute it in tiles without materialising the full matrix. The mathematics is unchanged.
Words in these notes. A GPU is the processor that runs these matrix multiplications in parallel. A kernel is one program launched on the GPU; a fused kernel does several steps in one launch instead of several. A tile is a small block of a matrix (for example 64 × 64 entries) processed at a time. Materialising S means writing all of it out to memory. FlashAttention is explained in Module 4 (lesson 4.3), online softmax in lesson 4.2; GPU memory and tiling are taught in Module 3. You do not need either to follow this lesson.
2.1.4 Scaling by √dk
A dot product adds one product per component. Wider query/key vectors can produce larger score variations. Before turning scores into weights, attention divides each score by the square root of their width. Our vectors have 2 components, so the divisor is √2.
Why √dk: the variance argument
Optional background. This argument and the saturation note below use variance (the average squared spread of a number around its mean) and a derivative (how fast one quantity changes when another changes). If those are unfamiliar, skim them: the rule “divide scores by √dk” and the scaled-versus-unscaled explorer below stand on their own.
Assume, as a model, that the components qc and kc are independent random variables with mean 0 and variance 1. Then each product qckc has mean 0 and variance E[qc2]·E[kc2] = 1, and the products are independent of each other, so
The standard deviation of a raw score is √dk, so dividing by √dk brings the variance back to 1 whatever the head width. Vaswani et al. give this argument (Section 3.2.1, footnote 4). Two limits matter: trained projections do not produce independent unit-variance components, so the argument motivates the choice of constant rather than proving anything about a trained model; and scaling reduces one cause of softmax saturation, it does not guarantee stable gradients.
Toy example. With dk = 2, the row for q3 goes from [4, 3, 7] to [2.83, 2.12, 4.95]. At dk = 2 the effect is mild. It becomes decisive at realistic head widths such as 64 or 128.
A larger example. Let dk = 16 and give q entries of ±1. Build each key by copying q and flipping the sign of its first f entries. Each unflipped entry contributes +1 to the dot product and each flipped entry −1, so q · k = 16 − 2f. With f = 4, 6, 8, 10 the raw scores are [8, 4, 0, −4]. Under the independence model above (random ±1 entries have mean 0 and variance 1), a raw score has standard deviation √16 = 4, so these are 2, 1, 0 and −1 standard deviations: typical sizes, not extremes. Scaling gives [2, 1, 0, −1].
Scaled vs unscaled softmax
- What this shows
- The dk = 16 vectors, a side-by-side table of both weight distributions, and the selected distribution as bars.
- Try
- Switch between unscaled and scaled softmax input.
- What to notice
- The ranking never changes. Without scaling, nearly all weight lands on k1 and the slope of that weight with respect to its score collapses.
Assumptions: constructed ±1 vectors with dk = 16 (not from a trained model); a single query row; no mask.
Why saturation matters. The softmax derivative is ∂ai/∂zj = ai(δij − aj), where δij is 1 when i = j and 0 otherwise. When one weight is close to 1, every one of these derivatives is close to 0: small changes to the scores barely move the weights, so little gradient flows back into WQ and WK. In the example the top weight is 0.982 unscaled and 0.644 scaled, and its slope with respect to its own raw score is 0.018 versus 0.057 (the scaled slope includes the chain-rule factor 1/4).
Engineering implication. The scale is a constant, so it costs essentially nothing: kernels multiply it in once, or it is folded into WQ. Some architectures choose a different constant or fold the factor into weight initialisation, so do not assume every model uses exactly 1/√dk at runtime.
2.1.5 Softmax: scores to weights
A row of scores is not yet usable as mixing weights: scores can be negative and do not sum to anything in particular. We want weights that are non-negative, sum to 1, preserve the ordering of the scores and are differentiable. Softmax does this.
Original softmax
Choose row maximum
Numerically stable form
- zj
- Softmax input for key j: the scaled (and, later, masked) score of one query row.
- aj
- Attention weight on key j. Softmax is applied separately to each row of the score matrix.
- m
- Row maximum, subtracted for numerical stability.
Why subtracting m is allowed and needed. ez − m = ez·e−m, and the common factor e−m cancels between numerator and denominator, so the result is identical. Numerically it matters: ez overflows in FP32 for z above about 88.7 and in FP16 above about 11.1. After the shift the largest exponent is e0 = 1 and the denominator is at least 1.
Worked example (query q3). Scaled scores z = [2.83, 2.12, 4.95]; m = 4.95; z − m = [−2.12, −2.83, 0]; exponentials [0.12, 0.059, 1]; their sum 1.179; weights [0.102, 0.05, 0.848]. (Intermediate values are rounded for display; the weights are computed at full precision.)
Three properties follow from the formula. Every weight is strictly positive for finite inputs, so softmax alone never fully ignores a key. Adding the same constant to every score changes nothing. Multiplying all scores by a factor larger than 1 sharpens the distribution, which is exactly the effect 2.1.4 guards against.
Attention-score explorer, continued: softmax
Separate 3-token “animal / was / tired” toy. This table follows the query selected in its score explorer, independently of the main “The sky is” model.
- What this shows
- The same query and keys as the explorer in 2.1.3, carried through scaling, the max shift, exponentials and normalisation, with scores and weights side by side.
- Try
- Change the alternate query row in the technical detail of 2.1.3; this table follows that selection.
- What to notice
- Doubling q doubles every score and makes the weights sharper; the column zj − m is always ≤ 0 with one entry exactly 0.
Change alternate query in the score explorer’s technical detail. Its chosen row is named in the table caption below.
Assumptions: this panel shares its state with the explorer in 2.1.3 (it is one widget with two views); scale 1/√2 because dk = 2; no mask yet.
Engineering implication. Softmax needs the maximum and the sum of a whole row before any weight is final, which makes it a row-wise reduction. Fused attention kernels keep a running maximum and running sum while streaming over blocks of keys (often called online softmax), rescaling partial results when the maximum changes. This is how they avoid storing the full score matrix.
2.1.6 Causal masking
A language model is trained to predict token i + 1 from tokens 1 to i. During training all positions of a sequence are processed in parallel, so without a constraint position i could simply read the token it is supposed to predict. During generation, later tokens do not exist yet. The causal mask enforces the same rule in both cases: position i may attend only to positions j ≤ i.
- M ∈ ℝT×T
- Additive mask: zero on and below the diagonal, −∞ above it. It is not learned.
- A ∈ ℝT×T
- Attention weights; softmax is applied row by row, so each row sums to 1.
Why add −∞ rather than multiply by 0. Multiplying a score by 0 gives a score of 0, and e0 = 1 is a perfectly ordinary positive weight. Adding −∞ gives e−∞ = 0, so the masked key receives exactly zero weight, and the remaining weights are normalised over the visible keys only. Implementations often use a large negative finite number instead of −∞ or skip masked blocks entirely; in floating point the masked exponentials underflow to 0, so the result is the same.
Example. Prepend “The” (toy embedding [0.5, 0.5]) to get the 4-token sequence “The animal was tired”; the other input rows are unchanged from 2.1.2. Without a mask, the row for “was” is [0.084, 0.042, 0.171, 0.703], with most of its weight on the later token “tired”. With the causal mask it becomes [0.284, 0.14, 0.576, 0]: the future key gets exactly 0 and the visible weights grow, in proportion to their exponentials, to fill the gap. The last row, [0.067, 0.095, 0.047, 0.792], is the same in both modes because the last position has no future to hide.
Causal vs bidirectional attention
- What this shows
- The 4×4 scaled score matrix (with the mask added) and the resulting weight matrix A, with row sums.
- Try
- Toggle between causal and bidirectional and compare each row.
- What to notice
- Masked cells show −∞ in the scores and exactly 0, marked ✕, in the weights. Every row still sums to 1. Only the rows that had future positions change.
Assumptions: toy 4-token sequence with invented embeddings and the 2.1.2 matrices; dk = 2; one head. Decoder-only language models use the causal mask in every attention layer; the bidirectional view is shown for comparison and corresponds to encoder models.
Engineering implication. Because row i never uses keys after i, appending a new token never changes the keys, values or outputs of earlier positions. That is precisely why cached K and V stay valid during decoding (Lesson 2.4). The mask also means about half of the T×T score matrix is never needed, and optimised kernels skip fully masked tiles instead of computing and discarding them.
2.1.7 Weighted values: O = AV
The weights say how much to draw from each position; the values say what is drawn. Each output row is the weighted sum of the value rows.
- oi
- Output row for position i, width dv.
- aij
- Weight of query i on key j (row i of A; masked entries are 0).
- vj
- Value row of position j. Shapes: [T, T] × [T, dv] = [T, dv].
Worked example (row “tired”, causal). Weights [0.067, 0.095, 0.047, 0.792]; values [0.5, 0.5], [1, −1], [0, 2], [1, 1]. Contributions ajvj: [0.033, 0.033], [0.095, −0.095], [0, 0.094], [0.792, 0.792]. Their sum is o4 = [0.92, 0.824]. (Contributions are rounded for display; the sum uses full precision.)
The top-weighted position supplies most of the output, but the other three still add [0.128, 0.032]. Because the weights are non-negative and sum to 1, every output row is a convex combination of the visible value rows: a point inside the region they span, pulled toward the heavily weighted ones.
Worked output: tired
Separate causal 4-token toy: “The animal was tired”. This fixed calculation uses the fourth row, “tired”; it is not the main “The sky is” model.
- What this shows
- For one row of the causal 4-token example: each weight, each value vector, each weighted contribution and their sum, plus the full output matrix O.
- Try
- Follow the “tired” weights into all four value contributions and their sum.
- What to notice
- “The” sees only itself, so its output equals its value vector. Later rows blend several values; masked positions contribute nothing.
Assumptions: causal weights from 2.1.6; toy value vectors; dv = 2; one head, so O is the layer's attention output before any output projection.
Engineering implication. AV costs another T2·dv multiply-adds. During decoding, a single new query row must read every cached value row it attends to; that read traffic is a central topic of Lesson 2.5. With several heads, each head produces its own O and the results are concatenated and projected by WO (Lesson 2.2).
2.1.8 The full attention equation
Putting the steps together gives scaled dot-product attention for one head:
Here M is the causal mask for a decoder (all zeros for bidirectional attention), and softmax acts on each row separately. The original paper writes the equation without M and describes masking in the decoder separately; the version above makes the mask explicit.
- Input X [T, dmodel]
- Project: Q, K [T, dk], V [T, dv]
- Scores QKT [T, T]
- Scale ÷ √dk
- Mask + M
- Softmax per row → A [T, T]
- Weighted values AV
- Output O [T, dv]
| Step | Operation | Result shape | Approximate cost |
|---|---|---|---|
| Project | XWQ, XWK, XWV | [T, dk] ×2, [T, dv] | T·dmodel·(2dk + dv) |
| Score | QKT | [T, T] | T2·dk |
| Scale and mask | ÷ √dk, + M | [T, T] | order T2 |
| Softmax | row-wise | [T, T] | order T2 exponentials |
| Mix | AV | [T, dv] | T2·dv |
The projections grow linearly with T; the score and mixing steps grow with T2. For short sequences the projections usually dominate the arithmetic, and for long contexts the T2 terms take over. A causal mask roughly halves the useful work in the T2 steps.
Left out on purpose. Multiple heads and the output projection WO (Lesson 2.2), positional information such as rotary embeddings, residual connections and normalisation, batching, and any learned bias terms. None of these change the core equation above.
References
- Vaswani, A. et al. (2017). Attention Is All You Need. arXiv:1706.03762. Section 3.2 defines scaled dot-product attention and the √dk scale.
- Dao, T. et al. (2022). FlashAttention: Fast and Memory-Efficient Exact Attention with IO-Awareness. arXiv:2205.14135. Mentioned only; not covered in this module.
Knowledge check
Three short questions on the reasoning in this lesson. Each gives an explanation after you check your answer; nothing is scored.