Build your own fused attention kernel in CUDA
Colab T4 · free~8 hWrite one CUDA kernel that computes causal scaled dot-product attention for GPT-2 shapes (12 heads, head_dim 64, sequences up to 1024) without ever materialising the S x S score matrix. Tile over keys, keep a running max and sum in registers (online softmax), accumulate the output in fp32, bind it with load_inline, and prove it matches torch F.scaled_dot_product_attention while timing it. It proves the phase because thread mapping, shared-memory tiling, warp reductions, coalesced loads and roofline reasoning all have to be right in a single kernel you can explain line by line.
Scope
- A naive three-kernel attention (QK^T GEMM, row softmax, PV GEMM) in CUDA first, kept as the correctness and speed baseline.
- The fused kernel, one block per (batch, head, 64-query tile), K and V tiles of 64 keys staged in shared memory, online softmax with rescaling, causal masking that skips fully masked tiles.
- A load_inline binding with shape, dtype and contiguity checks and a Python wrapper fused_attention(q, k, v, causal=True).
- pytest comparing against SDPA for batch 1-8, 12 heads, seq 128, 512 and 1024, head_dim 64, with fp32 and fp16 inputs.
- bench.py timing your kernel against the naive version and SDPA (default and math backends) with torch.cuda.Event, plus peak memory via torch.cuda.max_memory_allocated.
- One ncu Speed of Light row for your kernel at seq 1024, or event-derived FLOP/s and GB/s if ncu is blocked on Colab.
Out of scope
- The backward pass or anything training-related.
- A tensor-core (WMMA) path; fp32 FMA is the target, tensor cores are a stretch.
- Variable-length batches or paged KV (Phase 3).
What to measure
- Numerical agreement with SDPA
- How · max abs diff over 20 random inputs per shape, SDPA forced to the math backend for the reference
- Target · below 1e-4 with fp32 inputs, below 1e-2 with fp16 inputs
- Speed versus SDPA at batch 4, 12 heads, seq 1024
- How · median of 50 iterations after 10 warm-ups with torch.cuda.Event
- Target · within 3x of SDPA's default backend on a T4 and at least 1.5x faster than your naive three-kernel version
- Extra memory during the call
- How · max_memory_allocated minus the bytes of q, k, v and the output
- Target · under 1 MB at seq 1024, while the naive version allocates batch x heads x 1024 x 1024 x 4 bytes (192 MB at batch 4)
- Achieved FLOP/s
- How · 2 x B x H x S x S x D (causal, counting QK^T and PV, halved for the mask) divided by time
- Target · report; T4 note: FP32 FMA peak is 8.1 TFLOPS and Colab T4s sustain about 5-6 TFLOPS under the 70 W cap, a first fused kernel typically lands at 1-2 TFLOPS
- Scaling with sequence length
- How · time at seq 128, 256, 512 and 1024, log-log slope
- Target · slope between 1.7 and 2.2, and the speed-up over the naive version grows with S
Pay attention to
- Online softmax rescaling. When the running max changes, both the running sum and the accumulated output must be multiplied by exp(m_old - m_new); forgetting the output rescale passes short tests and fails at seq 1024.
- Causal masking must skip whole key tiles above the diagonal and apply -inf inside the diagonal tile; compare against SDPA with is_causal=True, not a hand-built mask of zeros, and check that the first 128 outputs are identical whether S is 128 or 1024.
- Scale by 1/sqrt(d) before the exp and keep max and sum in fp32; an fp16 running sum overflows on long rows.
- __syncthreads placement between loading the next K/V tile and reading it; double buffering without a barrier races and only shows up as sporadic mismatches.
- Timing hygiene. Synchronise, warm up, exclude the load_inline compile, and report the median, not the mean.
Acceptance (all must pass)
- ☐pytest passes the agreement test for every listed shape in fp32 and fp16.
- ☐The causality check passes (first 128 query outputs identical at S = 128 and S = 1024).
- ☐README has a bench table with your kernel, the naive version, SDPA default and SDPA math at four sequence lengths.
- ☐The memory measurement confirms no S x S intermediate.
- ☐README contains a roofline sketch placing the kernel at seq 1024 on the T4 and states whether it is compute- or memory-bound with the ncu or event numbers that justify it.