Inference Kernels and Graph Execution
Inference uses unusual shapes, changing sequence lengths and repeated small decode steps. A kernel or graph optimization matters only when its numerical contract, dispatch coverage and engine-level effect all hold.
Section 5 of 9 · 12 units · about 48 hours
By the end you can Integrate one oracle-backed kernel or graph path, pass the serving shape and dtype matrix, explain its measured hardware bottleneck, and either demonstrate or honestly reject endpoint benefit under replayable load.
Units
- Stable and online softmax, normalization and fused residual paths3h
- Prefill and decode attention shapes and IO-aware attention4h
- Paged and variable-length decode attention, GQA grouping and KV addressing4h
- KV append, gather and layout, and RoPE positions and offsets4h
- Sampling and token-selection kernels and guided-decoding integration4h
- Memory layout, strides and alignment, and fusion against intermediate traffic3h
- Launch and host overhead, streams, events and asynchronous execution4h
- CUDA graph capture and replay, static shapes, buckets, padding and fallback5h
- Compilation, graph breaks and recompilation in a serving path3h
- Kernel contracts, an independent oracle and randomized differential tests5h
- Device timing, FLOP, byte and launch accounting, and profiler classification4h
- Engine dispatch and fallback, kernel-to-endpoint translation and negative results5h
Build it
Mini project · about 12 to 18 hours
Serving kernels with oracles, graphs and endpoint translation
Build independent CPU oracles for residual, attention, paged KV and sampling paths in engine/, with shape ledgers and a timing harness. Capture graphs, log compilation, wire one path through dispatch with fallback, and translate the win or keep the loss.
- 1Write double-precision CPU references for fused residual-add plus norm and online-softmax merges in
engine/, checking retained residuals and activations through repeated calls with empty-partition and overlap policies stated. - 2Derive prefill, cached-chunk and decode shape ledgers with FLOP and byte predictions for your workload matrix, plus stride and alignment dispatch cases with a fusion ledger that keeps conversion and retained-output costs.
- 3Build a page-gather and head-mapping oracle independent of backend scheduling, and prove appends across page boundaries with absolute RoPE positions under reorder, remap, compaction, cancellation and slot reuse with poisoned tails.
- 4Implement masked greedy and filtered stochastic selection with a declared filter order and tie policy, keep grammar and random state per request across slot changes, time mask work apart from selection, and pass the CS336 forward attention tests.
- 5Trace a two-stream producer and consumer dependency with completion events and buffer lifetimes, time completed serving steps with warmup and interleaved medians, and check cancellation-safe buffer reuse in a CPU event simulation with profiler ranges.
- 6Capture and replay a static-shape decode step with bucket, padding and miss accounting, log compile breaks with recompile counts and a tested eager fallback, check state reset after both, then translate one kernel win to endpoint TTFT, TPOT and goodput with per-phase dispatch logs, keeping the losing regime.
What you hand in
- CPU oracles with shape ledgers, paged-KV lifecycle checks and the sampling oracle with per-request state tests.
- Timing harness with warmup, interleaved medians, profiler ranges and the stream dependency trace.
- Graph and compile evidence with dispatch logs, endpoint translation and the preserved losing regime.
How to check it
- Self-grade with the rubric below
- CS336 Assignment 2 attention tests
Pass
test_flash_forward_pass_pytorch, plus the Triton cases on your GPU; keep serving tolerances apart from the assignment contract.
How it's graded
Oracle independence
Pass: Oracles share no indexing, mask or reduction code with the candidate, and seeded shift and mask defects fail visibly.
Great: The matrix spans odd lengths, partial pages, empty rows and remapped allocations under stated per-dtype tolerances.
Lifecycle correctness
Pass: Append, gather, RoPE positions and sampler state survive reorder, compaction and slot reuse with poisoned tails inert.
Great: A stale-offset defect and a grammar-state leak are both caught by the request-identity tests.
Honest timing
Pass: Medians come from interleaved synchronized trials with stated boundaries, and profiler evidence backs the bottleneck call.
Great: Graph and compile wins translate to endpoint goodput by share math, or the negative result ships with its regime.
Resources
- FlashInfer: Efficient and Customizable Attention Engine for LLM Inference ServingFlashInfer Project
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)
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
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
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
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
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.
- vLLM structured outputs (v0.31.0)vLLM Project
Read Offline Inference and the API-field migration warning; trace grammar bitmask application before sampling in the versioned model-runner API.
- Mini-SGLang - Kernel, Model Runner and Overlap BoundariesSGLang Project
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
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
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
Work the Attention Kernels module for the decode-attention memory traffic and the paged-attention gather before the matching units.
- TensorRT-LLM Architecture OverviewNVIDIA
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.
- AI Performance Engineering - Kernel Optimization, Profiling and AttentionWafer
A curated index. Use Sections 2 and 3 only to find a kernel or profiler source the other entries lack.
- PyTorch compiler troubleshooting guide (2.14)PyTorch
Read Graph break, Guards, Recompilation and Dynamic Shapes; run
TORCH_LOGSset tograph_breaksandrecompileson a small serving-shaped function.