11.1 Scaled dot-product attention (forward and backward)
The sequence models of the previous chapter read the source through an RNN: one step per token, and everything the decoder knows about token 3 has passed through every later state. Luong attention already reads the encoder states directly with a dot product. The transformer keeps only that read. Every position attends to every position in one matrix product, so a sequence of length costs dot products but no sequential steps, and the gradient from position 50 to position 3 is one hop instead of 47.
Concepts from other sections (18)
This section uses these ideas. Each has a short definition and a link to the section that explains it in full. Tap a dotted term in the text to preview it.
- Dot product: ; it measures how much two vectors point the same way, and it is zero exactly when they are perpendicular. Read more: Chapter 10: Calculus 3 in Mathematics
- inference engine: software that loads weights, schedules requests, manages the KV cache, and generates tokens (vLLM, SGLang, TensorRT-LLM, llama.cpp). Read more: 20.5 LLM Serving Platforms: How They Work and When to Use Them
- FlashAttention: attention computed tile by tile with an online softmax, so the score matrix is never stored. Read more: 22.5 FlashAttention forward in C
- stable softmax: softmax computed after subtracting the largest logit, so
expnever overflows. Read more: 25.6 Usage policy enforcement - VJP (vector-Jacobian product): , the gradient of ; what reverse mode computes. Read more: 10.2 Jacobians, the multivariable chain rule, and numeric JVP/VJP in Mathematics
- Dropout: randomly zeroing activations during training to approximate an ensemble of subnetworks. Read more: Chapter 2: Deep Learning
- Variance: the expected squared distance from the mean; its square root is the standard deviation. Read more: 13.1 Random variables, expectation, variance, and normal draws by Box-Muller in Mathematics
- Standard deviation: , the typical distance of a random variable from its mean, in the same units as the variable itself. Read more: Chapter 13: Probability and Statistics in Mathematics
- vector-Jacobian product (VJP): the function mapping an output gradient to input gradients without forming the Jacobian. Read more: 6.2 Tensor, broadcasting backward, and no_grad
- PCG32: an LCG whose output is a permutation (xorshift, then a state-chosen rotation) of the old state. Read more: 12.3 Modular arithmetic, hashing, and PCG32 in Python in Mathematics
- op library (
F): the module of differentiable functions, each a NumPy forward plus one closed-form VJP joined byfrom_op. Read more: 6.3 The op library and gradcheck_all - KV cache: per-layer storage of past keys and values, so each decode step processes only the new token. Read more: 21.2 The KV cache, incremental decoding, and generate
- causal mask: the rule ; each position reads itself and the past. Read more: 11.2 Masks: causal, padding, sliding window, additive
- fully masked row: a row whose entries are all ; by contract its softmax is all zeros. Read more: 22.4 Softmax in C: three-pass and online two-pass
- Gradcheck: a comparison of a hand-written gradient against central differences of . Read more: 3.3 Oracles, golden and differential tests, gradcheck as a test in Software Engineering
- central differences: the numerical derivative , used as an oracle for analytic gradients. Read more: 6.3 The op library and gradcheck_all
- online softmax: computing the maximum and the normalizer in one read by rescaling the running sum whenever the maximum grows. Read more: 22.4 Softmax in C: three-pass and online two-pass
- PagedAttention: KV-cache management in fixed-size blocks mapped through a block table, like virtual memory. Read more: Chapter 20: Inference Engines and GPU Deployment
Every model from here on (the 2017 Transformer, GPT, BERT, the modern Llama block, the inference engine’s kernels) is built on this one function. In this section you will derive it, derive its backward pass by hand, and register the whole thing as a single node of the autograd graph instead of seven composed ops. That hand-written backward is also the exact computation that the FlashAttention forward in C and FlashAttention itself reorganize.
This section builds on Tensor, broadcasting backward, and no_grad (the Tensor class and from_op) and on the stable softmax of Stable numerics: logsumexp, softmax, and compensated sums in Mathematics. For the backward it helps to have read Matrix differentials, the trace trick, and closed-form VJPs and the softmax VJP derivation in the matrix calculus problem set; the dropout draw rule comes from The op library and gradcheck_all. The full solution is python/tinyllm/xfmr/sdpa.py (sdpa_forward, sdpa_backward, and scaled_dot_product_attention), its contract is course/contracts/py/tinyllm/xfmr/sdpa.pyi, and the model oracle tests are in test_sdpa.py.
Learning objectives
- Compute by hand and explain why the scale is .
- Derive the backward pass, including the softmax VJP , and show that the row sum equals .
- Implement forward, backward, and attention dropout as one autograd node with the same multiplier in both directions.
- Explain why masking uses before the softmax, and why a fully blocked row gives zeros rather than NaN.
The notation
Section titled “The notation”The whole section uses one set of symbols; the table lists each with its shape.
| Symbol | Meaning | Type / shape |
|---|---|---|
| queries, one row per position asking | [..., Tq, d] | |
| keys, one row per position offering | [..., Tk, d] | |
| values, what each key position contributes | [..., Tk, dv] | |
| query and key width | int | |
(scale) | score scale, default | float |
| scores | [..., Tq, Tk] | |
| mask, True = may attend (see Masks) | bool, broadcast to | |
| weights, each row sums to 1 (over keys) | [..., Tq, Tk] | |
| output | [..., Tq, dv] | |
| gradients of a scalar loss with respect to each | same shapes as their arrays | |
| the row sum in the softmax VJP | [..., Tq, 1] |
Attention as a soft lookup
Section titled “Attention as a soft lookup”A Python dict returns the value whose key equals the query. Attention returns a blend. It scores query against every key by the dot product (large when they point the same way), turns the scores into positive weights that sum to 1 with a softmax over the keys, and averages the values with those weights: . Because the output is a weighted sum over a set of key-value pairs, reordering the pairs changes nothing. Attention has no idea of position, which is why the transformer adds positional encodings. Each query is also computed independently of the others.
Why scale? If the entries of and are independent with mean 0 and variance 1, then is a sum of terms of variance 1, so it has variance . At the scores have standard deviation 8, the softmax is nearly one-hot, and its gradient (which is -shaped) nearly vanishes. Multiplying by brings the variance back to 1 for every width. You can check this empirically: the difference of two scaled scores has variance 2 (each has variance 1) at and at alike.
Masking
Section titled “Masking”A mask blocks query-key pairs, and the next section builds every kind you will need. The mechanism belongs here: set the blocked scores to before the softmax. Then , the blocked weights are exactly 0, and the open weights still sum to 1. Masking after the softmax (multiplying weights by 0/1) leaves rows that no longer sum to 1.
A row with every key blocked is all . The stable softmax defines its weights as zeros, so its output and gradients are zero instead of NaN. The same softmax subtracts each row’s maximum first, so scores of never overflow.
The backward pass
Section titled “The backward pass”With the forward fixed, the backward follows it in reverse. Given , the gradient of the loss with respect to the output, you work back through , then , then . For a matrix product , the vector-Jacobian products are and . So
For one row , , so . Stacked over rows:
Finally gives and . Note the transpose in : is [Tq, Tk] and must be [Tk, d].
One identity is worth knowing: , so the row sum can be computed from the output without storing . FlashAttention’s backward uses exactly this. And because masked positions have , every gradient through them is 0: padding never learns.
Batches and heads
Section titled “Batches and heads”Every leading dimension is an independent problem. An input of shape [B, H, T, d] is separate attentions, and numpy’s @ broadcasts over them. Multi-head attention reshapes [B, T, d_model] into heads and calls this function once.
Attention dropout
Section titled “Attention dropout”During training, the 2017 Transformer drops attention weights. Draw one uniform per weight (in C order, from the PCG32 the caller passes, the same rule as the op library’s dropout), keep where , and scale the kept ones by so the expected weight is unchanged: with .
The backward must use the same : and , and the softmax VJP is unchanged. The function returns before dropout, as a constant. The weights are for inspection (heat maps, the KV cache), and gradients flow through only.
Working it by hand
Section titled “Working it by hand”Now put numbers through every formula. Take one query, three keys, and , so . The query is ; the keys are , , ; the values are , , . The forward pass is three steps:
| Step | Computation | Value |
|---|---|---|
| , | ||
The backward with follows the derivation line by line:
| Step | Computation | Value |
|---|---|---|
| : row is | , , | |
| , which is | ||
| : row is | , , |
The third key scored highest and gets most of the weight. Raising its score further (moving toward it) raises , which is why . Notice also that is exactly , the identity from the derivation. A correct implementation reproduces both tables.
Designing the API
Section titled “Designing the API”The design has three functions: a numpy forward and backward that other code (the C kernel’s tests, the KV cache) can call directly, and a Tensor-level wrapper that adds dropout and registers the node.
def sdpa_forward(q, k, v, mask=None, scale=None) -> tuple[NDArray, NDArray]: ... # (O, P)def sdpa_backward(q, k, v, p, dout, scale=None, dropout_mult=None) -> tuple[NDArray, NDArray, NDArray]: ...def scaled_dot_product_attention(q: Tensor, k: Tensor, v: Tensor, mask=None, dropout_p=0.0, scale=None, rng=None) -> tuple[Tensor, Tensor]: ... # (out, weights)scaled_dot_product_attention computes the forward with sdpa_forward, applies dropout if asked, and returns from_op(out, [q, k, v], vjp) whose vjp is sdpa_backward: one node of the graph. Masks are bool (True = may attend) and must broadcast to the scores without changing their shape. float32 inputs stay float32.
Building it step by step
Section titled “Building it step by step”Before the code, here is the reasoning chain that forces each choice.
- A soft lookup is a softmax over keys followed by a weighted sum of values. Similarity is a dot product, so all scores are one matrix product , and all outputs another, . Every leading axis is a batch axis.
- The scale is forced by variance. A dot product of unit-variance terms has variance ; multiplying by restores variance 1 at every width. A caller may override it (some models fold it into ), but it must be positive and finite.
- Masks act on scores, with . Only then are blocked weights exactly 0 and open weights still sum to 1; a fully blocked row follows the stable softmax’s convention (zeros). A mask may broadcast (one
[Tq, Tk]causal mask for every batch and head), but it must not grow the scores’ shape, which would silently change the output shape. - The backward follows the forward in reverse, one VJP per line. , , , , . The worked example confirms it: .
- One autograd node, not seven. Writing the backward by hand and registering it with
from_opstores only and gives the exact computation that fused kernels reorganize. - Dropout is a fixed multiplier on . The forward uses ; the backward must use the same on both and . The softmax VJP is applied to the undropped , because sits after the softmax.
- The returned weights are for inspection. They are before dropout and are wrapped as a constant Tensor, so no gradient path runs through them.
The forward
Section titled “The forward”The forward is plain numpy, so the C kernel’s tests and the KV cache can call it directly:
def sdpa_forward(q, k, v, mask=None, scale=None): qa, ka, va = _float(q, "q"), _float(k, "k"), _float(v, "v") # ints -> float64; float32 stays _check(qa, ka, va) # same leading dims, q/k widths, k/v lengths # S = alpha Q K^T, the scale cast to q's dtype so float32 stays float32. s = (qa @ _t(ka)) * qa.dtype.type(_scale(scale, qa.shape[-1])) if mask is not None: m = np.asarray(mask) if m.dtype != np.bool_: raise ValueError(f"mask must be bool (True = may attend), got {m.dtype}") # ... (the mask must broadcast to s without changing s's shape) s = np.where(m, s, s.dtype.type(-np.inf)) # Softmax over the KEYS (the last axis): each query's weights sum to 1; # a row with every key masked is all zeros (stable softmax), never NaN. p = softmax(s, axis=-1) return p @ va, p_t swaps the last two axes, so qa @ _t(ka) is for any number of leading axes. _scale(None, d) is 1.0 / math.sqrt(d); an explicit scale must be finite and positive.
The backward
Section titled “The backward”The backward matches the derivation line for line:
def sdpa_backward(q, k, v, p, dout, scale=None, dropout_mult=None): qa, ka, va = _float(q, "q"), _float(k, "k"), _float(v, "v") _check(qa, ka, va) pa, g = np.asarray(p), np.asarray(dout) # ... (p must be [..., Tq, Tk] and dout [..., Tq, dv]) s = _scale(scale, qa.shape[-1]) pd = pa if dropout_mult is None else pa * dropout_mult # the P the forward actually used dv = _t(pd) @ g # dV = (P o m)^T dO dp = g @ _t(va) # dP = dO V^T ... if dropout_mult is not None: dp = dp * dropout_mult # ... o m, back through the dropout # Softmax VJP: dS = P * (dP - sum_j P_j dP_j), row by row. ds = pa * (dp - np.sum(dp * pa, axis=-1, keepdims=True)) dq = (ds @ ka) * s # dQ = alpha dS K dk = (_t(ds) @ qa) * s # dK = alpha dS^T Q (note the transpose) return dq.astype(qa.dtype), dk.astype(ka.dtype), dv.astype(va.dtype)Masked positions have , so ds is 0 there and dq, dk receive nothing from them; the dv rows of masked keys are 0 for the same reason.
The autograd wrapper
Section titled “The autograd wrapper”The wrapper adds dropout and registers the node:
def scaled_dot_product_attention(q, k, v, mask=None, dropout_p=0.0, scale=None, rng=None): qt, kt, vt = (x if isinstance(x, Tensor) else Tensor(x, dtype=np.asarray(x).dtype) for x in (q, k, v)) # ... (dropout_p in [0, 1]; an rng is required when dropout_p > 0) out, p = sdpa_forward(qt.data, kt.data, vt.data, mask, scale) mult = None if dropout_p > 0.0: u = np.asarray(rng.uniforms(p.size)).reshape(p.shape) # one uniform per weight, C order keep = u >= dropout_p mult = (np.zeros_like(p) if dropout_p == 1.0 else (keep / (1.0 - dropout_p)).astype(p.dtype)) # inverted dropout out = (p * mult) @ vt.data # dropout_p == 0 draws nothing, so adding the option never shifts the rng stream.
def vjp(g): return sdpa_backward(qt.data, kt.data, vt.data, p, g, scale, mult)
res = from_op(out.astype(qt.dtype), [qt, kt, vt], vjp, op="scaled_dot_product_attention") return res, Tensor(p, dtype=p.dtype) # weights: a constant, before dropoutThe closure captures p and mult, which is exactly the state the backward needs; nothing else from the forward is kept. The full solution is sdpa.py.
Why this design
Section titled “Why this design”Forward and backward each cost time per batch-head, and memory is for , kept for the backward. That quadratic memory is what FlashAttention removes by recomputing in tiles from saved row statistics.
You could instead compose matmul, masked_fill, and softmax from the op library. The composed graph would be correct, but it would store every intermediate and create seven nodes per call. The hand backward stores only , and it is the reference the C kernel is tested against.
Why compute as sum(dp * pa) and not as ? They are equal, with or without dropout (with dropout and carries the same ). Here is already materialized, so the direct row sum is simplest. FlashAttention uses because it never holds a full row of at once.
Why rather than a large negative number? A finite fill makes a fully masked row uniform over padding instead of zero. And why return the weights before dropout and detached? They are for heat maps and caches; making them a gradient path would let an inspection call change training.
What can go wrong
Section titled “What can go wrong”A correct implementation has to survive a specific list of checks, and each one guards something later chapters rely on. The hand example pins down the definition (forward) and the hand backward (, , , ). Against torch, the output, weights, and float64 gradients must match on five cases (cross attention, causal, padding, custom scale, 3-D); multi-head attention builds its own torch comparison on this. In float32, inputs stay float32 and agree within the reduction bound, since models train in float32. A float64 gradcheck compares every gradient element against central differences, with masks, and a second gradcheck replays a fixed dropout mask so training-mode gradients are covered too.
Several properties follow from the math. Permuting keys and values together permutes only the weights’ columns (key permutation equivariance, the reason positions must be added). Permuted or single queries give the same rows, which is what lets the KV cache decode one query at a time. A batched [B, H, T, d] call equals separate 2-D calls, gradients included.
At the boundaries, blocked keys get weights and gradients of exactly 0 while rows still sum to 1; a fully masked row gives zeros, never NaN (empty sequences in a batch); and scores of give a clean one-hot rather than overflowing. The default scale must equal explicitly, and scaled score differences must have variance 2 at both and . Dropout must draw one uniform per weight, keep , scale by , and draw nothing at , so it shares a stream with the op library’s dropout. The returned out requires grad and weights does not. Finally, mismatched shapes, float masks, a bad scale, a bad dropout rate, and dropout without an rng must all raise, so wiring bugs fail loudly.
The model suite test_sdpa.py uses the formula written out in numpy as its oracle (scores, masked softmax, weighted sum, in float64); the worked numbers, every mask kind, and a custom scale are checked against it. For the backward, central differences of sum(oracle(q, k, v) * g) are compared with the gradients of the Tensor op and of sdpa_backward, with and without dropout (the same uniforms are replayed for the oracle’s mask). It imports only contract modules.
The common mistakes are worth listing with their symptoms, because each produces a model that runs but is subtly wrong:
| Pitfall | Symptom | How the solution avoids it |
|---|---|---|
| scaling by instead of | flat attention that sharpens with width; torch disagrees | _scale returns 1.0 / math.sqrt(d) by default |
| the softmax over the query axis | columns sum to 1 instead of rows | softmax(s, axis=-1): the key axis |
| masking after the softmax | rows sum to less than 1 | np.where(m, s, -inf) on the scores, then the softmax |
| the softmax VJP without the term | gradients of a sum-to-one output that do not sum to 0 | ds = pa * (dp - np.sum(dp * pa, axis=-1, keepdims=True)) |
| without the transpose | a shape error for , wrong values otherwise | dk = (_t(ds) @ qa) * s |
| forgetting the scale in | gradients times too large | both dq and dk are multiplied by s |
| a backward that ignores the dropout mask | training gradients of a different function | the vjp passes mult to sdpa_backward, which applies it to both dv and dp |
| keeping | drops the wrong of the weights | keep = u >= dropout_p |
| masking with | a fully masked row attends uniformly to padding | masks with -np.inf; the stable softmax maps an all- row to zeros |
Warning: the last pitfall is the hardest to notice. A finite fill such as looks equivalent to on every row that has at least one open key; it only differs on fully masked rows, where it silently averages over padding.
Where this leads
Section titled “Where this leads”This function is the first piece of the 2017 transformer and is called everywhere after it. The masks of the next section are what you pass as mask. Multi-head attention calls it once per layer on [B, H, T, d_head]. In the modern block, MQA/GQA attention shares keys and values across heads and multi-head latent attention reconstructs them from a small cache. The KV cache runs one step’s queries against cached keys with q_offset masks, and the FlashAttention forward in C (online softmax, tiled) is tested against sdpa_forward. The vision transformer calls scaled_dot_product_attention on 2D-rotated heads, and Whisper decoding calls it through its declared contract.
Each piece also has a production equivalent worth reading:
| This piece | Production equivalent | What it adds | Where to look |
|---|---|---|---|
sdpa_forward | torch.nn.functional.scaled_dot_product_attention | dispatch to fused kernels (Flash, memory-efficient, math) by shape and device | aten/src/ATen/native/transformers/attention.cpp |
sdpa_backward | FlashAttention-2 backward | recomputes tile by tile from saved row statistics instead of storing it; | flash_attn/flash_attn_triton.py, Dao (2023) |
| the softmax over all keys | the online softmax | one pass over the keys with a running max and sum, the basis of the C FlashAttention kernel | Milakov and Gimelshein, “Online normalizer calculation for softmax” (2018) |
scaled_dot_product_attention | vLLM PagedAttention | keys and values in fixed-size blocks of a shared pool (see the paged KV cache) | vllm/attention/ |
Further reading
Section titled “Further reading”- Vaswani et al., “Attention Is All You Need” (2017), section 3.2.1.
- Dao et al., “FlashAttention” (2022), section 3.1 and appendix B.2 (the backward with ).
Key terms
Section titled “Key terms”- scaled dot-product attention: , a weighted average of values with weights from query-key similarity.
- score scale: the factor , by default , that keeps score variance at 1 whatever the width.
- softmax VJP: with , the backward of a row-wise softmax.
- attention dropout: an inverted-dropout multiplier applied to after the softmax, reused unchanged in the backward.
- permutation equivariance: permuting key-value pairs permutes only the weight columns and leaves the output unchanged.
Summary
Section titled “Summary”- Attention is a soft dictionary lookup: , a weighted average of values with weights from query-key similarity.
- The keeps the scores’ variance at 1 whatever the width, so the softmax neither saturates nor flattens.
- The backward is four matrix products and the softmax VJP , and that row sum equals .
- Attention is equivariant to permuting keys with their values: it has no notion of order.
- Blocked keys get weight and gradient exactly 0, and a fully blocked row is zeros, never NaN.
Review questions
Section titled “Review questions”- Why is the default scale and not ?
Answer
The variance of $q \cdot k$ grows as $d$, so its standard deviation grows as $\sqrt{d}$. Dividing by $\sqrt{d}$ restores unit variance; dividing by $d$ would shrink the scores toward 0 as width grows and flatten the softmax. - In the worked example, why is ‘s sum zero, and which line of the code guarantees it?
Answer
$\sum_k dS_k = \sum_k P_k (dP_k - D) = D - D \cdot 1 = 0$, since the weights sum to 1: moving all scores by a constant cannot change a softmax. The `- np.sum(dp * pa, ...)` term in `ds` is what makes it hold. - Why does
dkuse_t(ds) @ qawhiledqusesds @ ka?Answer
$S = \alpha Q K^\top$ is `[Tq, Tk]`. $dQ$ must be `[Tq, d]`, which is $dS\,K$; $dK$ must be `[Tk, d]`, which needs $dS^\top Q$. Without the transpose the shapes only match when $T_q = T_k$, and the values are wrong. - With dropout, why is the softmax VJP applied to
paand notpd?Answer
The dropout multiplier comes after the softmax: $O = (P \circ m)V$. The chain rule goes through $m$ first (`dp * dropout_mult`), then through the softmax, whose Jacobian depends on the undropped $P$. - Why must a mask be rejected if it would change the scores’ shape?
Answer
Broadcasting a larger mask would make `np.where` return a larger array, so the output would gain axes the caller never asked for. Rejecting it turns a silent shape bug into an error.