Scaled dot-product attention
From position-to-position scores to a weighted aggregation of values
Lesson objective. Explain and reconstruct one attention row — scores, scaling, masking, softmax, and aggregation — and justify the shapes and normalization of its intermediate quantities.
Lesson skeleton
- Query + Key + Value → Scaled dot-product attention + Attention weights · Compute one query’s weights and aggregate the values
Scaled dot-product attention turns learned compatibility scores between queries and keys into weights, then uses those weights to aggregate values. Softmax exponentiates and normalizes the (scaled, optionally masked) scores into weights over accessible positions; it does not prove semantic relevance or causality.
Verified Concept Architecture: Standard Attention
Attention is not one indivisible operation: it is the sequence scores → scaling → optional mask → softmax → aggregation. Scores compare Q and K; weights are normalized row by row; the output is a weighted combination of V.
First pass: follow the transition from scores to weights, then from weights to the output. Keep these three objects distinct.
Go deeper: the derivation of the scaling factor — why divide by \(\sqrt{d_k}\) and what the argument does not guarantee — is developed in Why scale attention scores?; changing which positions are accessible before softmax is the role of causal masking.
Q, K, V QKᵀ scores Scaling Optional mask Softmax per query Weighted sum of V
The computation at a glance
Five computation steps
For one head, \(Q,K\in\mathbb{R}^{T\times d_k}\) and \(V\in\mathbb{R}^{T\times d_v}\), where \(T\) is the sequence length.
\[ O=\operatorname{softmax}\left(\frac{QK^\top}{\sqrt{d_k}}+M\right)V. \]
The raw scores \(S=QK^\top\), the scaled scores \(S'=S/\sqrt{d_k}\), the masked scores \(S''=S'+M\) and the weights \(A=\operatorname{softmax}(S'')\) all have shape \(T\times T\), as does the optional mask \(M\). With the row-oriented matrix convention used here, row \(i\) corresponds to the query at position \(i\) and column \(j\) to the key at position \(j\): softmax is applied along the key axis, independently for each query. For each query, softmax divides the exponential of each accessible key’s score by the sum of the exponentials over those keys. Finally, \(O=AV\) has shape \(T\times d_v\).
Here \(M\) denotes an additive hard mask: \(M_{ij}=0\) for an allowed query-key pair and \(M_{ij}=-\infty\) for a disallowed pair. If no mask is needed, omit \(M\) (equivalently, use an all-zero matrix). In this computation, the additive mask is applied to scaled scores before softmax. The next lesson, on causal masking, explains how to construct the mask and identify accessible positions.
In the running example “What have the Romans ever done for us?”, follow the final position of the prefix. Its query is compared with the keys at accessible positions, and its weights combine their values. The sum is the head’s output for that position. The causal mask determines which positions are accessible.
1 — Compare queries with keys
The product \(S=QK^\top\) takes two matrices \(Q\) and \(K\) of shape \(T\times d_k\) and yields a matrix \(S\) of shape \(T\times T\). Each row contains one query’s scores against all \(T\) keys.
2 — Scale the scores
Divide each score by \(\sqrt{d_k}\). The input \(S\) and the output \(S'=S/\sqrt{d_k}\) both have shape \(T\times T\).
3 — Exclude inaccessible keys if a mask applies
Add the scaled scores \(S'\) and mask \(M\), both of shape \(T\times T\). In the output \(S''=S'+M\) of the same shape, inaccessible pairs have score \(-\infty\) before normalization.
4 — Turn one query’s scores into weights
Apply \(A=\operatorname{softmax}(S'')\) row by row. The input \(S''\) and output \(A\) have shape \(T\times T\). Each non-empty row is a probability distribution over the positions accessible to its query.
5 — Combine the values with these weights
The product \(O=AV\) takes weights \(A\) of shape \(T\times T\) and values \(V\) of shape \(T\times d_v\). The output \(O\) has shape \(T\times d_v\), with one weighted sum per query.
From the mechanism to the calculation
Follow the final position of the prefix. Its input state supplies the query for this row; the sequence positions supply the keys and values. Attention softmax weights these positions. Later, the softmax applied to the output logits normalizes scores over vocabulary tokens. In the workshop, try the case where the training sequence includes the next target and the causal mask blocks access to it.
Compute the scores, weights, and output on the dedicated practice page.
Optional lab · What happens when you change K, V, or access to a position?
Follow one query q = (1, 1) in a toy head. Both positions A and B are accessible in the starting example. The vectors are chosen for the exercise. Decimals are rounded to three places.
Before changing B, predict what will change in the scores, the weights, and the contributions to the output.
| Measure | Before | After |
|---|---|---|
| Weights A and B | ||
| Output (sum of contributions) |
| Step | A | B |
|---|---|---|
| Key k | (1, 1) | (0, 0) |
| Raw score q · k | 2 | 0 |
| Scaled score (÷ √2) | 1.414 | 0 |
| Score after masking | 1.414 | 0 |
| Weight a (softmax) | 0.804 | 0.196 |
| Value v | (2, 0) | (0, 4) |
| Contribution a × v | (1.609, 0) | (0, 0.782) |
Output (sum of contributions) (1.609, 0.782)
Starting example: weights ≈ (0.804, 0.196), output ≈ (1.609, 0.782).
Show the reasoning
If only vB doubles, the weights stay the same and the second output component doubles. If the keys become identical, both weights are 0.5 and the output becomes (1, 2).
During training, B is the token immediately after A in the observed sequence. What weight does it receive in A's row, and which token do the logits at A predict?
Show the worked answer for the masked case
B's score becomes −∞ before normalization, so its weight is 0. A remains visible and gets weight 1. The head output at A is (2, 0). After the blocks and the output projection, the logits at A predict the token after A, so B. The target B contributes to the loss, while the input representation at B is inaccessible to A's query.
Provenance and purpose
The formulation is presented in Vaswani et al. (2017), Attention Is All You Need, which compares additive and dot-product attention and introduces the scaling factor. It supports efficient matrix computation and naturally fits multi-head mechanisms.
Misconceptions and counterexamples
- “Softmax measures absolute similarity.” No: it produces a distribution relative to the scores in a row. Adding the same constant to every score in a row leaves the weights unchanged.
- “A weight of 0.8 means 80% semantic relevance.” No: it is a weight in this aggregation, conditional on the other scores and learned projections.
Common Fallacy: “An attention weight of 0.95 proves this token is the primary cause of the answer”
Rigorous refutation: The weight \(\alpha_{ij}\) is obtained by applying softmax to the score \(q_i^\top k_j/\sqrt{d_k}\): it expresses a relative weighting among accessible positions, not causality. Before the output projection, position \(j\) contributes the direct aggregation term \(\alpha_{ij}v_j\), whose norm is \(\alpha_{ij}\lVert v_j\rVert\). A high weight therefore does not even guarantee a large-norm aggregation term. Nor is that term the effect on the final prediction: the output projection, residual connections, normalization, and MLP further transform the signal. Establishing causal importance requires an appropriate intervention-based analysis, not merely reading attention weights.
- “The scale factor is an empirical constant with no rationale.” No: it follows from reasoning about dot-product scale; the assumptions are simplified, but the factor addresses a specific numerical issue. The full derivation and numerical simulation are developed in Why scale attention scores?.
Attention and mutual information: an analogy, not an identity
Mutual information between two random variables depends on a joint distribution:
\[ I(X;Y)=H(X)-H(X\mid Y) =\sum_{x,y}p(x,y)\ln\frac{p(x,y)}{p(x)p(y)}. \]
It measures how much observing \(Y\) reduces uncertainty about \(X\). Attention weights, by contrast, are softmax-normalized compatibility coefficients over accessible positions; they depend on the input, queries, keys, and mask, and are used to aggregate the value vectors \(V\). They do not directly measure, in bits, how much information one token provides about another. A row of attention weights is therefore neither a joint distribution over \((X,Y)\) nor an automatic estimator of \(I(X;Y)\).
The analogy can motivate a useful question — which positions contribute to a contextualized representation? — but it is not a mathematical equivalence. A high attention weight does not quantify “how much information” a token provides, nor does it establish statistical dependence or causal importance. An attention map alone does not establish a causal or semantic explanation.
Connections to other concepts
- The derivation of the scaling factor and the numerical variance simulation are developed in Why scale attention scores?.
- Inputs \(Q,K,V\) are explained in queries, keys, and values.
- Excluding future tokens is defined in causal masking.
- Softmax connects to probabilities, but a normalized distribution is not necessarily calibrated.
- The Transformer overview places this computation in the model’s data flow.
Practice
The questions and exercises for this lesson are collected on its dedicated practice page.
Further exploration
Supplementary resources Explore implementation choices and optimizations of attention computation.
Optional Build-path companion
This page belongs to the conceptual Theory / Understand path: it explains the mechanism and its invariants. To see how the primitive is called in a multi-head implementation, optionally consult the Transformer-block walkthrough, which belongs to the Build path, independent of the conceptual path. General axis and dimension conventions are collected in tensors.
Optimized execution (optional deepening)
The mathematical definition of attention does not prescribe how a GPU executes it. FlashAttention preserves exact dense attention while processing blocks and reducing transfers between GPU memory and fast on-chip memory. It should not be confused with sparse attention, which changes the allowed positions. For the mechanism, trade-offs and measurement caveats, see the FlashAttention source review, followed by the PyTorch SDPA documentation and the reproducible benchmark protocol. This hardware optimization is an optional deepening, not an extra stage in the conceptual route.
FlashAttention in pictures (optional deepening)
These diagrams are original pedagogical reconstructions based on the FlashAttention paper and follow-up work; they do not reproduce figures from the newsletter.