Tiled attention with online softmax in numpy
CPU · your Macnotebook120 minrequiredGoal · Implement block-tiled attention that never materializes the full score matrix, prove it matches the reference, and count the bytes each version touches.
- 1Write reference_attention(Q, K, V) in numpy that forms the full N x N softmax matrix; use N=1024, d=64, float32.
- 2Write online_softmax(row_blocks) that processes a row in chunks keeping running max m and running sum l; verify against np.softmax on random rows.
- 3Write flash_attention(Q, K, V, block_q, block_k) with an outer loop over K/V blocks and an inner loop over Q blocks, rescaling the partial output when the max changes.
- 4Assert np.allclose(flash, reference, atol=1e-5) for several block sizes including ones that do not divide N evenly.
- 5Instrument both versions with a byte counter that adds the size of every array read or written to the "HBM" (anything outside the current tile) and print the totals.
- 6Plot bytes moved versus N for N in [256, 512, 1024, 2048] for both versions on a log scale.
- Deliverable
- A notebook with both implementations, the allclose assertion and the bytes-versus-N plot.
- Check
- allclose passes for all block sizes; naive bytes grow as N^2 while tiled bytes grow linearly in N.