Unit 10 of 11 · about 4 hours · implement

CUDA graphs and validated dispatch with fallback

Graphs remove per-launch CPU overhead for repeated work, but a graph bakes in addresses and shapes. The validation and fallback around it is the actual engineering.

You'll be able to

  • Capture a stable kernel sequence into a graph and replay it with identical results.
  • Update an instantiated graph in place when only parameters change, and re-instantiate when the topology changes or the update is refused.
  • Gate dispatch on shape, dtype and device validation with a correct eager fallback.

Covers

CUDA graph capture, replay, update and eager fallbackShape, dtype, layout and device dispatch with validated fallback
1

Read

In this order, only the parts listed

0 of 3 done

  1. CUDA graphs chapterAI Systems Performance Engineering - Chapters 11 and 12

    Chapter 12, CUDA Graphs (memory pools and pointer stability), Capturing a CUDA Graph with a CUDA Stream (cudaStreamBeginCapture to cudaStreamEndCapture) and Dynamic Graph Update (parameter changes without recapture)

    Skip device-initiated launch beyond the vocabulary; this section launches graphs from the host.

  2. Graphs referenceCUDA C++ Programming Guide (v13.4.2)

    Sections 4.2.2 (stream capture with cross-stream rules, prohibited operations, instantiation and execution) and 4.2.3 (whole-graph update, per-node update with cudaGraphExecKernelNodeSetParams, and the update limitations); Section 2.5.9.2 on the asynchronous execution page is the short introduction

    Read the capture constraints and update rules. Skim conditional nodes; they are not used in this section.

  3. Dispatch and fallback contractGPU Microbenchmark and Kernel Suite - CUDA Core

    Architecture constraints (dispatch never selects an unvalidated path; every custom path has a correct fallback) and Milestone C (correctness-gated dispatch with unseen-shape fallback)

2

Focus on

  • Capture, instantiate and launch happen once, once and many times. Replay removes most per-launch CPU cost: on an RTX 3050 6 GB with CUDA 13.4, tiny kernels took 0.79 us each inside a graph against 2.67 us launched one by one, so graphs pay when launch overhead is a large share of step time.
  • Capture forbids allocation, synchronization, legacy-stream work and shape changes. Preallocate maximum shapes and validate before capturing.
  • cudaGraphExecUpdate updates an instantiated graph in place when the new capture has the same topology: kernel arguments, pointers and grid sizes may change. A different sequence of nodes fails the update; check the result and the reported node, then destroy and re-instantiate.
  • The first launch after instantiation also uploads the graph (cudaGraphUpload can do it ahead of time), so warm up before timing: the first replay of an 8-kernel chain took 34 us on the RTX 3050 example above, against about 6 us warm; measure your own first-replay cost the same way.
Common mistakes · 3
  • Capturing on the legacy default stream is invalid. Use an explicit stream, preferably non-blocking.
  • Replaying after freeing and reallocating buffers reads stale addresses. Graphs bake in pointers, so tie buffer lifetime to the executable graph.
  • Ignoring the cudaGraphExecUpdate return code and launching the stale instance after an incompatible change.
3

Try it yourself

Closed-book, before checking anything

Capture an 8-kernel saxpy chain, replay it 100 times with outputs identical to eager, update a pointer and a length in place with cudaGraphExecUpdate, then change the number of kernels so the update fails and you re-instantiate. Report per-kernel launch time eager and in the graph, after warmup.
4

Quiz yourself

Answer first, then mark it. Missed ones go to Review.

0 got · 0 missed

  1. 1.When do CUDA graphs help, in one measured rule?Answer

    When per-launch CPU overhead is a large fraction of kernel time. Tiny kernels took 2.67 us each launched eagerly against 0.79 us inside a graph on an RTX 3050 6 GB; long kernels show no gain.

  2. 2.What does an executable graph bake in, and which changes can it take in place?Answer

    The nodes, their dependencies and every parameter: kernel arguments, pointers and launch dimensions. Parameters, grid sizes included, can be updated in place while the topology is unchanged; a different sequence of nodes needs a new instantiation.

  3. 3.Whole-graph update fails on a new input. What is the correct recovery?Answer

    Destroy the executable graph and recapture plus re-instantiate from the new sequence. The update API names the failing node for the log.

  4. 4.Why can random-number generation inside a capture repeat the same values on every replay?Answer

    A replay reuses the captured arguments, so a generator whose seed or offset is a kernel argument produces the same numbers each time. PyTorch registers its generator with the graph and advances the offset per replay; otherwise generate outside the capture or read the offset from device memory.

