Phase 04/Faster kernels and memory/CUDA Graphs and kernel fusion
PHASE 04 · Faster kernels and memory

CUDA Graphs and kernel fusion

0%
7 h5 subtopics2 lessons · 1 required
In plain English

A GPU does its work in small jobs called kernels, and the CPU has to hand each one over before it can run. When a model generates one token at a time, each step is hundreds of tiny jobs, and the hand-over itself takes longer than the job. Two tricks fix this. Kernel fusion merges several tiny jobs into one, like asking a courier to deliver three parcels in one trip instead of three. CUDA Graphs record the whole sequence of jobs once and then replay the recording with a single command, like a factory pressing play on a pre-programmed robot arm instead of a worker reading instructions aloud step by step. Neither changes the math; both remove the time the GPU would otherwise spend waiting for the next instruction.

Why it matters

For small batch decode the GPU can sit idle most of the time waiting on kernel launches. vLLM, SGLang and TensorRT-LLM all capture decode steps into CUDA Graphs and fuse elementwise ops into matmuls, which can double tokens per second on small models. Knowing when a graph can and cannot be captured explains many engine configuration flags.

Hiring signal

Skills this topic builds, with the number of the 46 analysed job postings that ask for each. Companies asking: Anthropic, Anyscale, Baseten, Cerebras, CoreWeave, Fireworks, Hugging Face, Liquid AI, Modal, nvidia, OpenAI, Perplexity, Thinking Machines, Together AI, xAI.See all skills →

Learning objectives

  • Measure kernel launch overhead and show when it dominates a decode step.
  • Capture a model forward pass into a CUDA Graph and measure the replay speedup.
  • Explain the constraints on graph capture (static shapes, static addresses, no CPU sync) and how engines work around them.
  • Identify fusion opportunities in a transformer block and verify torch.compile fuses them.

Key concepts

Kernel launch overhead
The few microseconds of CPU and driver work per kernel; dominates when kernels run in under 10 microseconds.
CUDA Graph
A recorded DAG of kernels and memory operations that can be launched as a single unit.
Graph capture
Running code under torch.cuda.graph so launches are recorded rather than executed.
Static shapes and addresses
Captured graphs replay the same kernels with the same pointers, so inputs must be copied into fixed buffers.
Padded batch buckets
Capturing one graph per batch size (1, 2, 4, 8...) and padding requests up to the nearest bucket.
Kernel fusion
Combining several operations into one kernel so intermediates stay in registers instead of round-tripping through HBM.
Vertical versus horizontal fusion
Fusing a chain of dependent ops (matmul then bias then GELU) versus fusing independent ops that run side by side (q, k, v projections).
torch.compile / Inductor
PyTorch's compiler that generates fused Triton kernels and can wrap them in CUDA Graphs with mode reduce-overhead.

Subtopics

  1. 1. Where launch overhead comes from

    Python dispatch, ATen, the CUDA driver and the hardware queue; measuring it with tiny kernels and with a profiler timeline.

  2. 2. Capturing and replaying a graph

    torch.cuda.CUDAGraph, warmup on a side stream, static input and output tensors, and the replay call.

  3. 3. Capture constraints and engine workarounds

    No dynamic shapes, no host sync, no allocation changes; vLLM captures per batch-size bucket and only for decode.

  4. 4. Fusion patterns in transformers

    Fused QKV projection, fused bias+activation, fused residual+norm, fused RoPE; what memory traffic each removes.

  5. 5. Compiler-driven fusion

    torch.compile and Inductor generate fused Triton kernels; reading the generated code to see which ops were merged.

Resources

Hands-on lessons

L1

Capture GPT-2 decode into a CUDA Graph on a T4

Colab T4 · freenotebook120 minrequired

Goal · Measure the per-step latency of a batch-1 GPT-2 decode step eagerly versus replayed from a CUDA Graph, and count the kernels per step.

  1. 1Load gpt2 in float16 on the Colab GPU; build a static input_ids tensor of shape (1, 1) and a static past_key_values of fixed length.
  2. 2Time 100 eager forward calls with torch.cuda.Event, after 10 warmup calls.
  3. 3Use torch.profiler for one eager step and count the number of CUDA kernels launched.
  4. 4Warm up on a side stream, then capture one forward step with torch.cuda.graph(g) writing into static output tensors.
  5. 5Time 100 g.replay() calls and compare to eager; compute the ratio.
  6. 6Try torch.compile(model, mode="reduce-overhead") on the same step and record its time as a third column.
  7. 7Change the input shape to (2, 1) and observe what happens to the captured graph; write down why.
Deliverable
A table of eager, graph-replay and compiled per-step latency plus the kernel count.
Check
Graph replay is at least 1.5x faster than eager at batch 1; the kernel count per step is in the hundreds, explaining why.
Fallback
On CPU, measure Python dispatch overhead instead by timing 100 forward steps with and without torch.compile and comparing per-step time; the gap shows the same launch-overhead idea.
L2

Watch torch.compile fuse a transformer MLP

