Unit 10 of 12 · about 5 hours · implement
Kernel contracts, an independent oracle and randomized differential tests
Independent references and differential and property tests and Tolerances and an extreme-value policy gave the generic method. A serving kernel adds absolute positions, paged gathers and grouped heads, so the oracle must stay independent of the runner's own metadata.
You'll be able to
- Write the shape, dtype, stride, mask, position and tolerance contract for one serving kernel path.
- Build an independent double-precision oracle that shares no indexing, mask or reduction code with the candidate.
- Run a randomized differential matrix over shapes, dtypes, layouts and masks that fails seeded defects and honors an extreme-value policy.
Covers
Read
In this order, only the parts listed
0 of 3 done
- FlashAttention oracle and public testsCS336 Assignment 2 - FlashAttention and Triton Sections
_attention_and_lse(explicit scale, softmax,logsumexp),_make_attn_inputs(seed 0, batch 4, 128 by 128, width 64),assert_closeatrtol=1e-2, atol=1e-2with the saved-LSE check in_test_flash_forward_pass;test_flash_forward_pass_pytorchand the parametrized triton cases - Attention-state merge contractFlashInfer Documentation
FlashInfer documentation:
merge_statesovervof shape[seq_len, num_states, num_heads, head_dim]with float32sof shape[seq_len, num_states, num_heads], returning one merged output and logsumexp per head (page read 2026-10-14, release 0.7.1) - Mask and tolerance contracts in the serving harnessAI Systems Performance Engineering companion code - Chapter 18
_build_dense_mask_from_block_table,_build_block_mask_from_block_tablewithmask_fn(batch, head, q_idx, kv_idx), plusoutput_toleranceandprecision_flags
Focus on
- Share nothing with the candidate. The oracle recomputes positions, masks and reductions from the logical spec; importing the candidate's block table or mask builder makes the test circular.
- Declare tolerances per dtype before running. A double-precision oracle against a float candidate needs stated
rtolandatol; all-masked rows, NaN, infinities and subnormals need explicit policies, not tighter defaults. - Build every rectangular mask from absolute positions.
is_causal=Truein PyTorch'sscaled_dot_product_attentionand the CS336 reference mask are top-left aligned, which is wrong for a cached suffix, while some kernels align bottom-right; pass an explicit mask instead of trusting a flag. - Merge split states through their normalizers with
merge_states. Test per-request outputs after batch reordering and page remapping under the declared tolerance. Bitwise batch invariance is a stronger contract. FA2 tensor-core decode documentsfixed_split_sizein pages to stabilize merge order;disable_split_kvavoids that split. Neither establishes bitwise invariance for the entire model, and a fixed split can change capture geometry as lengths grow.
Common mistakes · 3
- Testing only comfortable shapes. Sample odd lengths, non-multiple-of-tile widths, empty rows and all-masked rows; dispatch fails at the tail.
- Fixing one seed and calling the suite randomized. Vary seeds and shapes per trial and pin one seed for the regression file.
- Tightening the tolerance to chase ULP noise from reduction order. Declare the accumulation contract first; noise inside it is not a defect.
Try it yourself
Closed-book, before checking anything
rtol=1e-12, atol=1e-12 over contiguous queries and a strided view of the same data. A one-slot value shift and a top-left-mask substitution must both fail the comparison.Quiz yourself
Answer first, then mark it. Missed ones go to Review.
0 got · 0 missed
1.Why must the oracle avoid the candidate's mask builder?Answer
Sharing it tests the kernel against itself. An independent mask from the logical spec is what catches offset defects.
2.What breaks when a cached suffix uses top-left causal?Answer
Each query row attends keys up to its chunk-local index instead of its absolute position, dropping valid prefix keys. The absolute-position oracle mismatches on every row.
3.Why merge through normalizers instead of averaging partition outputs?Answer
Partitions have different denominators. Weight each output by its normalizer before dividing by the combined one;
merge_statesis that operation.4.The candidate passes float32 at 1e-2 but fails float64 at 1e-12. Is it broken?Answer
Not established. The tolerance must match the dtype and accumulation contract. Restate the contract, then judge.
Practice
- CS336 Assignment 2:
test_flash_forward_pass_pytorchProblem (
flash_forward) (p. 26); wire your implementation throughget_flashattention_autograd_function_pytorchintests/adapters.pyand passtest_flash_forward_pass_pytorch(plus the triton cases on your GPU)Implement in your own repository and follow assignment integrity: use concepts, invariants, tests and profiling, not copied solutions. The 1e-2 tolerance is the assignment's contract; your serving matrix keeps its own per-dtype tolerances.
You're done when
Your oracle fails the seeded shift and mask defects, passes the full matrix including an all-masked row under a stated policy, and your own implementation passes the CS336 forward tests.
Only when you can do this without notes.
Leads to
Notes
Resources · 3 for this unit, 11 more in the section
- 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.
- 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.
- 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
- 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.
- 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.
- 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.
- 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.