Unit 1 of 10 · about 5 hours · derive
Attention shapes, prefill and decode reuse, and materialized traffic
The score matrix is often larger than the inputs. Its shape explains what tiling removes and why a prefill schedule need not work well for decode.
You'll be able to
- Derive attention shapes and leading matrix-multiply FLOPs for prefill and single-token decode.
- Count score and probability storage separately from reads and writes.
- Explain why decode has less query-side reuse without declaring it bandwidth-bound from shape alone.
Covers
Read
In this order, only the parts listed
0 of 2 done
- FlashAttention, arXiv:2205.14135v2FlashAttention
Section 2.2, Standard Attention Implementation, and Algorithm 0 (p. 4)
- FlashInfer decode shape and layout contractFlashInfer
Commit f2794d5,
single_decode_with_kv_cachedocstring:q,k,v,kv_layoutanduse_tensor_coresparametersRead the parameter contracts only. Do not implement the production dispatch yet.
Focus on
- For batch size , query heads , query length , key length and equal key/value head width , scores have shape . Attention is , with softmax over keys.
- Count the two dense matrix products as FLOPs, counting each multiply-add as two. Scaling, masking and softmax are additional work. Prefill has many query rows; ordinary decode has one per request.
- Algorithm 0 writes and reads both scores and probabilities. At bytes per intermediate element this is requested bytes, not the complete kernel traffic or a hardware-counter measurement.
- Decode can reuse each KV head across grouped query heads, but cannot reuse it across a long query tile. Layout, cache residency and schedule determine whether that reuse is realized.
Common mistakes · 3
- Calling storage size traffic. A tensor may be read several times, and actual memory transactions can exceed requested bytes.
- Using the paper's unscaled equation as a different model. Its exposition omits the scale; your reference must include the model's scale.
- Assuming the paper's HBM hardware. The same dataflow applies to GPUs with GDDR memory, but bandwidth and on-chip capacity differ.
Try it yourself
Closed-book, before checking anything
Quiz yourself
Answer first, then mark it. Missed ones go to Review.
0 got · 0 missed
1.Does avoiding the score matrix remove quadratic prefill arithmetic?Answer
No. Dense attention still computes every allowed query-key interaction. Tiling changes storage and data movement, not the leading dense matrix-product count.
2.Why are 32 MiB of intermediates responsible for 64 MiB of requested traffic in this model?Answer
Each of the two tensors is written once and read once. This excludes input/output movement, repeated tile loads, masks and workspace.
3.Does a long KV cache prove decode is memory-bound?Answer
No. It predicts substantial KV movement. Launches, insufficient parallelism, reductions and address translation may dominate; timing and profiling must distinguish them.
Practice
- LeetGPU 6: Softmax Attention
reference_impl,generate_example_testand all four cases ingenerate_functional_testImplement the unchanged
solvesignature in CUDA or Triton. Use the public generators and reference in your own local harness, as in the CUDA primitives section; the repository lackscore.challenge_base, andscripts/run_challenge.pysubmits to a service with an API key rather than running locally. Recreate the generated tensors and compare outputs using the challenge's tolerances. The cases include rectangular attention and odd head widths. The section mini-project covers the traffic ledger.
You're done when
Your traffic ledger reproduces the counts, and your attention implementation matches every functional case of challenge 6 without claiming a speedup.
Only when you can do this without notes.
Leads to
Notes
Resources · 2 for this unit, 11 more in the section
- FlashAttentionTri Dao and collaborators · primary
Read the IO-awareness argument, exact attention algorithm and complexity analysis. Derive the online state and block dataflow, then implement a reduced forward kernel or trace a trusted implementation across at least causal and noncausal cases.
- FlashInferFlashInfer Project · support
Inspect the attention, sampling and serving-kernel interfaces. Reconstruct one dispatch path and compare its layout and workspace contracts with your reduced kernel instead of copying the optimized implementation.
Also in this section
- FlashAttention-2Tri Dao · required
Study reduced non-matmul work, sequence parallelism and warp work partitioning. Compare the schedule with the first paper and predict which shapes benefit before checking measurements.
- Online Normalizer Calculation for SoftmaxOnline Softmax Authors · required
Re-derive the recurrence inside tiled attention and prove rescaling correctness. Add extreme-logit, all-masked, odd-head and partial-tile tests before any performance comparison.
- CS336 Assignment 2 - Section 4 FlashAttention-2 in TritonStanford University · required
Do the weighted-sum warm-up, then
flash_forward(a PyTorch tiled version and the Triton kernel) andflash_backwardagainsttests/test_attention.py. Runflash_benchmarkingon sizes that fit your GPU instead of the handout's B200 sweep. - TensorTonic Language Modeling from Scratch - Blockwise Online SoftmaxTensorTonic · support
Solve it before the tiled attention kernel as a check on the rescaling recurrence.
- LeetGPU - Attention and Transformer ChallengesAlphaGPU · required
Solve 6 Softmax Attention and 12 Multi-Head Attention or 53 Causal Attention. Then choose two of 50 RMS Normalization, 54 SwiGLU, 61 RoPE, 80 Grouped Query Attention, 83 Fused Residual Add RMS Norm and 84 SwiGLU MLP Block. Keep correctness tests beyond the hosted score.
- GPU MODE - Attention and Fused KernelsGPU MODE · support
Use Lectures 12, 13, 18, 36 and 40 for FlashAttention, Ring Attention, fusion, FlashAttention-3 and FlashInfer. Reproduce one schedule or fusion idea under the stage shape matrix and a strong baseline.
- FlashAttention-3FlashAttention Authors · depth
Study Hopper-specific asynchronous execution and low-precision design after the portable kernel. Implement only with the required architecture, and separate algorithmic from hardware-specific gains.
- Modern GPU Programming for MLSys - Flash Attention 4MLC · depth
Read the complete Blackwell attention chapter, including two MMAs, online softmax, causal masking and GQA. Run it only on compatible sm_100a hardware with the pinned TIRx stack; otherwise use the code for architecture reconstruction.
- PyTorch SDPA contracts and integration tutorialPyTorch · reference
The PyTorch 2.14 SDPA API page gives mask polarity, rectangular causal alignment, GQA and backend limitations. The SDPA tutorial (https://docs.pytorch.org/tutorials/intermediate/scaled_dot_product_attention_tutorial.html, read 2026-10-13) gives Explicit Dispatcher Control, Causal Self Attention, Using SDPA with
torch.compileand Using SDPA withattn_biassubclasses. Correct the tutorial's evaluation-time causal flag before integration. - Triton 3.8.0 Layer NormalizationTriton Project · required
Motivations and
_layer_norm_fwd_fusedin tutorial 05, pinned to v3.8.0. Study centered variance, float32 reductions, valid-column masks and the forward wrapper's supported-width guard. Defer backward and the benchmark sweep. - vLLM serving latency and goodput definitionsvLLM Project · reference
vLLM v0.31.0: Benchmark CLI, Understanding the Latency Metrics and Load Pattern Configuration; serving benchmark CLI, goodput service-level objectives. Use definitions to translate kernel evidence into request metrics, not as a required serving-engine installation.