5

Practice

  • AI Systems companion code: Chapter 12 graph demos

    graph_capture_demo.py, graph_replay_benchmark.py and baseline_cuda_graphs.py: capture and replay on your GPU with a state-reset test

    graph_capture_demo.py and graph_replay_benchmark.py run with PyTorch alone; baseline_cuda_graphs.py imports the shared harness and needs the repository's requirements.txt. Add a parameter-update test and a forced re-instantiation fallback test of your own.

You're done when

Your graph replays bit-identical results, an in-place update handles parameter changes, and a topology change falls back to re-instantiation correctly.

Only when you can do this without notes.

Leads to

Notes

Resources · 3 for this unit, 8 more in the section
  • AI Systems Performance Engineering - Chapters 11 and 12Chris Fregly (O'Reilly) · required

    Read Chapter 11 on streams, events, inter-kernel pipelining and stream-ordered allocation, and Chapter 12 on CUDA graphs and dynamic scheduling. Skip device-initiated launch beyond the vocabulary.

  • GPU Microbenchmark and Kernel Suite - CUDA CoreRoadmap-Final · support

    Complete the CUDA vector map, reduction, transpose and stable softmax requirements plus seeded access, synchronization, mask, stream and numerical failures. Preserve library and framework baselines.

  • CUDA C++ Programming Guide (v13.4.2)NVIDIA · reference

    Use Section 2.3.4 for coalesced access, the transpose example and bank-conflict padding; Section 2.5 for streams, events, synchronization and the stream-capture intro; and Section 4.2 for graph creation, update and capture constraints. This is the API reference beside the book chapters.

Also in this section

  • Programming Massively Parallel Processors, 4th edition - Chapters 6 and 9 to 12Wen-mei Hwu, David Kirk and Izzat El Hajj · primary

    Read thread coarsening in Chapter 6, then Chapters 9 (histogram), 10 (reduction), 11 (prefix sum) and 12 (merge, optional). Work the exercises that test work, depth, contention and boundary handling.

  • Efficient Matrix Transpose in CUDA C/C++NVIDIA · required

    Rebuild copy, naive transpose, coalesced transpose and padded shared-memory variants. Update deprecated details for the installed toolkit and compare requested transactions, bank behavior and achieved bandwidth on odd as well as friendly shapes.

  • Optimizing Parallel Reduction in CUDANVIDIA · required

    Implement the optimization sequence from interleaved addressing through sequential addressing, first-add-during-load, unrolling and warp-level completion. Correct outdated assumptions and retain the stage where each optimization stops helping.

  • Single-pass Parallel Prefix Scan with Decoupled Look-backNVIDIA Research · depth

    Read after two-pass scans pass. Derive the state and progress argument, then implement or inspect a bounded version only if the available hardware and time support meaningful comparison.

  • Online Normalizer Calculation for SoftmaxOnline Softmax Authors · required

    Derive the running maximum and normalizer recurrence, test extreme and all-masked rows, and compare materialized, two-pass and online implementations before using the recurrence inside attention.

  • LeetGPU - CUDA Primitive ChallengesAlphaGPU · required

    Solve challenge 3 Matrix Transpose, 4 Reduction, 5 Softmax, 13 Histogramming and 16 Prefix Sum in CUDA. Add 70 Segmented Prefix Sum or 72 Stream Compaction only after the required set. Keep local source, hidden-shape assumptions, hardware, raw timings and correctness evidence outside the leaderboard.

  • GPU MODE - Reductions and ScansGPU MODE · support

    Use Lectures 9, 20, 21 and 24 after the PMPP implementations. Reproduce one faster scan or reduction idea and show the exact shape and device regime where it changes the bottleneck.

  • MIT 6.S894 Accelerated Computing (Fall 2025) - Lectures 6, 7 and 9 and Lab 7MIT · support

    Use Lecture 6 for host-device copies and streams, and Lectures 7 and 9 for map, stencil, reduce, compaction, scan, segmented scan, histogram and merge. Do Lab 7 (Run-Length Compression, with its scan and shuffle warm-ups) built for your own GPU.