Backpropagate through scaled dot-product attention
Why it matters FlashAttention's backward kernel computes exactly these five matmuls tile by tile.
Writing attention's backward pass by hand is the core of FlashAttention-style kernels.
Write attention_backward(Q, K, V, dO). Q, K, V are (T, d) (single head, no mask). Forward: S = Q K^T / sqrt(d), P = softmax(S) by rows, O = P V. Return (dQ, dK, dV) given dO of shape (T, d).
def attention_backward(Q, K, V, dO)Example
if dO is all zeros, every gradient is all zeros.
Understand the idea
Attention's forward pass is S = Q K^T / sqrt(d), P = softmax of each row of S, O = P V. The backward pass walks these steps in reverse. The tricky piece is the softmax: changing one score changes every probability in its row, which gives a row-wise correction term. Worked example with T = 1, d = 1: Q = [[2]], K = [[3]], V = [[5]], dO = [[1]]. P = [[1]] because a single score always gets probability 1. dV = P^T dO = 1. dP = dO V^T = 5. The row term D = sum(dP * P) = 5, so dS = P * (dP - D) = 0, and therefore dQ = dK = 0. Rule: dV = P^T dO; dP = dO V^T; D = row sums of (dP * P); dS = P * (dP - D); dQ = dS K / sqrt(d); dK = dS^T Q / sqrt(d). Dropping the D term is the classic mistake. Check your answer against finite differences on a random small input. Used in: FlashAttention style kernels, which store D per row and recompute P during backward.
Shapes and data flow
S, P (T, T); O (T, d) dV = P^T dO (T, d); dP = dO V^T (T, T) dS (T, T) -> dQ = dS K, dK = dS^T Q (scaled)