Unit 2 of 11 · about 4 hours · measure
Launch overhead, CUDA graphs, bucketing and graph misses
Small decode steps are often launch-bound, not kernel-bound. Graphs remove the host overhead only for stable shapes with a tested fallback.
You'll be able to
- Measure per-launch overhead with interleaved event trials and report medians, not best runs.
- Capture and replay a stable kernel sequence in a CUDA graph with static buffers and an eager fallback.
- Name one bucketing or graph-miss regime where graphs lose and show the measured crossover.
Covers
Read
In this order, only the parts listed
0 of 3 done
- Capture, replay and graph best practiceAI Systems Performance Engineering - Chapters 13, 15 and 16
Chapter 13, Reducing Kernel Launch Overhead with CUDA Graphs: Capturing a CUDA Graph and Preallocating Memory; Replaying the Graph; Best Practices for CUDA Graphs
The book says any allocation during capture fails. In PyTorch 2.14.1,
torch.cuda.graphserves capture-time allocations from the graph's private memory pool; host synchronization such astorch.cuda.synchronize()or.item()is what fails. Preallocate static buffers anyway so addresses and memory stay predictable. - Eager launches versus graph replayAI Systems Performance Engineering companion code - Chapters 12 to 16
BaselineCudaGraphsBenchmarkinbaseline_cuda_graphs.pyversusOptimizedCudaGraphsBenchmarkinoptimized_cuda_graphs.py(N = 1024, 32000 iterations); diagnostic ingraph_replay_benchmark.py - Piece graphs and shape bucketingAI Systems Performance Engineering companion code - Chapters 12 to 16
BaselinePieceGraphsBenchmarkinbaseline_piece_graphs.pyversusOptimizedPieceGraphsBenchmarkinoptimized_piece_graphs.pywithRegionalPieceGraphinpiece_graphs_model.py
Focus on
- Name the timed boundary before comparing: per-launch overhead, captured replay, or end-to-end step. Keep warmup, capture and steady-state replay in separate intervals.
- Capture on a side stream with static input buffers. Tensors allocated during capture come from the graph's private pool and keep fixed addresses, so copy new inputs into the captured buffers; any shape change after capture needs a new graph or bucket.
- Bucket one graph per stable shape and keep an eager fallback. A replay on an unseen shape silently computes the wrong geometry or fails to launch.
Common mistakes · 3
- Synchronizing with the host inside the capture region, through
torch.cuda.synchronize()or a value read back with.item(). The capture fails, so move such checks before capture or into the replayed outputs. - Timing capture or warmup inside the steady-state interval and calling that replay latency.
- Keeping one graph for all shapes. Unseen geometry replays stale work; bucket explicitly and test the fallback.
Try it yourself
Closed-book, before checking anything
graph.replay() calls with CUDA events, interleaved in pairs with a recorded seed, and report both medians. On an RTX 3050 6 GB with PyTorch 2.14.1 and driver 595.99, six runs of 41 interleaved pairs gave eager medians from 2.4 to 13.5 us per launch and replay medians from 1.8 to 7.2 us as host load changed; replay was 1.4 to 1.9 times faster in every run; yours will differ, so compare the ratio on your GPU. Record host load with your medians; replay must not exceed eager on this shape, and any shape change needs recapture.Quiz yourself
Answer first, then mark it. Missed ones go to Review.
0 got · 0 missed
1.What does graph replay remove from a stable sequence?Answer
It removes per-launch host overhead and idle gaps between kernels. It does not shorten the kernels themselves.
2.Why does a shape change after capture need recapture?Answer
The replay reuses captured addresses and launch geometry. A new shape needs a new capture or bucket; otherwise the run reads stale buffers or fails.
3.Name one regime where CUDA graphs lose.Answer
When capture, bucket lookup, or replay setup exceeds the saved launch overhead, or when misses force frequent fallback. Small stable batches win; ragged dynamic shapes lose.
Practice
- Companion code ch12: CUDA-graph capture and replay pair
Run
python -m cli.aisp bench run --targets ch12:cuda_graphs --profile minimal(plainpython -m ch12.compareruns every pair in the chapter) and the standalonegraph_replay_benchmark.pydiagnostic; then capture one stable 32-step sequence and compare interleaved eager versus replay medians with a fallback pathNeeds CUDA. Keep each run short. No public autograder checks the graph; retain event medians, capture logs and the fallback test.
You're done when
You report interleaved eager and replay medians with explicit boundaries, a passing fallback test, and one measured losing regime.
Only when you can do this without notes.
Leads to
Notes
Resources · 2 for this unit, 12 more in the section
- AI Systems Performance Engineering - Chapters 13, 15 and 16Chris Fregly · primary
Read Chapter 13 on profiling and tuning PyTorch, Chapter 15 on inference parallelism, decoding and routing, and Chapter 16 on profiling and debugging inference. Keep Chapters 17 to 19 for GPU-9 and depth.
- AI Systems Performance Engineering companion code - Chapters 12 to 16Chris Fregly · required
Use compatible examples from
code/ch12throughcode/ch16. Trace whether each optimized path changes a kernel, graph, compiler choice, scheduler or library dispatch, then integrate one bounded custom path into a realistic operator or small endpoint.
Also in this section
- AI Performance Engineering - Inference EnginesWafer · reference
A curated index. Use Section 4 only to find the introducing paper and implementation for the mechanism your measurement points to.
- PagedAttention and vLLMvLLM Authors · required
Study block-based key-value allocation, sharing and scheduling interaction. Trace logical token positions to physical blocks in one engine run and quantify fragmentation and memory-capacity effects.
- SGLangSGLang Authors · support
Read the runtime and RadixAttention design, then inspect the repository path for one kernel or prefix-reuse interaction. Use it as an alternative architecture in the integration defense.
- LeetGPU - Inference Kernel SetAlphaGPU · required
Choose three bottleneck-matched challenges from 74 GPT-2 Block, 83 Fused Residual Add RMS Norm, 84 SwiGLU MLP Block, 87 Speculative Decoding Verification, 93 Llama Transformer Block and 96 INT8 KV Cache Attention. Integrate one result locally rather than stopping at the hosted submission.
- FlashInferFlashInfer Project · support
Use the repository as the serving-kernel baseline and interface reference. Reconstruct workspace planning, layouts, dispatch and stream behavior for one selected operation before comparing your path.
- GPU Microbenchmark and Kernel Suite - IntegrationRoadmap-Final · support
Complete the real tensor or model-operation integration, dispatch and fallback requirements. Report compilation and invocation overhead, workload frequency, correctness or quality and the end-to-end no-benefit regime.
- PyTorch 2.14 ProfilerPyTorch · reference
Read the Overview example plus the API reference for
torch.profiler.profile(activities,schedule,on_trace_ready,record_shapes,with_stack),torch.profiler.record_functionandexport_chrome_trace. Use it for exact profiler and NVTX-range call contracts missing from the book. - Orca (OSDI 2022)USENIX · support
Read Sections 3 to 4 for iteration-level scheduling and selective batching, and Section 6 for the engine microbenchmark and end-to-end latency-throughput method. Use it as the continuous-batching mechanism behind the book summary.
- Sarathi-ServearXiv · support
Read Sections 3 to 4 for chunked-prefill stall-free batching and token-budget selection, and Section 5 for capacity and overhead method. Use it as the chunked-prefill mechanism behind the book summary.
- Fast Inference from Transformers via Speculative DecodingPMLR · support
Read Sections 2 to 3 for the draft-verify-accept loop, the acceptance rule and the walltime-versus-operations analysis. Use it for the verification cost model behind the engine guides.
- vLLM Documentation - Automatic Prefix CachingvLLM Project · reference
Read Automatic Prefix Caching (vLLM v0.31.0) for hash-based block reuse, full-block caching, reverse-order freeing and the multimodal hashing example. Use it for engine behavior the papers do not version.
- Transformer Inference ArithmeticKipply · reference
Read kv cache, capacity, latency calculations, batch sizes and flops counting for per-token KV bytes, weight-capacity arithmetic and memory-bound versus compute-bound latency floors. Use it to derive endpoint bounds before measuring.