Standard attention keeps the probability matrix (and, with dropout, the dropout mask) in HBM for the backward pass. FlashAttention keeps only the output , two statistics per row, and the seed of the random number generator, and rebuilds every block of and of the mask on chip when the gradients need them. Implement that backward pass in NumPy.
The forward pass these inputs came from. and is the softmax scale (default ):
where is the elementwise product and is the dropout mask. The matrix is cut into blocks of query rows and key columns; block covers rows and columns (the last blocks may be shorter), and its part of is block_dropout_mask(seed, i, j, rows, cols, p_drop).
block_dropout_mask(seed, i, j, rows, cols, p_drop): draw u = np.random.default_rng([seed, i, j]).random((rows, cols)) and return the float array that is where u >= p_drop and elsewhere.
flash_backward(Q, K, V, O, dO, l, m, Br, Bc, tau=None, p_drop=0.0, seed=0): dO is for some scalar loss ; l and m are the forward statistics above. Return a dict with the arrays "dQ", "dK", "dV" of shape (N, d): the gradients of with respect to , and .
Work block by block: loop over key/value blocks, and inside over query blocks, rebuilding each block of from l and m and each block of from the seed. Do not form any array.
p_drop = 0 means no dropout: every mask entry is .