torch.compile
|
This content was generated with the assistance of AI and should be verified against the official documentation before being relied on in production. |
torch.compile is the PyTorch 2.x way to make eager code faster without rewriting it. It captures the PyTorch operations of a Python function or module into graphs, hands them to a compiler backend (by default TorchInductor) that fuses operations and generates optimised kernels, and caches the result. The model is still ordinary Python that you can debug in eager mode by removing one line. This page covers the mental model, every argument of the function, the practical training and inference patterns, and the standard pitfalls. Diagnosing graph breaks, recompilation and dynamic shapes in depth is the subject of Graph Breaks, Recompilation & Dynamic Shapes, and exporting a program to ship elsewhere is torch.export.
Examples were run on Python 3.13 with PyTorch 2.15 on 2026-10-31 (CPU, with torch.accelerator selecting Apple MPS where the code asks for an accelerator). All speed figures here are illustrative; measure your own workload.
How it works
-
TorchDynamo uses CPython’s frame-evaluation API to trace the Python code and extract graphs of PyTorch operations. Code it cannot trace causes a graph break: the graph is split, the troublesome Python runs eagerly, and tracing resumes afterwards. A graph break costs optimisation opportunities but does not change results.
-
AOTAutograd captures the backward pass ahead of time, so the backend can accelerate both forward and backward passes.
-
TorchInductor, the default backend, fuses operations and generates code for several accelerators. According to the
torch.compileroverview it targets NVIDIA, AMD and Intel GPUs through OpenAI Triton; the same overview lists CPU support through further backends (check the page for the current CPU story on your platform).
Where the speed comes from: fewer round trips to GPU memory because pointwise operations are fused into one kernel, and less Python overhead per operation. The tutorial notes that models that are strongly compute-bound (simple architectures with large data) see smaller gains, since the matrix multiplications themselves are already well optimised.
Basic usage
torch.compile can wrap a function, be used as a decorator, or wrap a module. Nested calls inside a compiled function are compiled recursively.
import torch
def fused(x, y):
a = torch.sin(x)
b = torch.cos(y)
return a + b
compiled_fused = torch.compile(fused)
@torch.compile
def also_compiled(x):
return torch.nn.functional.gelu(x) * 2
device = torch.accelerator.current_accelerator() or torch.device("cpu")
x = torch.randn(10_000, 10_000, device=device)
y = torch.randn(10_000, 10_000, device=device)
out = compiled_fused(x, y) # first call: compiles (slow)
out = compiled_fused(x, y) # later calls: reuse the compiled code
For modules there are two equivalent spellings. Compiling a module compiles its forward call and leaves the object as an nn.Module with the same parameters.
import torch
from torch import nn
model = nn.Sequential(nn.Linear(256, 1024), nn.GELU(), nn.Linear(1024, 10)).to(device)
compiled_model = torch.compile(model) # returns a wrapper around model
# or, in place:
model.compile()
logits = compiled_model(torch.randn(32, 256, device=device))
model.compile() is documented in the tutorial as equivalent to compiling the module’s __call__; the wrapper returned by torch.compile(model) shares parameters with the original.
The signature
The 2.15 reference gives:
torch.compile(
model,
*,
fullgraph=False,
dynamic=None,
backend=None, # None selects "inductor"
mode=None,
options=None,
name=None,
disable=False,
recompile_limit=None,
isolate_recompiles=False,
dynamic_shapes=None,
)
Calling it without model returns a decorator, so @torch.compile(mode="max-autotune") is valid. The parameters:
| Parameter | Meaning |
|---|---|
|
Default |
|
|
|
|
|
One of |
|
A dictionary of backend options, for Inductor listed by |
|
Naming of the compiled region and a finer control of dynamic dimensions; see the reference for their current semantics. |
|
Default |
|
How many recompilations this call allows before falling back to eager ( |
Modes
-
"default": a balance of performance and overhead. -
"reduce-overhead": uses CUDA graphs to cut Python and launch overhead, useful for small batches. It may use more memory, and the reference says it applies to CUDA-only graphs that do not mutate inputs. -
"max-autotune": uses Triton or template-based matrix multiplications and Triton convolutions on the GPU and enables CUDA graphs by default on the GPU. Compilation takes noticeably longer because many candidate kernels are benchmarked. -
"max-autotune-no-cudagraphs": like"max-autotune"but without CUDA graphs.
Selected options
The reference highlights these options keys: max_autotune (profile to pick the best matmul configuration), epilogue_fusion (fuse pointwise operations into templates, requires max_autotune), shape_padding (pad matrix shapes to align loads, helping tensor cores), triton.cudagraphs (CUDA graphs to cut overhead), fallback_random (helpful when debugging accuracy issues) and trace.enabled (the most useful debugging flag, which also enables output such as trace.graph_diagram). guard_filter_fn controls which Dynamo guards are saved; the docs call it unsafe with no backward-compatibility guarantee.
compiled = torch.compile(model, mode="max-autotune")
# mode and options cannot be combined; spell the mode's settings as options instead
tuned = torch.compile(model, options={"max_autotune": True, "shape_padding": True})
strict = torch.compile(model, fullgraph=True) # error on the first graph break
static = torch.compile(model, dynamic=False) # specialise on every shape
flexible = torch.compile(model, dynamic=True) # generalise over varying sizes
Warm-up, caching and benchmarking
The first call compiles, which is slow; the tutorial shows the first call taking roughly an order of magnitude longer than an eager call (about 0.45 s versus 0.036 s in its example), while later calls were about 2.85 times faster than eager on its hardware. Treat those numbers as an illustration. Consequences:
-
Always run a few warm-up iterations before timing, and time GPU work with CUDA events or
torch.cuda.synchronize()because kernel launches are asynchronous. -
Compilation is repeated for each new input shape signature that Dynamo specialises on, and for changes in guarded values (dtype, device, requires_grad, module flags such as
training). Switching betweenmodel.train()andmodel.eval()triggers a separate compilation of each. -
Compile cost is paid per process. For short jobs compilation can outweigh the savings; use
mode="default"there. For long training runs and serving it amortises quickly. The on-disk caches Inductor keeps are discussed in the compiler guides.
import time
import torch
model = torch.compile(model)
x = torch.randn(64, 256, device=device)
for _ in range(3): # warm-up: compile + autotune
model(x)
if device.type == "cuda":
torch.cuda.synchronize()
t0 = time.perf_counter()
for _ in range(100):
model(x)
if device.type == "cuda":
torch.cuda.synchronize()
print("ms/iter:", (time.perf_counter() - t0) * 10)
Using it in a training loop
Compile the model once, outside the loop, and use the compiled object for forward passes. The optimizer keeps the original parameters, which the compiled wrapper shares:
model = build_model().to(device)
opt = torch.optim.AdamW(model.parameters(), lr=1e-3)
compiled = torch.compile(model)
for x, y in loader:
x, y = x.to(device), y.to(device)
opt.zero_grad(set_to_none=True)
with torch.autocast(device_type=device.type, dtype=torch.bfloat16):
loss = torch.nn.functional.cross_entropy(compiled(x), y)
loss.backward()
opt.step()
Practical notes:
-
Keep batch shapes constant (use
drop_last=Truein the DataLoader, pad sequences to a small set of bucket lengths) to avoid repeated recompilation. See Workers, Pinned Memory & Samplers. -
Mixed precision composes with compilation; the reference notes that when backward runs outside autocast, as recommended, the config
torch._functorch.config.backward_pass_autocast(default"same_as_forward") should be set to"off"for the compiled region. See Mixed Precision with torch.amp. -
To compile only the expensive block of a large model (for example the repeated transformer layer) rather than the whole network, see Regional compilation below.
-
Compiled modules wrap the original:
compiled.state_dict()keys carry an_orig_mod.prefix. Save the state dict of the original module (model.state_dict()) so checkpoints load into uncompiled models. See Saving & Loading Models. -
Distributed training wraps first and compiles after, or compiles inside the wrapper, depending on the strategy; see DistributedDataParallel and FSDP2 (fully_shard).
Regional compilation
Compiling a large model whole can take minutes, mostly because Dynamo traces every one of dozens of identical blocks (transformer layers, residual stages). Regional compilation compiles the repeated block once and reuses the result, which cuts cold-start compile time while keeping most of the speed-up. There are two ways to do it:
-
Compile each block instead of the whole model (
layer.compile()ortorch.compile(layer)for every layer). Identical layers share the compiled code, so only the first one pays. Code outside the blocks (embeddings, head) stays eager. -
Keep compiling the whole model, but mark the block with
torch.compiler.nested_compile_region. Dynamo then compiles the marked region the first time it meets it and stamps the same compiled code out for every later call, recompiling only if shapes, dtypes or other guarded inputs change. Outsidetorch.compilethe decorator is a no-op.
import time
import torch
from torch import nn
class Block(nn.Module):
def __init__(self, dim: int = 256):
super().__init__()
self.norm = nn.LayerNorm(dim)
self.mlp = nn.Sequential(nn.Linear(dim, 4 * dim), nn.GELU(), nn.Linear(4 * dim, dim))
def forward(self, x):
return x + self.mlp(self.norm(x))
class RegionBlock(Block):
@torch.compiler.nested_compile_region # compile once, reuse for every layer
def forward(self, x):
return super().forward(x)
class Model(nn.Module):
def __init__(self, block=Block, depth: int = 24, dim: int = 256):
super().__init__()
self.layers = nn.ModuleList(block(dim) for _ in range(depth))
self.head = nn.Linear(dim, 10)
def forward(self, x):
for layer in self.layers:
x = layer(x)
return self.head(x)
x = torch.randn(32, 256)
# Option 1: compile only the repeated block; the head stays eager.
per_layer = Model()
for layer in per_layer.layers:
layer.compile()
# Option 2: compile the whole model, with the block marked as a nested region.
nested = torch.compile(Model(block=RegionBlock))
for name, m in [("per-layer", per_layer), ("nested region", nested)]:
t0 = time.perf_counter()
m(x) # the first call compiles
print(f"{name}: first call {time.perf_counter() - t0:.1f} s")
On the CPU used for this page the first call took about 1.2 s for the per-layer variant and 0.6 s for the nested-region variant, against 4.5 s for torch.compile(Model()) without a marked region; the absolute numbers depend on the machine and model. nested_compile_region also accepts max_reuse_entries (default 8) to cap how many differently-guarded variants of a region are cached.
Graph breaks and fullgraph
Data-dependent Python control flow (an if that tests a tensor value), calls into unsupported libraries, print of tensors and some in-place Python mutations split a function into several graphs with Python running between them. The tutorial’s example if b.sum() < 0: produces two graphs. Results stay correct, but each break reduces fusion opportunities and can add guard checks. Use fullgraph=True while developing a model that is supposed to compile cleanly: the first break becomes an error with an explanation. For control flow that must stay in the graph, the tutorial points to torch.cond. See the troubleshooting page for logging (TORCH_LOGS, torch._logging.set_logs(graph_breaks=True)) and fixes.
import torch
@torch.compile(fullgraph=True)
def clean(x):
return torch.relu(x) + 1
@torch.compile(fullgraph=True)
def with_break(x):
if x.sum() < 0: # data-dependent branch
return x - 1
return x + 1
clean(torch.randn(4))
try:
with_break(torch.randn(4))
except Exception as exc:
print("fullgraph error:", type(exc).__name__)
The tutorial also contrasts torch.compile with TorchScript: torch.jit.trace can silently produce wrong results on data-dependent control flow, while torch.jit.script needs annotations and errors on unsupported code; torch.compile handled the same cases without annotations. TorchScript is deprecated (see Legacy APIs & Migration).
Backends
"inductor" is the default for training and inference. The torch.compiler overview also lists "cudagraphs" (CUDA graphs with AOTAutograd) for training and inference, and inference-only backends such as "tensorrt" (requires importing torch_tensorrt), "openvino", "tvm" and "ipex". torch.compiler.list_backends() lists what your installation supports. The repository documentation of those third-party backends governs their installation and limits.
Requirements
The tutorial lists torch 2.0 or newer, a C++ compiler such as g{pp} and the Python development headers on the build machine, because Inductor generates and compiles code. On GPUs it relies on Triton, which ships with the standard CUDA wheels (see Installation & Versions). Hardware support follows Devices & Accelerators.
When to compile, and when not to
Good candidates: long training runs, inference services with stable shapes, models with many small pointwise operations (normalisation, activations, elementwise glue) and anything limited by launch overhead. Poor candidates: short scripts, heavily dynamic shapes or Python control flow that breaks the graph every call, and code whose bottleneck is the input pipeline or host-device copies. Profile first (Profiling with torch.profiler) and apply the other tips of Performance Tuning Guide.
If torch.compile raises an obscure error or gives different numbers, bisect:
-
Run with
torch.compile(model, disable=True)or remove the call to confirm eager is correct. -
Try
backend="eager"or"aot_eager"(listed bytorch._dynamo.list_backends(None)among the debug backends) to separate tracing problems from Inductor problems. -
Use
fullgraph=Trueto locate graph breaks. -
Use
fallback_randominoptionswhen random operations are involved. -
Compare outputs with
torch.testing.assert_closeusing tolerances; bitwise equality with eager is not expected (see Reproducibility & Determinism).
Compile versus export
torch.compile accelerates a program inside a running Python process and tolerates Python fallbacks. torch.export captures a whole graph for deployment to a runtime without Python and does not support graph breaks. Their roles and the follow-up paths (AOTInductor, ONNX, ExecuTorch) are compared in torch.export and Deploying & Serving Models. The eager-versus-compiled decision in the wider ecosystem is part of Choosing a Framework.