Unit 6 of 10 · about 5 hours · implement
Variable-length, paged and decode attention
Serving batches contain different lengths and noncontiguous cache pages. Attention must preserve request and token identity while changing storage.
You'll be able to
- Implement request-local ragged indexing and logical-token to physical-page translation.
- Build a reduced paged decode path that matches contiguous attention.
- Explain when split-KV parallelism needs a stable merge and extra workspace.
Covers
Read
In this order, only the parts listed
0 of 3 done
- FlashInfer ragged and paged layoutsFlashInfer
Commit f2794d5: Layout: NHD/HND, Ragged Tensor and Page Table Layout, plus the FAQ on cache ownership
Skip MLA and cascade layouts. Read the data contracts rather than copying older API examples. Empty requests need your own policy; the documented last-page rule assumes at least one page.
- Attention states and recursive attentionFlashInfer
Commit f2794d5: attention-state definition and binary/n-ary merge equations; Applications, KV Sequence Parallelism
Apply the merge equations only to disjoint token subsets. Skip shared-prefix performance claims. Use maximum subtraction in the merge, as the text notes but its displayed expression omits.
- Paged decode planning and execution contractFlashInfer
Commit f2794d5:
BatchDecodeWithPagedKVCacheWrapperclass example, constructor andplan/rundocstringsTrace one supported backend's shape, page-table and workspace arguments. Do not implement every backend, and run Hopper or Blackwell paths only on a GPU that has them; otherwise audit them statically.
Focus on
- Ragged data uses prefix offsets; each request has its own query and KV range. A flat index is not a logical token position, and neighboring requests must never attend to each other.
- With page size , logical token uses page-table entry and slot . The page-table entry gives the physical page; it need not equal the logical page number.
- For a nonempty request with pages and last-page occupancy , valid length is , with . Read only valid slots, even if stale data occupies the rest.
- Split-KV decode produces independent states over disjoint key ranges. Merge normalizers and weighted outputs, not equally weighted partial outputs. Extra launches and partial-state workspace can outweigh the added parallelism.
Common mistakes · 3
- Using allocated page capacity as sequence length. Unused slots are not keys and may contain another request's old data.
- Averaging split outputs. Each output is already normalized by a different partition's mass; their logsumexp statistics set the merge weights.
- Counting the same prefix in two split states. Merge algebra represents a disjoint partition; overlap double-counts those keys.
Try it yourself
Closed-book, before checking anything
[3, 1]. Its last-page occupancy is 3; token 6 maps to page 1, slot 2. Build a CPU gather oracle, permute the physical allocation while preserving the page table, and verify unchanged dense decode output. Then implement the same mapping in a bounded CUDA or Triton decode kernel with odd lengths and partial pages.Quiz yourself
Answer first, then mark it. Missed ones go to Review.
0 got · 0 missed
1.If the last page is full, is its occupancy zero?Answer
No. It equals the page size. Zero does not encode a full page under the documented nonempty-request contract.
2.Should physical page order affect the attention answer?Answer
No, if the page table still maps the same logical tokens and values. Changing logical token positions or masks would affect it. Floating-point reduction order may introduce tolerated rounding differences.
3.Why can splitting the KV sequence help decode when query tiling cannot?Answer
It creates more independent thread blocks from a long key sequence despite having only one query row. A second reduction combines their attention states, so the gain must exceed that overhead.
Practice
- TensorTonic: Decode Attention with a KV Cache
Implement
kv_cache_decode_step: append the new key and value at position , attend each query head through its group's KV head over all positions, and return the extended caches; pass the existing-cache, uniform two-position and shared-KV-head public casesIts caches are contiguous. The section mini-project covers the paged path: a
kernellabragged/paged decode kernel, a contiguous gather oracle, page-permutation, request-isolation and split-state tests.
You're done when
Your reduced decode kernel matches the independent contiguous oracle for permuted pages, unequal request lengths, partial last pages and the chosen empty-request policy.
Only when you can do this without notes.
Leads to
Notes
Resources · 1 for this unit, 12 more in the section
- 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
- 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.
- 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.