Unit 2 of 12 · about 4 hours · explain, derive
Prefill and decode attention shapes and IO-aware attention
Attention shapes, prefill and decode reuse, and materialized traffic already supplied the square-attention ledger. Serving adds cached suffixes, mixed request lengths and a shape distribution that can invalidate a single-kernel choice.
You'll be able to
- Derive rectangular attention shapes for uncached prefill, cached chunks and ordinary decode.
- Separate query-head arithmetic from KV-head traffic and identify potential GQA reuse.
- Predict when query tiling or split-KV parallelism is worth testing without assuming a bandwidth bottleneck.
Covers
Read
In this order, only the parts listed
0 of 2 done
- Serving intensity and tile selection, arXiv:2501.01005v1FlashInfer: Efficient and Customizable Attention Engine for LLM Inference Serving
Section 2.1, FlashAttention; Sections 3.2.1 and 3.2.2, data movement and microkernel tile sizes; Appendix A, Head Group Fusion for Grouped-Query Attention
Use the paper's intensity as an attention-only model. Its statement about batching does not apply to weight reuse in the rest of a transformer.
- Forward attention state and workCS336 Assignment 2 - FlashAttention and Triton Sections
Section 4.2.2, Details of the FlashAttention forward pass and Algorithm 1, printed pp. 24 to 25
Reuse your completed forward implementation. Skip backward and the training benchmark sweep; extend the shape ledger to rectangular cached attention.
Focus on
- For one request with query tokens, visible KV tokens, query heads and head width , scores have shape . Uncached prefill has equal lengths; a cached chunk has more keys than queries; ordinary decode has one query.
- Dense score and value products cost FLOPs, counting a multiply-add as two. This excludes scaling, masking and softmax; useful causal pairs and executed padded tiles need separate counts.
- An ideal single KV read costs bytes for equal key/value widths and bytes per element. Reusing these bytes across grouped heads is a schedule property, not a consequence of fewer stored heads alone.
- IO-aware attention removes global score/probability materialization. Short queries still offer little query-row reuse; split-KV adds parallelism but needs partial-state storage and reduction.
Common mistakes · 3
- Using a square or upper-left causal mask for a cached suffix. Its query positions start after the cached prefix.
- Reducing arithmetic by the GQA group size. Query heads still compute distinct scores and outputs.
- Calling a low-intensity attention shape bandwidth-bound without timings and profiler evidence. Launch supply or insufficient parallelism may dominate.
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 batching unrelated decode requests create reuse of each request's KV across query tokens?Answer
No. Ordinary decode still has one query per request. Batching adds parallel work and can improve weight reuse elsewhere, but unrelated requests have different KV.
2.Why distinguish useful causal FLOPs from executed FLOPs?Answer
A masked tile can still execute dense instructions or padded lanes. A mathematical pair count is not a hardware instruction count.
3.Why can FlashAttention reduce traffic without reducing the attention pair count?Answer
It streams tiles and retains row state on chip instead of writing quadratic intermediate matrices. It still evaluates the permitted query-key interactions.
You're done when
You derive the cached-chunk ledger and mask from absolute positions, then explain a different request mix without confusing useful work, modeled bytes and measured traffic.
Only when you can do this without notes.
Leads to
Notes
Resources · 2 for this unit, 12 more in the section
- FlashInfer: Efficient and Customizable Attention Engine for LLM Inference ServingFlashInfer Project · primary
Read the storage heterogeneity, plan and run separation, load-balanced scheduling, customization, CUDA Graph compatibility and end-to-end evaluation. Use it to connect serving-shaped attention kernels to dynamic workloads and dispatch constraints.
- CS336 Assignment 2 - FlashAttention and Triton SectionsStanford University · required
Complete the relevant derivation, PyTorch reference and Triton sections using your own code. Follow assignment integrity: use external help for concepts, invariants, tests and profiling, not copied solutions or edited answer code.
Also in this section
- AI Systems Performance Engineering - Chapters 18 and 19, decode kernels and engine optimizationsChris Fregly (O'Reilly) · required
Read "Optimized Decode Kernels" in Chapter 18 (FlashMLA, ThunderMLA, FlexDecoding), then the Chapter 19 sections on kernel autotuning, occupancy-aware kernel selection, hot-swappable kernels and CUDA-graph prewarming. Choose one bounded critical path to verify.
- AI Systems Performance Engineering companion code - Chapter 18Chris Fregly · required
Start with paged_attn_common.py, the dense versus paged layout pair, CUDA graph bucketing and the vLLM integration pair. Run correctness tests first, then a hardware-compatible benchmark with newly captured artifacts.
- FlashAttention-2: Faster Attention with Better Parallelism and Work PartitioningTri Dao · required
Derive online-softmax state, memory traffic and work partitioning. Implement only a small oracle-backed version or use the CS336 assignment; production kernel tuning belongs to the GPU track.
- FlashInfer DocumentationFlashInfer Project · required
Use the current attention, PageAttention, sampling, JIT and CUDA Graph interfaces while implementing. Pin the version and supported GPU architecture, and validate dispatch and fallback over the real workload shape distribution.
- Mini-SGLang - Kernel, Model Runner and Overlap BoundariesSGLang Project · support
Trace how FlashAttention or FlashInfer, KV layouts, tensor parallel communication and overlap scheduling meet the model runner. Identify the fallback and state-reset boundary before attempting a change.
- UCSD CSE 291A (Spring 2026) - Guest lecture: Engineering vLLMUC San Diego · support
Read the scribe notes, Sections 4 and 5: CPU overhead, the API server and renderer, synchronous and asynchronous engine-core scheduling, GPU-side input preparation, piecewise CUDA graphs and the hybrid kernel strategy.
- vLLM CUDA Graphs design (v0.31.0)vLLM Project · support
Use the capture modes, batch-size buckets and piecewise splitting around attention to explain what a graph replay can and cannot include.
- LLM Inference: From scratch, one token at a time - Module 07Tushar Amrit · support
Work the Attention Kernels module for the decode-attention memory traffic and the paged-attention gather before the matching units.
- AI Performance Engineering - Kernel Optimization, Profiling and AttentionWafer · reference
A curated index. Use Sections 2 and 3 only to find a kernel or profiler source the other entries lack.
- TensorRT-LLM Architecture OverviewNVIDIA · support
Use the runtime-optimization section to compare graph replay, overlap scheduling and backend dispatch with your selected engine. Record current version and hardware support before treating a path as available.
- vLLM structured outputs (v0.31.0)vLLM Project · required
Read Offline Inference and the API-field migration warning; trace grammar bitmask application before sampling in the versioned model-runner API.
- PyTorch compiler troubleshooting guide (2.14)PyTorch · reference
Read Graph break, Guards, Recompilation and Dynamic Shapes; run
TORCH_LOGSset tograph_breaksandrecompileson a small serving-shaped function.