Optimization & decoding4 min read

torch.compile for LLM inference: fusion, shapes, and guards

Eager PyTorch executes one Python operator at a time, reading and writing intermediate tensors back to GPU memory between every small RMSNorm, rotary embedding, and activation gate. torch.compile traces those operations into fused GPU kernels—provided you keep dynamic token shapes and guard recompilations under control.

Conceptual illustration of separate operator blocks fusing into one streamlined kernel channel.
Operator fusion folds intermediate pointwise reads and writes into registers instead of round-tripping through HBM.

What torch.compile changes in an inference forward pass

In eager mode, an expression such as silu(gate) * up or x * rsqrt(mean(x * x) + eps) launches multiple separate CUDA kernels. Every kernel reads its input tensor from HBM and writes its temporary output back to HBM before the next kernel starts. `torch.compile` captures the PyTorch graph with TorchDynamo and lowers it through TorchInductor into fused Triton or C++ kernels that keep intermediate values in on-chip registers.

Components of the PyTorch 2 compilation stack during inference.
ComponentRole during `torch.compile`What can go wrong
TorchDynamoIntercepts Python bytecode, records tensor ops into FX graphs, and emits shape/type guardsData-dependent Python control flow causes graph breaks
AOTAutogradTraces underlying ATen decompositions (forward-only under torch.inference_mode())Custom C++ ops without meta/fake-tensor registrations fail tracing
TorchInductorFuses pointwise and reduction ops into Triton/CUDA kernels and optionally wraps CUDA graphsFirst-run compilation latency adds cold-start seconds or minutes

Fusion helps non-matmul glue most: RMSNorm, Rotary Position Embeddings, SwiGLU, residual additions, and quantization dequant/scale steps. Large projections still call tuned cuBLAS or CUTLASS Tensor Core routines, while Inductor fuses surrounding epilogues and pointwise chains.

Visual explanation

From eager PyTorch ops to fused device kernels

  1. TorchDynamoCapture Python tensor ops into an FX graph and attach shape guards.
  2. AOTAutogradLower composite PyTorch ops into primitive ATen decompositions.
  3. TorchInductorFuse pointwise chains and epilogues into Triton or C++ kernels.
  4. Cached executionReuse compiled artifacts whenever runtime guards match.
Compilation flow under torch.inference_mode(). Large matrix multiplications still dispatch to cuBLAS or CUTLASS, while surrounding normalizations, rotary embeddings, and activations fuse to cut HBM traffic.

Calculate the HBM round-trips fusion eliminates

Consider an unfused SwiGLU activation y = silu(g) * u over hidden states of shape [tokens, intermediate_size]. Eager execution reads g, writes s = silu(g), then reads s and u to write y—five tensor transfers instead of reading g and u once and writing y once. This script counts that traffic across 32 layers.

Run with Python 3; no GPU or packages required
tokens = 2048
intermediate = 14336  # Llama 3.1 8B MLP width
bytes_per_elem = 2    # BF16
layers = 32

tensor_bytes = tokens * intermediate * bytes_per_elem
unfused_bytes = 5 * tensor_bytes * layers  # read g, write s, read s, read u, write y
fused_bytes = 3 * tensor_bytes * layers    # read g, read u, write y

print(f"One [2048, 14336] BF16 tensor: {tensor_bytes / 2**20:.1f} MiB")
print(f"Unfused 32-layer SwiGLU traffic: {unfused_bytes / 2**30:.2f} GiB")
print(f"Fused   32-layer SwiGLU traffic: {fused_bytes / 2**30:.2f} GiB")
print(f"HBM traffic avoided: {(unfused_bytes - fused_bytes) / 2**30:.2f} GiB per pass")
Calculated output
One [2048, 14336] BF16 tensor: 56.0 MiB
Unfused 32-layer SwiGLU traffic: 8.75 GiB
Fused   32-layer SwiGLU traffic: 5.25 GiB
HBM traffic avoided: 3.50 GiB per pass

