GPUs & infrastructure5 min read

CUDA memory hierarchy and graphs for LLM inference

Two bottlenecks explain most single-GPU inference profiles: waiting on high-bandwidth memory to deliver weights and KV state, and waiting on the CPU to launch hundreds of tiny decode kernels. Understanding the CUDA memory hierarchy and CUDA graphs turns both from black-box flags into predictable engineering levers.

Conceptual illustration of tiered GPU memory plates beside a captured sequence of kernel nodes.
On-chip SRAM and registers feed Tensor Cores quickly while CUDA graphs replay multi-kernel decode steps under one launch.

The three memory tiers every inference kernel crosses

An NVIDIA GPU does not compute directly on tensors sitting in main device memory. Data moves upward through successively smaller, faster storage tiers before warp instructions touch a single floating-point value. The CUDA C++ Programming Guide defines the programmer-visible hierarchy:

Programmer-visible memory tiers on modern CUDA GPUs, ordered from fastest and smallest to largest and furthest from compute.
Memory tierScopeTypical role in LLM inference
RegistersOne threadAccumulate dot products, softmax maxima, and rescaling factors inside a kernel
Shared memory / L1 (SRAM)One thread block (SM)Stage matrix tiles and FlashAttention Q/K/V blocks on chip for reuse across threads
L2 cacheAll SMs on the GPUAbsorb repeated reads of shared metadata, scales, or hot prefix pages
Global memory (HBM)Whole GPUHold resident model weights, paged KV-cache pools, and inter-kernel activation tensors

On an NVIDIA H100 SXM, HBM3 delivers 3.35 TB/s while dense BF16 Tensor Cores reach nearly 990 TFLOPS. Dividing compute by bandwidth gives a ridge point near 295 FLOPs per byte: unless a kernel performs roughly 300 floating-point operations for every byte it loads from HBM, the Streaming Multiprocessors stall waiting for memory. Test this directly in our roofline latency calculator.

Why autoregressive decode stresses both HBM and the CPU

During prefill vs. decode, a 2,048-token prompt multiplies weight matrices against thousands of token rows at once, reusing each tile in SRAM and keeping Tensor Cores busy. During decode at small batch sizes, each linear projection multiplies weights against only a handful of rows, so execution time is bounded by HBM read traffic.

Fast HBM exposes a second bottleneck that surprises newcomers: CPU kernel-launch overhead. A 32-layer or 64-layer transformer executes hundreds of individual operations per generated token—RMSNorm, QKV projections, rotary embeddings, paged attention, output projections, and SwiGLU MLPs. When each GPU kernel finishes in 5 to 15 microseconds on an H100 or H200, a host Python and driver dispatch cost of 8 to 20 microseconds per kernel leaves the GPU idle between launches.

Calculate when CPU launch overhead overtakes GPU work

This standalone script compares pure HBM weight-read time against cumulative host dispatch gaps for an illustrative 8B FP8 model across 36 layers. All launch timings are synthetic teaching inputs; measure your own host with Nsight Systems.

Run with Python 3; no GPU or packages required
# Illustrative decode step: 8.2B FP8 weights on a 3,350 GB/s GPU.
weight_bytes = 8.2e9
effective_bw_bytes_s = 3350e9 * 0.75  # 75% effective HBM bandwidth
pure_gpu_ms = (weight_bytes / effective_bw_bytes_s) * 1000

kernels_per_layer = 9
layers = 36
total_kernels = kernels_per_layer * layers

print(f"Idealized GPU weight-read time: {pure_gpu_ms:.2f} ms ({total_kernels} kernels/token)")
for cpu_gap_us in (0.0, 4.0, 10.0):
    exposed_ms = (total_kernels * cpu_gap_us) / 1000
    step_ms = pure_gpu_ms + exposed_ms
    print(f"  Exposed CPU gap {cpu_gap_us:4.1f} us/kernel -> "
          f"TPOT {step_ms:5.2f} ms ({1000 / step_ms:5.0f} tok/s)")
Calculated output
Idealized GPU weight-read time: 3.26 ms (324 kernels/token)
  Exposed CPU gap  0.0 us/kernel -> TPOT  3.26 ms (  306 tok/s)
  Exposed CPU gap  4.0 us/kernel -> TPOT  4.56 ms (  219 tok/s)
  Exposed CPU gap 10.0 us/kernel -> TPOT  6.50 ms (  154 tok/s)

Ten microseconds of unhidden host dispatch per kernel doubles TPOT in this illustrative example without running a single extra floating-point operation. Kernel fusion via `torch.compile` reduces total_kernels, while CUDA graphs eliminate per-kernel host submission.

