torch.compile is a function that transforms a PyTorch model or function into an optimized, compiled version. Its primary mechanism is graph capture, where it traces Python operations to build a static, intermediate representation (IR) graph. This graph is then passed through a series of compiler passes—most critically, operator fusion—which merge many small operations into fewer, larger kernels to minimize launch overhead and improve memory locality. The optimized graph is finally lowered to efficient hardware-specific code via a backend like Inductor, which generates tailored CUDA or CPU kernels.
Glossary
torch.compile

What is torch.compile?
torch.compile is PyTorch's just-in-time (JIT) compiler, introduced in PyTorch 2.0, designed to accelerate model execution by capturing a computational graph and applying a suite of aggressive low-level optimizations.
The compiler operates in several distinct modes, defined by the mode argument: 'default' balances compilation speed and performance, 'reduce-overhead' optimizes for small models by minimizing Python overhead, and 'max-autotune' exhaustively searches for the fastest kernels. A key optimization is automatic fusion of adjacent operators (e.g., combining linear, batch norm, and ReLU layers), which drastically reduces the number of kernel launches and intermediate tensor writes to global memory. This makes torch.compile a foundational tool for inference optimization, directly reducing latency and improving throughput for production deployments.
Key Features and Capabilities
torch.compile is PyTorch's just-in-time (JIT) compiler, designed to accelerate model execution by capturing a computational graph and applying a suite of aggressive optimizations, most notably operator and kernel fusion via its default Inductor backend.
Graph Capture & Dynamo
The first stage of torch.compile uses TorchDynamo to safely and efficiently capture PyTorch operations into a FX Graph—a traceable intermediate representation (IR). Unlike previous PyTorch JIT tracers, Dynamo operates at the Python bytecode level, allowing it to handle dynamic control flow and complex Python features while identifying sequences of tensor operations suitable for compilation. This captured graph is the substrate for all downstream optimizations.
Operator Fusion via Inductor
The default backend for torch.compile is Inductor, a deep learning compiler that generates high-performance Triton or C++/OpenMP kernels. A primary optimization is operator fusion, where adjacent operations in the graph are merged:
- Elementwise Fusion: Combines pointwise ops (e.g.,
silu,add) into single kernels. - Vertical Fusion: Chains a producer op (e.g.,
matmul) with its consumer (e.g.,gelu). - Horizontal Fusion: Merges independent ops that share an input. Fusion reduces kernel launch overhead and minimizes costly round-trips to global GPU memory by keeping intermediate results in registers or shared memory.
Backend Selection & Modes
torch.compile supports multiple backends, allowing a trade-off between compilation speed and runtime performance:
inductor(default): The most aggressive, generating fused Triton/C++ kernels.aot_eager: Extracts the graph but runs it with eager-mode PyTorch operators; useful for debugging.cudagraphs: Uses CUDA Graphs to capture and replay entire GPU work sequences, reducing launch latency.ipex: Intel's backend for CPU optimization. Themodeparameter further tailors behavior:"default"for balanced optimization,"reduce-overhead"to minimize framework overhead for small graphs, and"max-autotune"for exhaustive kernel search.
Dynamic Shape Support
A core challenge for graph compilers is handling inputs with varying shapes (e.g., variable sequence lengths). torch.compile addresses this through symbolic shape propagation. The compiler creates symbolic representations (e.g., s0, s1) for dynamic dimensions, allowing it to generate a single, reusable kernel that works for a range of concrete shapes, avoiding recompilation for every new input size. This is critical for production workloads with non-uniform data.
Performance Profile & Use Cases
The performance benefit of torch.compile is workload-dependent. It excels with:
- Compute-bound models: Where fusion increases arithmetic intensity.
- Sequences of small ops: Where kernel launch overhead dominates.
- Compilation time is amortized: Over many subsequent inference runs (e.g., in serving). Typical speedups range from 1.1x to 3x+ for compatible models. It is less beneficial for models dominated by a single, already-optimized kernel (e.g., a large, unfusable matrix multiplication).
torch.compile Backends: A Technical Comparison
A comparison of the primary backends available for PyTorch's torch.compile, focusing on their optimization approaches, hardware targets, and integration characteristics.
| Feature / Metric | `'inductor'` (Default) | `'aot_eager'` | `'cudagraphs'` | `'nvprims'` |
|---|---|---|---|---|
Primary Optimization Strategy | Graph capture & aggressive operator fusion via Triton | Graph capture only (no kernel fusion) | CUDA Graph capture for launch fusion | Direct mapping to NVIDIA Primitive ops |
Target Hardware | NVIDIA & AMD GPUs (via Triton), CPUs (via C++/OpenMP) | Any device (eager-mode fallback) | NVIDIA GPUs only | NVIDIA GPUs only |
Kernel Generation | JIT-generated Triton & C++ kernels | None (uses PyTorch's eager kernels) | Captures & replays existing eager kernels | Lowers to NVIDIA's pre-compiled Primitives |
Operator Fusion Capability | Extensive, pattern-based & heuristic-driven | None | Coarse-grained (kernel sequence fusion) | Limited, primitive-level composition |
Compilation Overhead | Moderate to High (JIT compilation) | Very Low (graph capture only) | Low (graph capture + CUDA Graph creation) | Low to Moderate |
Best For | Maximizing throughput on supported GPUs | Debugging, correctness checking | Reducing launch overhead on stable graphs | Leveraging NVIDIA's optimized primitive library |
Integration with | Full support for static graphs | Supported | Limited | Experimental |
Memory Optimization | Aggressive (via fused kernels & in-place ops) | Minimal | Moderate (via CUDA Graph memory pooling) | Depends on underlying primitives |
Primary Optimization Techniques
torch.compile is PyTorch's just-in-time (JIT) compiler that transforms eager-mode PyTorch code into an optimized, fused computational graph, primarily leveraging the Inductor backend to generate high-performance kernels.
Graph Capture & Lowering
The first phase of torch.compile involves tracing the model's execution to capture a computational graph (FX Graph). This graph is then lowered through a series of intermediate representations (IRs). Key steps include:
- Operator Decomposition: Breaking down complex PyTorch operators into simpler, primitive operations.
- Pattern Matching: Identifying subgraphs amenable to fusion (e.g.,
matmul+add). - Device-Specific Lowering: Translating the graph to backend-specific IRs like Triton for GPUs or C++/OpenMP for CPUs.
Operator & Kernel Fusion
A core optimization where adjacent operations are merged into a single fused kernel. This reduces kernel launch overhead and minimizes costly reads/writes to global memory (DRAM). torch.compile with Inductor performs:
- Vertical Fusion: Chaining dependent ops (e.g.,
silu->mul). - Horizontal Fusion: Combining independent ops that share an input.
- Pointwise Fusion: Merging element-wise operations like
add,relu, andsigmoid. The compiler uses a cost model to decide fusion profitability, balancing improved compute intensity against potential register pressure.
The Inductor Backend
The default and most advanced backend for torch.compile. Inductor generates high-performance GPU code via Triton and efficient CPU code via OpenMP. Its workflow:
- Receives a lowered IR graph.
- Schedules loops for optimal parallelism and memory access.
- Codegens kernel source code in Triton or C++.
- Compiles the generated source just-in-time. Inductor's scheduling includes loop tiling, vectorization, and shared memory promotion to maximize hardware utilization.
Dynamic Shape Support
torch.compile can handle inputs with dynamic shapes (e.g., variable batch sizes, sequence lengths). It avoids recompilation for every new shape through:
- Symbolic Shapes: Using symbolic variables (e.g.,
s0,s1) to represent dimensions in the captured graph. - Guarded Execution: The first run records concrete shapes and installs guards. If a subsequent input matches the guards, the cached kernel is reused.
- Recompilation: If guards are violated (e.g., a new sequence length), the graph is recompiled automatically. The
mode="reduce-overhead"is optimized for dynamic shapes.
Compilation Modes & Trade-offs
torch.compile offers modes that balance optimization time (compile latency) vs. runtime performance:
mode="default": Full optimizations. Highest runtime speed, slower first run.mode="reduce-overhead": Reduces Python overhead with lighter graph breaks. Good for dynamic shapes and small graphs.mode="max-autotune": Extensive search for optimal kernel configurations (e.g., tile sizes). Slowest compilation, best peak performance for large, stable workloads. Usefullgraph=Trueto enforce a single graph with no Python fallbacks, maximizing speed if the model is fully capturable.
Integration with PyTorch Eager
torch.compile is designed for seamless use with standard PyTorch:
- No Code Rewrite: Decorate a
nn.Moduleor function; eager-mode code works unchanged. - Python Interoperability: Supports most Python control flow, which is captured via graph breaks. Complex flow may trigger fallback to eager execution.
- Debugging: Tools like
torch._dynamo.explain()help identify graph breaks and compilation issues. - Compatibility: Integrates with Distributed Data Parallel (DDP), Autograd, and most of the PyTorch ecosystem, including custom operators.
Frequently Asked Questions
torch.compile is PyTorch's just-in-time (JIT) compiler, designed to accelerate model execution through graph-level optimizations like operator fusion. These questions address its core mechanisms, use cases, and performance characteristics.
torch.compile is PyTorch's just-in-time (JIT) compiler that transforms a PyTorch model's execution from eager, line-by-line mode into an optimized, graph-based representation for faster inference and training. It works by tracing a model's operations to create a computational graph, then applies a series of graph-level optimizations—most notably operator fusion—before compiling the optimized graph into efficient, low-level kernels for the target hardware via a backend like Inductor.
Internally, the process involves:
- Graph Capture: The model's forward pass is traced, converting Python operations into a static, intermediate representation (IR) graph.
- Graph Optimization: The compiler pass performs transformations on this graph, such as fusing adjacent operations (e.g.,
conv2d+batch_norm+relu) into single kernels to minimize kernel launch overhead and intermediate memory transfers. - Code Generation: The optimized graph is lowered to hardware-specific code (e.g., CUDA for NVIDIA GPUs, C++ for CPU) by the selected backend compiler.
Enabling Efficiency, Speed & Accuracy
Intelligent Analysis, Decision & Execution
We build AI systems for teams that need search across company data, workflow automation across tools, or AI features inside products and internal software.
Talk to Us
Search across company data
Give teams answers from docs, tickets, runbooks, and product data with sources and permissions.
Useful when people spend too long searching or get different answers from different systems.

Automate internal workflows
Use AI to route work, draft outputs, trigger actions, and keep approvals and logs in place.
Useful when repetitive work moves across multiple tools and teams.

Add AI to products and internal tools
Build assistants, guided actions, or decision support into the software your team or customers already use.
Useful when AI needs to be part of the product, not a separate tool.
Related Terms
torch.compile is a just-in-time compiler that accelerates PyTorch models by capturing a computational graph and applying a suite of low-level optimizations. Its core mechanism for performance gains is operator and kernel fusion, which reduces overhead and improves memory locality.
Operator Fusion
Operator fusion is a graph-level optimization that merges adjacent computational operators in a neural network's computational graph into a single, compound operation. This minimizes the need to write intermediate results to slow global memory (e.g., GPU VRAM) and read them back, which is a major bottleneck.
- Mechanism: The compiler identifies chains of operations (e.g.,
linear -> relu -> dropout) and replaces them with a single, custom operator. - Benefit: Dramatically reduces memory bandwidth pressure, which is critical for performance on accelerators.
- In
torch.compile: This is a primary optimization performed by the Inductor backend, which fuses pointwise, reduction, and other compatible operations.
Kernel Fusion
Kernel fusion is the low-level implementation of operator fusion. It involves generating a single fused kernel—a GPU or accelerator function—that executes the logic of multiple primitive operations without intermediate synchronization or global memory traffic.
- Key Difference: While operator fusion is a graph transformation, kernel fusion is the actual code generation that makes it efficient.
- Goal: Amortize kernel launch overhead and maximize data reuse in fast on-chip caches (L1, shared memory).
- Example: A fused
matmul -> add -> gelukernel performs all calculations while the data is still in registers or shared memory, avoiding costly round-trips to VRAM.
Inductor Backend
Inductor is the default and most advanced lowering backend for torch.compile. It translates PyTorch operations into high-performance GPU or CPU code, with fusion as a central optimization.
- Process: It first captures a FX graph from PyTorch code, then applies fusion and other optimizations, and finally generates code in Triton (for GPUs) or C++/OpenMP (for CPUs).
- Fusion Strategy: Uses a fusion planner and cost model to decide which groups of operators (fusion groups) are profitable to combine, balancing improved locality against potential downsides like increased register pressure.
- Output: Produces highly optimized, fused kernels that are just-in-time compiled for the specific model and input shapes.
Graph Capture (FX)
Graph capture is the first step of torch.compile, where PyTorch's eager execution is intercepted to produce a static, intermediate representation (IR) of the computation. This is done using PyTorch's FX (torch.fx) framework.
- Purpose: Creates a traceable, manipulable dataflow graph of
nn.Moduleoperations. This graph is essential for all downstream compiler optimizations, including fusion. - How it works: It "symbolically traces" the model's forward pass, recording operations on proxy tensors to build the graph.
- Result: A Fusion Group is a subgraph within this IR that has been identified as a candidate for being turned into a single fused kernel.
Just-In-Time (JIT) Compilation
Just-In-Time (JIT) compilation is the execution model of torch.compile, where optimization and code generation occur at runtime, typically on the first invocation of the model with a given set of input shapes.
- Advantage over AOT: Allows optimizations (like fusion) to be tailored to the specific runtime context, including dynamic input shapes and the target hardware.
- Trade-off: Introduces a one-time compilation overhead ("warm-up" time) in exchange for faster subsequent executions.
- Dynamic vs. Static:
torch.compilesupports adynamic=Truemode for graphs with varying input shapes, which impacts how aggressive fusion can be.
Pattern Matching for Fusion
Pattern matching for fusion is the algorithmic process by which a compiler like Inductor identifies specific, profitable subgraph patterns within the computational graph that are canonical candidates for fusion.
- Common Patterns: Well-known sequences like Conv-BN-ReLU, Linear-GELU, or Scaled Dot-Product Attention are matched and replaced with a single, hand-optimized or generated fused kernel.
- Heuristics: The compiler uses fusion heuristics—rule-based or learned cost models—to decide if fusing a matched pattern will improve performance (fusion profitability).
- Example: The Fused Multi-Head Attention kernel (inspired by FlashAttention) is a result of pattern matching the entire attention mechanism for fusion.

About the author
Prasad Kumkar
CEO & MD, Inference Systems
Prasad Kumkar is the CEO & MD of Inference Systems and writes about AI systems architecture, LLM infrastructure, model serving, evaluation, and production deployment. Over 5+ years, he has worked across computer vision models, L5 autonomous vehicle systems, and LLM research, with a focus on taking complex AI ideas into real-world engineering systems.
His work and writing cover AI systems, large language models, AI agents, multimodal systems, autonomous systems, inference optimization, RAG, evaluation, and production AI engineering.
Partnered with leading AI, data, and software stack.
How We Work
Custom AI workflows for your Business
One-fit-all AI don't work for modern businesses. At Inferensys, we aim to understand your business & custom requirements; which we use to define most efficient agentic workflows, the data, and the tools for your business.
01
Review the use case
We understand the task, the users, and where AI can actually help.
Read more02
Pick the right approach
We define what needs search, automation, or product integration.
Read more03
Build the first useful version
We implement the part that proves the value first.
Read more04
Improve from there
We add the checks and visibility needed to keep it useful.
Read moreThe first call is a practical review of your use case and the right next step.
Talk to Us