Saving 3.5 GiB of HBM reads and writes on a single pointwise activation across 32 layers illustrates why compiler fusion matters even when cuBLAS already handles the matrix multiplications. Practice writing the forward pass yourself in SwiGLU Feed-Forward Layer and RMSNorm.

Why dynamic prompt lengths trigger guard recompilations

Before TorchDynamo reuses a compiled graph, it checks lightweight C++ guards verifying that tensor dtypes, devices, aliasing, and shape assumptions still hold. If a graph was specialized to seq_len == 512 and the next request arrives with 513 tokens, the guard fails and PyTorch recompiles—stalling a live request for seconds until the recompile limit falls back to eager execution. PyTorch dynamic shapes manual.

  • Wrap inference in `torch.inference_mode()`. Otherwise Dynamo traces autograd bookkeeping and keeps activation tensors alive unnecessarily.
  • Mark sequence and batch axes dynamic with torch._dynamo.mark_dynamic(input_ids, 1) or dynamic=True when serving variable-length prompts in custom PyTorch services.
  • Avoid `mode="reduce-overhead"` with changing shapes. That mode wraps Inductor output in CUDA graphs, recording a separate static graph allocation for every distinct input shape until GPU memory runs out. PyTorch `torch.compile` LLM optimization guide.

How vLLM combines torch.compile with paged attention

Production engines cannot compile an entire serving step into a single static CUDA graph because custom C++/CUDA paged-attention kernels depend on dynamic per-sequence block tables and variable prompt lengths. vLLM solves this with piecewise compilation: TorchDynamo splits the transformer model at attention boundaries, compiles the dense linear/norm/MLP subgraphs once with symbolic token counts (SymInt), and captures CUDA graphs for those compiled subgraphs at fixed token budgets while letting paged attention run dynamically in between. vLLM `torch.compile` architecture.

Validate compiled models before serving traffic

  1. Audit graph breaks first. Run TORCH_LOGS="graph_breaks,recompiles" on representative short, medium, and max-length requests during staging.
  2. Warm up every bucket outside timed benchmarks. Separate compilation time from steady-state TTFT and TPOT.
  3. Verify numerical parity. Fused BF16/FP16 reductions reorder floating-point additions; compare greedy token agreement and task accuracy against an eager baseline.
  4. Build fluency in PyTorch internals. Start with our free What is PyTorch? lesson and continue through compilation and export in the PyTorch course.

torch.compile inference FAQ

Does torch.compile replace FlashAttention or vLLM?

No. torch.compile fuses PyTorch tensor operations inside a model, while FlashAttention provides specialized tiled attention kernels and vLLM supplies paged KV memory, continuous batching, and piece-by-piece compilation integration.

Why was my first request 100× slower after adding torch.compile?

TorchInductor compiles and autotunes Triton/CUDA kernels lazily on the first forward pass that matches a shape signature; always run warmup requests before opening readiness probes to live traffic.

Should I use fullgraph=True in production model code?

Use fullgraph=True in unit tests on isolated transformer blocks to catch accidental Python graph breaks early, while allowing controlled splits around custom serving ops at the top level.

Sources and further reading

Primary documentation and research behind this guide.

  1. PyTorch tutorial: Introduction to torch.compile
  2. PyTorch documentation: Dynamic shapes in torch.compiler
  3. PyTorch recipe: Compile time caching in torch.compile
  4. vLLM v0.30.0: torch.compile integration and piecewise compilation

Keep learning

Related guide · 5 min readCUDA memory hierarchy and graphs for LLM inferenceRelated guide · 7 min readLLM inference optimization: practical guide to low latencyRelated guide · 5 min readFlashAttention vs PagedAttention: what each optimizesRelated guide · 7 min readvLLM vs SGLang: measured comparison and benchmark planAcademy course · 9 unitsInference Engineering FoundationsAcademy course · 13 unitsvLLMAcademy course · 20 unitsPyTorchAcademy course · 18 unitsCUDA from zero
Back to all articles