How CUDA graphs capture and replay decode steps

A CUDA graph records a sequence of GPU kernel launches, arguments, and dependencies on a capture stream, instantiates them into an executable graph object, and replays the entire multi-hundred-kernel step from a single cudaGraphLaunch call. NVIDIA’s CUDA Graphs guide documents the capture and instantiation workflow, and PyTorch’s `torch.cuda.CUDAGraph` reference exposes it in Python.

  • Static tensor addresses. Graph replay reads inputs and writes outputs at the exact device memory pointers recorded during capture. Serving engines copy new token IDs and block-table indices into pre-allocated static input buffers before replaying.
  • Fixed shapes per captured graph. Because grid dimensions and tensor shapes are baked into each graph, vLLM and SGLang capture a discrete set of decode batch sizes at startup (for example, 1, 2, 4, 8, 16, 24, …) and pad an active batch of 6 sequences up to the 8-sequence graph.
  • Startup time and memory pool cost. Capturing dozens of batch sizes increases server startup time and reserves private graph memory pools, leaving slightly less VRAM for the KV cache.
Visual explanation

Eager kernel dispatch versus CUDA graph replay

Eager decodePer-kernel host launch
  1. Python + driver dispatchCPU prepares and launches each small op separately
  2. Short GPU kernels5–15 µs kernels leave idle gaps when host dispatch lags
  3. Repeat hundreds of timesLaunch overhead accumulates into milliseconds per token
CUDA graph replaySingle graph launch
  1. Capture once at startupRecord fixed-batch decode kernels on static buffers
  2. Copy step inputsWrite token IDs and block tables into static pointers
  3. Replay full stepOne cudaGraphLaunch runs kernels back to back on GPU
Conceptual comparison of host-driven eager dispatch and captured CUDA graph replay during autoregressive decode. Actual launch durations vary with CPU clock speed, Python path, and GPU generation.

Inspect kernels and graph replay in practice

  1. Check startup logs. Both vLLM and SGLang log the captured batch-size list and the GiB consumed by graph capture before serving requests.
  2. Budget graph memory explicitly. Reserve 1.5–3 GiB in the GPU memory calculator when running wide tensor parallelism or high --cuda-graph-max-bs.
  3. Spot gaps on a timeline. In Nsight Systems or torch.profiler, eager decode shows a staircase of tiny CUDA kernels separated by gaps on the GPU row; a captured graph packs kernels back to back under one host launch.
  4. Learn kernel mechanics from the ground up. Start with our free What is CUDA? lesson, then work through memory coalescing, shared-memory tiling, streams, and CUDA graphs in CUDA from zero.

CUDA memory and graphs FAQ

Why do LLM servers use CUDA graphs mainly for decode rather than prefill?

Prefill processes thousands of prompt tokens at arbitrary lengths, so individual kernels run long enough to hide CPU launch latency and dynamic sequence lengths would require too many static graph shapes—though piecewise compilation can still graph fixed-shape subgraphs.

Does shared memory (SRAM) hold the KV cache between decode steps?

No. Shared memory lives only for the duration of a thread block; persistent weights and KV-cache blocks stay in GPU HBM across steps and are staged into SRAM tile by tile during FlashAttention.

When should I lower --cuda-graph-max-bs or disable CUDA graphs?

When a model barely fits on your GPU and graph pool reservations starve the KV cache, or at very large batch sizes where GPU execution already dominates host dispatch.

Sources and further reading

Primary documentation and research behind this guide.

  1. NVIDIA: CUDA C++ Programming Guide — Memory Hierarchy
  2. NVIDIA H100 Tensor Core GPU specifications
  3. NVIDIA Developer Blog: Getting Started with CUDA Graphs
  4. PyTorch documentation: CUDA semantics and CUDAGraph
  5. vLLM v0.30.0: CUDA graphs design
  6. vLLM v0.30.0: conserving memory
  7. SGLang: server arguments and CUDA graph controls

Keep learning

Related guide · 4 min readtorch.compile for LLM inference: fusion, shapes, and guardsRelated guide · 7 min readLLM inference optimization: practical guide to low latencyRelated guide · 5 min readFlashAttention vs PagedAttention: what each optimizesRelated guide · 5 min readGPU memory for LLM inference: how to size and choose a GPUAcademy course · 9 unitsInference Engineering FoundationsAcademy course · 13 unitsvLLMAcademy course · 13 unitsSGLangAcademy course · 18 unitsCUDA from zero
Back to all articles