Compute dK and dV tile by tile from the saved log-sum-exp
Why it matters Memory-efficient attention training relies on this backward recipe, which keeps memory linear in sequence length instead of quadratic.
The memory-efficient attention backward pass never stores the attention matrix. It saves only the row log-sum-exp from the forward pass, recomputes P one key tile at a time, and uses D = rowsum(dO * O) to get the softmax gradient.
Write flash_backward_kv(Q, K, V, O, dO, lse, block). Q, O, dO are (Tq, d); K, V are (Tk, d); lse is (Tq,) with lse[i] = log sum_j exp(S[i, j]) where S = Q K^T / sqrt(d) (no mask). Compute D = rowsum(dO * O) once. Then for each key tile of block rows: S_t = Q K_t^T / sqrt(d), P_t = exp(S_t - lse[:, None]), dV_t = P_t^T dO, dP_t = dO V_t^T, dS_t = P_t * (dP_t - D[:, None]), dK_t = dS_t^T Q / sqrt(d). Return (dK, dV) with shapes (Tk, d).
def flash_backward_kv(Q, K, V, O, dO, lse, block)Example
Q [[1, 0]], K [[1, 0], [0, 1]], V [[1, 2], [3, 4]], dO [[1, 0]], block 1, with O and lse from the forward pass, gives dK [[-0.3128, 0], [0.3128, 0]] and dV [[0.6698, 0], [0.3302, 0]] (rounded to 4 places).
Understand the idea
The backward pass of softmax needs, for every query row, a sum over all keys of P times dP. That sounds like it needs the whole attention matrix, but there is a shortcut: since O = P V, the sum over keys of P[i, j] dP[i, j] equals the dot product of dO[i] and O[i]. So one number per query, D[i], replaces a full row sum. Worked example: one query with P = [0.67, 0.33], V rows [1, 2] and [3, 4], dO = [1, 0]. O = [1.66, 2.66], so D = 1.66. dP = dO V^T = [1, 3]. dS = P (dP - D) = [0.67 x -0.66, 0.33 x 1.34] = [-0.44, 0.44]. Rule: P_t = exp(S_t - lse), dV_t = P_t^T dO, dS_t = P_t (dP_t - D), dK_t = dS_t^T Q / sqrt(d). Each key tile is then independent, so it runs in parallel without storing the matrix.
Shapes and data flow
Q (Tq, d) K_t, V_t (b, d) P_t (Tq, b) dV_t = P_t^T dO (b, d) dS_t (Tq, b) dK_t = dS_t^T Q (b, d)