Backward pass of scaled dot-product attention
This page derives the adjoint that scaledDotProductAttentionBackward
(DefaultExecutionTape.kt) implements, and states how each option of
TensorOps.scaledDotProductAttention enters it. The formulas are checked against
PyTorch autograd by scripts/reference/sdpa_backward_check.py; the Kotlin implementation is
checked by SdpaBackwardTest.
Forward
For one batch row and one head, let \(Q \in \mathbb{R}^{n \times d}\) hold the \(n\) queries and \(K, V \in \mathbb{R}^{m \times d}\) the \(m\) keys and values:
\(s\) is the scale and \(M \in \mathbb{R}^{n \times m}\) the sum of all additive masks. \(S\) and \(P\) are \(n \times m\); \(O\) is \(n \times d\).
Derivation
Write \(\bar X\) for the gradient of the loss with respect to \(X\). \(\bar O\) comes from the layers above. The three steps of the forward are undone in reverse order.
Step 3, \(O = PV\). A matrix product \(C = AB\) has \(\bar A = \bar C B^\top\) and \(\bar B = A^\top \bar C\):
Step 2, the row-wise softmax. For one row, \(\partial P_j / \partial S_l = P_j(\delta_{jl} - P_l)\), so
or, with \(\odot\) the element-wise product and the row sum broadcast over the row,
Step 1, \(S = s\,QK^\top + M\). The product rule of step 3 again, and the identity for the added mask:
Each row of \(\bar S\) sums to zero, because adding a constant to a row of \(S\) does not change its softmax.
How each option of the forward enters
| Option | Effect on the backward |
|---|---|
|
A constant. |
|
Query \(q\) attends to keys \(k \le m - n + q\) (the last query is aligned with the last key). The rule adds the constant |
|
Query \(q\) attends to keys \(m - n + q - w + 1 \le k \le m - n + q + r\). The same mechanism as |
|
Row \(b\) attends to keys \(k < \text{length}_b\). Again a constant mask. A padded key has \(P = 0\) in its whole column, so its rows of \(\bar K\) and \(\bar V\) are exactly zero. The lengths are integers and get no gradient. |
Several rules |
Their key sets intersect; the masks add. Nothing changes in the formulas. |
Dense |
A real input, added to \(S\), so it has the gradient \(\bar M = \bar S\). The mask is broadcast to |
Grouped-query attention |
Key/value head \(g\) serves the query heads \(g \cdot r, \dots, g \cdot r + r - 1\) with \(r = \text{heads} / \text{kvHeads}\). Each of those heads uses the formulas above with the same \(K\) and \(V\); the gradient of the shared \(K\) and \(V\) is the sum of the \(r\) per-head results. |
KV-cache decode step |
\(n = 1\) and \(m\) = number of cached keys. No special case: the alignment \(m - n + q\) places the single query at the last key, so a causal step attends to the whole cache. |
Masked scores have exactly zero probability in floating point, not just a small one: \(e^{-10^{30} - \max}\) underflows to zero. That is why the gradients at masked positions are exactly zero and not merely small. It requires that the row has at least one attended key; see A row with no attended key.
Memory: \(P\) is recomputed
The formulas need \(P\), which is [batch, heads, seqQ, seqKV] and by far the largest
intermediate. The implementation does not keep it from the forward pass; it recomputes
\(S\) and \(P\) from \(Q\), \(K\) and the mask rules in the backward. That costs one
more \(Q K^\top\) and softmax and saves storing a quadratic tensor per attention layer for
the lifetime of the tape. FlashAttention makes the same trade: its backward pass recomputes
the attention matrix from \(Q\) and \(K\) instead of storing it (Dao et al., 2022).
A row with no attended key
If the rules leave a query row without any key (for example keyLengths[b] = 0), every score
of that row is \(-10^{30}\). The softmax of a constant row is uniform, so the forward
returns the mean of all value rows, padded ones included, and the result stays finite.
For such a row the formulas above describe the derivative of the definition, but not of what the CPU kernel computes. The kernel never evaluates the scores of a masked position, so its output does not depend on \(Q\), \(K\) or the dense mask for an empty row; the true gradient is zero. Evaluated literally, \(S = s\,QK^\top + M\) gives a uniform \(P\) and a non-zero \(\bar Q\) and \(\bar K\). The backward therefore sets \(\bar S\) of an empty row to zero (#1572). \(\bar V\) keeps the uniform weights, consistent with the forward.
Numerical check
scripts/reference/sdpa_backward_check.py evaluates the formulas in float64 and compares them
with torch.autograd.grad of \(\sum (O \odot W)\) for a random \(W\). Where PyTorch has the
same option, the forward is also compared with
torch.nn.functional.scaled_dot_product_attention. Output with PyTorch 2.4.1:
plain max |hand - autograd| = 0.0e+00 forward vs torch 2.2e-16 custom scale 0.5 max |hand - autograd| = 0.0e+00 forward vs torch 2.2e-16 causal max |hand - autograd| = 0.0e+00 forward vs torch 2.2e-16 causal decode step (1 query, 5 cached keys) max |hand - autograd| = 1.1e-16 forward vs torch 1.1e-16 key padding, lengths [4, 2] max |hand - autograd| = 0.0e+00 gradient of padded keys 0.0e+00 sliding window 2 max |hand - autograd| = 0.0e+00 sliding window 2, right context 1 max |hand - autograd| = 0.0e+00 causal + window 3 + lengths [5, 3] max |hand - autograd| = 0.0e+00 gradient of padded keys 0.0e+00 dense mask [1, 1, seqQ, seqKV] max |hand - autograd| = 2.2e-16 dense mask [batch, heads, seqQ, seqKV] max |hand - autograd| = 0.0e+00 grouped query, 4 heads on 2 K/V heads max |hand - autograd| = 0.0e+00 forward vs torch 2.8e-16 grouped query + causal + scale 0.5 max |hand - autograd| = 0.0e+00 grouped query + dense mask per K/V head max |hand - autograd| = 0.0e+00 fully masked row, lengths [3, 0] max |hand - autograd| = 0.0e+00 gradient of padded keys 6.5e-01 fully masked row: |dQ| of that row = 2.6e-01 (not zero, see the note)
Formulas and autograd perform the same floating-point operations in the same order, which is why most differences are exactly zero.
SdpaBackwardTest checks the Kotlin implementation: every option above against central finite
differences, and three cases (plain, causal, grouped-query with causal mask and custom scale)
against gradients exported from PyTorch.
References
-
Vaswani, A. et al. (2017). Attention Is All You Need. arXiv:1706.03762 — definition of scaled dot-product attention and the \(1/\sqrt{d}\) scale (section 3.2.1).
-
Dao, T. et al. (2022). FlashAttention: Fast and Memory-Efficient Exact Attention with IO-Awareness. arXiv:2205.14135 — backward pass that recomputes the attention matrix instead of storing it.
-
Dao, T. (2023). FlashAttention-2: Faster Attention with Better Parallelism and Work Partitioning. arXiv:2307.08691 — the same backward in a simpler form.
-
Ainslie, J. et al. (2023). GQA: Training Generalized Multi-Query Transformer Models from Multi-Head Checkpoints. arXiv:2305.13245 — grouped-query attention.
-
torch.nn.functional.scaled_dot_product_attention— PyTorch documentation