CPU · your Macreading-code60 minoptional

Goal · Compile a small MLP block, read the generated code, and count how many kernels replaced the original ops.

  1. 1Define mlp(x) = linear2(gelu(linear1(x) + bias)) with d=768 in plain PyTorch.
  2. 2Run with TORCH_LOGS="output_code" and torch.compile(mlp) on CPU; save the generated C++/Triton-style code to a file.
  3. 3List the original ATen ops (torch.profiler or TORCH_LOGS="aot_graphs") and the fused kernels in the output.
  4. 4Mark on the original op list which ops were fused together and which remained separate matmuls.
  5. 5Explain why bias+GELU fused into one loop but the matmuls did not.
Deliverable
The saved generated code with an annotated op list.
Check
You can point to the single generated loop that computes bias add and GELU together.

Build your own

Build your own fused decode step with CUDA Graphs

PythonColab T4 · free~7 h

Take one GPT-2 decode step from hundreds of eager kernel launches to a captured graph of fused kernels, and measure every millisecond you removed on a T4.

The real thing: github.com/vllm-project/vllm/blob/main/vllm/v1/worker/gpu_model_runner.py ↗

How you know a stage passes

Write tests/test_decode.py first. Every stage asserts that 64 greedy tokens from your decode path equal transformers' generate(do_sample=False) for 5 prompts, then records two numbers with torch.profiler and cuda events: kernel launches per decode step and median per-step latency over 50 steps after 10 warmup steps. bench.py appends a row per stage to results.csv. Run `!pytest -q` on Colab; a stage is done when its test passes, all earlier tests still pass, and the row is written.

Stages, in order. Each one leaves you with something that runs.0/6
  1. 01an eager decode step with a static KV cache
    GPT-2-small fp16 runs one decode token per call against a preallocated [layers, 2, batch, heads, max_len, head_dim] cache with a device-side position counter, no Python-side shape changes.
    test · Tokens match transformers; the profiler shows more than 200 kernel launches per step and your CSV row records the eager latency.
  2. 02capture and replay
    Static input and output buffers, three warmup iterations on a side stream, then torch.cuda.CUDAGraph capture of the whole step and graph.replay() per token.
    test · Replayed tokens match eager for all 64 steps; per-step latency at batch 1 drops by at least 1.5x; kernel count per step is unchanged, proving the gain is launch overhead.
  3. 03the pointer trap
    Position ids, the cache write index and the attention length live in device tensors updated in place; a test demonstrates what happens when a captured Python int is changed instead.
    test · A deliberately wrong version that rebinds position_ids to a new tensor after capture produces tokens that diverge from eager within 64 steps, and the in-place version does not; both assertions are in the test file.
  4. 04batch-size buckets with padding
    One graph per bucket in 1, 2, 4, 8, 16; a batch of size b is padded to the next bucket and the padded rows are discarded.
    test · Batches of 3 and 5 route to buckets 4 and 8 and produce the same tokens as eager for every real row; the test prints bytes held by each captured graph's private pool.
  5. 05fused Triton kernels inside the graph
    Residual-add plus LayerNorm and bias plus GELU become one Triton kernel each, replacing the PyTorch ops before capture.
    test · Fused outputs are allclose to the PyTorch ops (atol 1e-3 in fp16); kernel launches per step fall by at least 36 (24 add-norm pairs and 12 bias-GELU pairs in 12 layers); tokens still match.
  6. 06compare with torch.compile and write it up
    The same decode step under torch.compile(mode="reduce-overhead") joins the table, and the README explains each row's gain.
    test · results.csv has rows eager, graph, graph+fused and compile with latency and kernel count; your graph+fused latency is within 1.3x of torch.compile's; the README names which fusion torch.compile found that you did not, or states that it found none.

No GPU? On your Mac run stages 1, 3 and 5 on CPU with TRITON_INTERPRET=1 for correctness; graph capture needs a CUDA device, so record stages 2, 4 and 6 as pending until a Colab session is available.

Knowledge check

QWhy do CUDA Graphs help batch-1 decode much more than large-batch prefill?

Batch-1 decode kernels run in a few microseconds each, so launch overhead is a large fraction of step time; prefill kernels run for milliseconds and overhead is negligible.

QName two things that break CUDA Graph capture.

Dynamic tensor shapes or new allocations between replays, and any CPU-GPU synchronization such as .item() or printing a tensor during capture.

QHow does vLLM handle varying batch sizes with CUDA Graphs?

It captures one graph per batch-size bucket during startup and pads the live batch up to the nearest captured size.

QWhat does kernel fusion save, in terms of the memory hierarchy?

The intermediate tensor between two ops stays in registers or shared memory instead of being written to and read back from HBM.

Completion

  • All 5 subtopics marked done
  • All 1 required lessons done
  • All subtopics marked completed.
  • Lesson l1 latency table saved and the check passes.
  • Can list the capture constraints and explain the padded-bucket workaround.
Topic progress is derived; it reaches 100% when both checks above pass.Next recommended topic →