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.
| Component | Role during `torch.compile` | What can go wrong |
|---|---|---|
| TorchDynamo | Intercepts Python bytecode, records tensor ops into FX graphs, and emits shape/type guards | Data-dependent Python control flow causes graph breaks |
| AOTAutograd | Traces underlying ATen decompositions (forward-only under torch.inference_mode()) | Custom C++ ops without meta/fake-tensor registrations fail tracing |
| TorchInductor | Fuses pointwise and reduction ops into Triton/CUDA kernels and optionally wraps CUDA graphs | First-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.
From eager PyTorch ops to fused device kernels
- TorchDynamoCapture Python tensor ops into an FX graph and attach shape guards.
- AOTAutogradLower composite PyTorch ops into primitive ATen decompositions.
- TorchInductorFuse pointwise chains and epilogues into Triton or C++ kernels.
- Cached executionReuse compiled artifacts whenever runtime guards match.
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.
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")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 passSaving 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)ordynamic=Truewhen 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
- Audit graph breaks first. Run
TORCH_LOGS="graph_breaks,recompiles"on representative short, medium, and max-length requests during staging. - Warm up every bucket outside timed benchmarks. Separate compilation time from steady-state TTFT and TPOT.
- Verify numerical parity. Fused BF16/FP16 reductions reorder floating-point additions; compare greedy token agreement and task accuracy against an eager baseline.
- 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.
