Naive and tiled attention in CUDA via load_inline
Colab T4 · freenotebook240 minrequiredGoal · Build two CUDA attention kernels callable from PyTorch and show the tiled online-softmax version uses O(N) extra memory and runs faster at N=4096.
- 1In a Colab T4 notebook, confirm nvcc is available and write a hello-world kernel with torch.utils.cpp_extension.load_inline.
- 2Implement naive_attention where each thread computes one query row by writing scores to global memory, then softmax, then the weighted sum.
- 3Verify against F.scaled_dot_product_attention for batch 1, heads 8, N in (128, 1024), d 64, fp32, with atol 1e-4.
- 4Implement flash_attention_fwd with BLOCK_M query tiles and a loop over BLOCK_N KV tiles in shared memory, maintaining running max m, sum l and output accumulator O per row.
- 5Verify at N 4096 and record torch.cuda.max_memory_allocated for both kernels.
- 6Time both kernels and SDPA at N in (512, 1024, 2048, 4096) with CUDA events; plot latency versus N.
- 7Add causal masking as a flag and re-verify.
- Deliverable
- Notebook with both kernels, correctness asserts, memory numbers and the latency plot.
- Check
- The tiled kernel's peak memory does not grow quadratically with N (less than 2x from 2048 to 4096) and it is faster than the naive kernel at N 4096.
- Fallback
- Write the same two kernels in Triton following tutorial 06 if nvcc compilation in Colab fails; the memory and speed checks are identical.