torch.compile from the user's side

What happens between torch.compile(model) and the fused kernels, on the topic's running example: Dynamo, guards, graph breaks, recompiles and dynamic shapes, AOTAutograd's partitioner, Inductor's fusion, modes, compiled autograd, compile time and caches, torch.export and AOTInductor, and debugging. Recorded with torch 2.14.1 on an Apple M1 Pro (CPU unless marked); GPU numbers are quoted and labelled. Data as of October 2026. Reading: 36 min, plus 14 in closed details.

The idea in one screen

torch.compile captures your Python as a graph on the first call (Dynamo), derives the backward and chooses what the forward keeps for it (AOTAutograd), fuses both into kernels (Inductor), and reuses that code on every later call whose guards still pass. Everything you tune is one of three things: keep the graph whole, keep the guards passing, pay the compile once.

Fig. 1: the first call runs three compilers; every later call is a guard check

  1. First call, T = 64: three compilers. Nothing is cached. Dynamo reads the bytecode into a graph and writes guards; AOTAutograd derives the backward and cuts it from the forward; Inductor fuses both into kernels. For the whole training step: 59 graph ops and 549 guards, a joint graph of 646 ops cut into 271 forward and 427 backward that keeps 34.81 MB for backward (sections 1, 2, 5); one block's forward becomes 4 kernels plus a Python wrapper (section 6); cold first step about 9.1 s, warm 0.85 s (sections 9, 10). The result is cache entry 0/0, valid while T == 64.
  2. T = 32: a guard fails, so Dynamo compiles again. The log names the guard: "tensor 'idx' size mismatch at index 1. expected 64, actual 32". The new entry 0/1 compiles T as a symbol, s75, guarded by 2 ≤ T instead of an equality (section 4).
  3. T = 48, then 16: a hit. The entries are checked in order: 0/0 fails, 0/1 passes, and its cached kernels run with no Python per op. The check runs in C++: 45 to 81 µs for the whole model's 549 guards (section 2).
  4. T = 1: outside the symbol's range. Sizes 0 and 1 stay specialised (a 1 broadcasts), so "2 <= idx.size()[1]" fails as well and entry 0/2 is compiled for T == 1 alone.
  5. T = 64 again: entry 0/0 still serves it. Six calls, three compiles: the cache keeps every version and walks them in order.
  6. Ten different strings: the recompile limit. A small function guarded on a string's value compiles eight versions (mode == 'a0' to 'a7'); after recompile_limit (8) the ninth and tenth calls compile nothing and run eagerly, with only a warning (section 4).

Step 1's numbers are the running example's training step, measured here (torch 2.14.1, CPU); steps 2 to 5 replay section 4's recorded run (the forward, eval, exp/dynamic.py) with its logged reasons, and step 6 the recompile-limit run of the same script. The two ways the picture goes wrong are a graph break (section 3, Fig. 2) and a recompile (steps 2 and 4).

torch.compile(model) returns a wrapper and does nothing until the first call. The parent page's Compile lab measured what this does to one training step of the running example (the 3,186,944-parameter character GPT: 4 blocks, d 256, batch 8 x 64 tokens): one graph, 59 operations, 0 breaks, 549 guards; no gain on the laptop's CPU (23.20 ms against 22.75 ms) and 1.18 times on its GPU (MPS). This page goes one level down into each stage, on the same model, so you can predict what compile will do to your code, read what it did, and fix it.

You need fake tensors and functionalization (Tensors, the dispatcher and autograd, section 2.5). New terms, each defined again where it is used:

frame, bytecode
one function call, and the stack-machine instructions CPython runs for it
guard
a check that compiled code is still valid for this call (shape, dtype, object identity, global flags)
graph break
a line Dynamo cannot capture: it runs in Python and the graph is split around it
recompile
a guard failed, so another version of the frame is compiled and cached
symbol (backed, unbacked)
a size compiled as a variable; backed from an input size, unbacked from data
joint graph, partitioner
forward and backward as one graph, and the cut that decides what is saved between them
fusion, wrapper
several ops in one kernel; the generated Python that launches the kernels in order

The question the page keeps returning to: when does compile pay, what does it cost, and how do you see what it did? Six answers measured here, each with its section:

The stages in one table (what each takes and gives, measured, and the log that shows it)
StageTakesGivesOn the running example, measured hereSee it with
DynamoPython bytecode of each called frameFX graph, guards, rewritten bytecodeMLP: 36 bytecode instructions traced, 3 graph ops, 45 guards (section 1)TORCH_LOGS=graph_code,guards,bytecode
AOTAutogradFX graphforward graph + backward graph (functional ATen ops)joint graph 646 ops, cut into 271 forward and 427 backward; keeps 34.81 MB for backward (section 5)TORCH_LOGS=aot_graphs
Inductorthe ATen graphskernels + a Python wrapper that calls themone block's forward: 16 scheduler nodes, fused into 10, written as 4 C++ kernels + 4 matmul calls + 1 attention call (section 6)TORCH_LOGS=output_code,fusion
torch.exporta moduleone whole graph, no breaks allowed94 ops; 326 after run_decompositions(); AOTInductor package 14,358,669 bytes (section 11)ep.graph_module
Where the neighbours are. Compile's place in a bottleneck hunt, and the activation-memory budget on a larger model: Making training fast; custom ops that remove graph breaks: Extending PyTorch; where Inductor's Triton goes next (PTX, SASS): The compiler stack, section 1; CUDA graphs: Streams, CUDA graphs and multi-GPU.

Same instructions: CPython computes as it goes, Dynamo only writes the graph down

Bytecode

Recorded with torch 2.14.1, Python 3.12, CPU (exp/walk.py). By the end CPython has run 9 ATen calls; Dynamo has run none, with both Linear.forward calls inlined (depth 1). Dynamo's copy of MLP.forward has two extra instructions before each call (PUSH_NULL, SWAP) from rewriting the bytecode into a canonical form. Stack entries are Dynamo's own repr, shortened (Lazy(...) = LazyVariableTracker).

1. Dynamo: reading your Python as it runs

A compiler needs the whole computation as a graph, but a model is ordinary Python: loops over layers, attribute lookups, the odd if. Dynamo keeps running Python as Python and captures only what it can prove safe.

Why not the earlier capture tools (PyTorch 2 paper, section 2)

torch.jit.trace ran the model once and recorded only the path taken, silently wrong when control flow changed; torch.jit.script required a restricted Python dialect; torch.fx.symbolic_trace fails on any data-dependent branch. The PyTorch 2 paper (Ansel et al., ASPLOS 2024, section 2) reviews them.

How it works. CPython compiles each function to bytecode, a list of stack-machine instructions (LOAD_FAST x pushes a local, LOAD_ATTR fc replaces the top of the stack with its attribute, CALL 1 calls with one argument), and evaluates one frame (one function call) at a time. PEP 523 lets a C extension replace the frame evaluator; Dynamo installs its own (enable_eval_frame_shim, eval_frame.c L247-L255 at v2.14.1), so it sees every frame first. For a frame compiled before, it runs the guards and, if they pass, jumps to the compiled version. Otherwise it symbolically evaluates the bytecode: the same instructions, but its stack holds VariableTrackers instead of values.

TensorVariableA tensor, as a fake tensor (shape, dtype, device, no data) plus a proxy: every operation on it adds a node to the FX graph.
NNModuleVariableA module such as self.fc. Calling it inlines its forward; its parameters become graph inputs.
LazyVariableTrackerA value not inspected yet; turned into a real tracker (and guarded) only if the code uses it, which keeps the guard list short.
Constant, builtin, Python moduleComputed at trace time: C // n_head is evaluated now and baked into the graph as a number, with a guard on what it came from.

One frame gives three things: an FX graph (tensor operations and their inputs), the guards, and new bytecode for the frame that gathers the inputs, calls the compiled graph and returns its result. The running example's MLP (block 0: self.proj(F.gelu(self.fc(x)))), recorded instruction by instruction from Dynamo itself (its step() wrapped), against the same call run by CPython with every ATen call caught by a dispatch mode. Same input, (8, 64, 256). Predict before you step: how many kernels run while Dynamo traces?

Step through it: Dynamo tracing, then CPython running the same call

  1. Start tracing MLP.forward. Dynamo intercepted the frame through its PEP 523 hook before any instruction ran; its stack starts empty, and self is pushed as a LazyVariableTracker, inspected (and guarded) only if the code uses it.
  2. Look up self.proj, F.gelu, self.fc; push x. Attribute lookups are answered now, at trace time, and each answer becomes a guard (the count grows from 7 to 13); the global F's identity is guarded, so replacing it would invalidate the code. PUSH_NULL and SWAP are bookkeeping Dynamo inserted when it normalised the bytecode for a method call.
  3. Inline Linear.forward for fc. A call into a module is not compiled separately: Dynamo follows it (depth 1), so both frames end up in one graph. self.weight and self.bias are parameters, so they become graph inputs (placeholders).
  4. Call F.linear: a node, no arithmetic. On TensorVariables Dynamo runs the function on fake tensors (shapes only) to learn the output shape and adds the node linear to the FX graph; it then returns to MLP.forward with the result on its stack.
  5. Call F.gelu. One more node, gelu. A real run would launch a kernel here; Dynamo only writes it down.
  6. Inline Linear.forward for proj. The same pattern again: two more placeholders and the node linear_1.
  7. Return: the graph is complete. Dynamo marks the returned TensorVariable as the graph output, compiles the graph (3 calls on 5 inputs, 45 guards) and writes new bytecode for the frame that calls it. Next call: run the guards, then the compiled code.

Attribute lookups such as self.fc never reach the graph: they were answered at trace time, and the answer is protected by a guard.

Predict: inside a compiled function, how many times does self.fc (a Python attribute lookup) run per call after the first?

Cost. Tracing is Python running Python: for the whole running example, Dynamo's share of the first call ("entire_frame_compile" minus the backend) was about 0.25 s of the roughly 9 s cold compile; the rest is AOTAutograd and Inductor (section 10). Afterwards each call pays only the guard check (section 2). Check with TORCH_LOGS=bytecode (original and rewritten bytecode), graph_code (the FX graph with each line's source), trace_bytecode (every instruction with the tracker stack, what the stepper replays), or torch._dynamo.explain(fn)(*args) for a summary of graphs and breaks.

2. Guards: the conditions that keep compiled code valid

Everything Dynamo baked in (shapes, dtypes, which module object, a Python flag, grad mode) must still hold on the next call, or the compiled code computes the wrong thing; checking it in Python each call would cost more than the kernels of a small model. So each fact becomes a guard in a tree keyed by where the value comes from (L['x'] for a local, G['F'] for a global, attributes of those), built in C++ (GuardManager, RootGuardManager, guards.cpp L4242; enable_cpp_guard_manager is on by default): a check walks each source once and runs its leaf guards. The MLP's tree as TORCH_LOGS=guards printed it (paths shortened), counted by kind:

Leaf checks in the printed tree, by kind (53 leaf checks; Dynamo's own guard set for this frame held 45 entries, the number used in section 1).

The printed guard tree (TORCH_LOGS=guards, first lines)

Four kinds do most of the work: TENSOR_MATCH (dispatch keys, dtype, device, requires_grad, sizes and strides of a tensor input), ID_MATCH (this exact object: the F module, the gelu builtin), TYPE_MATCH, and GLOBAL_STATE (grad mode, autocast, default dtype, thread count, deterministic flag, in one check). DIMENSION_DYNAMIC_MARKING_GUARD makes sure a tensor that later gets mark_dynamic is not served by code compiled for a static shape.

Cost. 51.71 microseconds for the MLP's tree in the recorded run (one unlocked measurement that varied by about two times between runs: an order of magnitude); the whole model's 549 guards measured 45 to 81 microseconds in the Compile lab. Nothing against a 23 ms CPU step; a real overhead against a 1 ms GPU step, where kernels launch asynchronously and the CPU's time is the critical path. When a guard fails, Dynamo compiles again and keeps both versions in a per-frame cache, checked in order on each call: a recompile (section 4; Fig. 1, steps 2 to 5, walks the cache).

Guard APIs: skipping guards, and failing on recompiles (torch 2.14.1)

Three APIs trade safety for speed: torch.compiler.skip_guard_on_inbuilt_nn_modules_unsafe, skip_guard_on_all_nn_modules_unsafe and skip_guard_on_globals_unsafe (all present in torch.compiler at 2.14.1, read from the wheel); their names say what they risk. torch.compiler.set_stance("fail_on_recompile") turns every recompile into an error, useful in a test that pins the number of compiles; "eager_on_recompile" runs eagerly instead.

3. Graph breaks: each kind, and how to remove it

When Dynamo meets something it cannot put in a graph, it does not fail by default: it compiles the graph so far, emits bytecode that runs the unsupported instruction in plain Python, and starts a new graph after it (a resume function; the rewritten bytecode, step by step, is in The compiler stack, section 8). That split is a graph break. It costs twice: no fusion across it, and Python plus a guard check between the pieces on every call. The Compile lab measured a print in each block at +7 to 9% step time on the CPU; on a GPU each piece also launches separately and a CUDA graph cannot span the break.

Where the break sits matters more than how many. GPT.forward runs the blocks in a for blk in self.blocks loop, and Dynamo cannot resume tracing in the middle of a loop, so a break anywhere inside a block costs the whole caller. Fig. 2 plays it with the running example's recorded numbers; the sibling Extending PyTorch (its Fig. 2) draws the same kind of split operation by operation.

Fig. 2: a print in Block.forward, frame by frame

  1. No break: one graph. Dynamo traces GPT.forward and inlines every Block.forward: 1 graph of 101 operations for the forward, 0 breaks, one piece call per forward.
  2. A print in Block.forward. Dynamo reaches the print inside for blk in self.blocks; it cannot resume in the middle of a loop, so it gives up on the whole GPT.forward frame ("Failed to handle graph break gracefully. Skipping the function and falling back to eager", its own log, read with tlparse in section 12). The embeddings, final LayerNorm, head and loss now run as plain Python.
  3. Block.forward becomes its own frame, in two pieces. Graph 1 holds the attention half (18 ops); the print runs in Python; a resume function compiles the rest (graph 2, 5 ops). Dynamo's reason: "Failed to trace builtin operator".
  4. Every block reuses the two graphs. The parameters are graph inputs, so blocks 1 to 3 pass the same guards: 2 graphs and 1 break in all, and only the two halves of each block are compiled: 8 piece calls per forward instead of 1, with Python between them and no fusion across the print.
  5. Fixed: one graph again. With reorderable_logging_functions = {print} Dynamo moves the print to after the graph: 1 graph of 101 operations, the same output (maximum difference 0.0, measured).

Each kind of break, and its fix

Nine lines placed in Block.forward, one at a time, each with its fix; the widget beside this text draws one forward for any of them. Every one leaves GPT.forward uncompiled as in Fig. 2; they differ in how many pieces each block splits into and in whether a flag, a rewrite or a custom op removes the break.

Can the caller be kept compiled? torch._dynamo.config.nested_graph_breaks (off by default, config.py L585-L587 at v2.14.1: "Resume tracing in nested frames if a nested graph break occurs. Old behavior is to bubble up the graph break to the top level frame") was run on four small programs with one torch._dynamo.graph_break() in the inner function:

It works for a plain call and for unrolled module calls, and changes nothing inside a for loop, which is how almost every transformer calls its blocks; on the running example it did not help (2 graphs either way, measured). The rule stays: remove the break.

Predict: with torch._dynamo.config.capture_scalar_outputs = True, the block that does s = x.abs().max().item() and then 1.0 if s < 1e9 else 0.0 compiles to how many graphs?

Three lessons from the twelve rows. (1) Some flags remove a break by changing what a graph may contain: capture_dynamic_output_shape_ops lets boolean-mask indexing in (the selected size becomes a symbol); reorderable_logging_functions = {print} moves the print to after the graph runs (so it prints after the whole region, not at its line). (2) fullgraph=True is not just "no breaks": for the boolean mask it compiled without error, because when one graph is required Dynamo captures the dynamic size instead of breaking, while for .item() followed by an if it raised. (3) A @torch.compiler.disable helper is a deliberate break; call it outside the compiled region, or register the code as a custom op (Extending PyTorch owns that; its root lesson: a .tolist() body gives 3 graphs and 2 breaks, the same body as a custom op 1 and 0).

All twelve rows in one table (Dynamo's reason, graphs and breaks before and after)

Check. torch._dynamo.explain(model)(x, y) returns graph count, break count and each reason with its user stack; TORCH_LOGS=graph_breaks prints them as they happen, each with a link into the graph-break registry (for example gb7000, the loop case); fullgraph=True turns the first one into an exception, which is what you want in a training loop you control.

One forward pass with a break line in each block: green runs compiled, dashed runs as Python

Pick a line, then broken or fixed; the lane shows the whole forward.

Broken
Fixed

Dynamo's reason:
With fullgraph=True:

Nine lines placed in Block.forward between attention and the MLP, twelve fixes (three lines have two). Counts from torch._dynamo.explain; every fix gives the same output as the unmodified model (maximum difference 0.0, measured; exp/fixer.py). The lane is drawn from the counting backend's record: which compiled pieces exist (ops in each) and how many piece calls one forward makes; the order of the eager segments is the model's (embedding, 4 blocks, final LayerNorm, head and loss).

4. Recompiles and dynamic shapes

Sizes are guarded like everything else: a new sequence length, a short last batch or a learning rate passed as a Python number fails a guard and costs seconds of compiling. Compiling for "any size" instead gives kernels that cannot specialise (no fully unrolled loops, extra index arithmetic) and adds symbolic reasoning to every compile.

How it works. The first call compiles every size static. When a size guard fails, automatic dynamic shapes (automatic_dynamic_shapes, on by default, config.py L188) recompiles with the changed dimension replaced by a symbol (s75 below) read at run time, guarded by inequalities instead of equalities. Two exceptions are built in: sizes 0 and 1 stay specialised, because a dimension of 1 broadcasts and code valid for "any n" may be wrong for 1 (0/1 specialisation); and parameters' shapes are always static (force_parameter_static_shapes). Predict before you look: six calls with T = 64, 32, 48, 16, 1, 64; how many compiles by default?

Default: T = 32 fails the exact-size guard ("tensor 'idx' size mismatch at index 1. expected 64, actual 32") and recompiles with T symbolic, range [2, inf]; 48 and 16 reuse it; T = 1 falls outside "2 <= idx.size()[1]" (0/1 specialisation) and compiles a third version (Fig. 1 replays this row, guard by guard). dynamic=False: every new length compiles, 5 times. mark_dynamic(idx, 1, min=2, max=64) before each call: one compile covers 64, 32, 48 and 16, and T = 1 is now an error (ConstraintViolationError), not a recompile: a bound you state is checked.

The two odd strategies: dynamic=True compiled 4 times, mark_unbacked broke tracing (measured; one cause unconfirmed)

dynamic=True: symbolic from the first call, yet 4 compiles here; the recompile log blamed a guard that itself raised ("'NoneType' object has no attribute 'size'": some guard read a size from an attribute that is None) and then the 0/1 guard. Recorded; which guard raised was not traced further (cause unconfirmed), and it looks like a Dynamo bug rather than anything the model does. mark_unbacked (no 0/1 specialisation, see unbacked symbols below) broke tracing at scaled_dot_product_attention inside the block loop, so GPT.forward was skipped and each block frame compiled on its own.

The same six calls under five strategies: default compiles 3 times, dynamic=False 5

The running example, forward, eval, CPU, torch 2.14.1 (exp/dynamic.py). A filled square is a call that compiled (two for dynamic=True's first call), an empty one reused a version, a red one raised. Pick a strategy for its recompile reasons as logged:

Python numbers behave like sizes: the Compile lab showed a float learning rate compiled at calls 1 and 2 and symbolic afterwards (specialize_float = False, config.py L162). Values that are not numbers (a string flag, a dtype, a module attribute) are guarded by value with no symbolic fallback. A small function called with ten different strings:

After recompile_limit (8, config.py L121) versions of one frame, Dynamo stops compiling it and runs it eagerly, with only this warning (convert_frame.py L2000-L2019), recorded:


The ninth and tenth calls compiled nothing and ran eagerly, with no error unless fail_on_recompile_limit_hit is set: a silent slowdown is the usual symptom. torch.compile(..., recompile_limit=n) sets it per function at 2.14.1 (a new keyword in its signature), and accumulated_recompile_limit (256) caps all frames together.

Unbacked symbols: sizes that come from data

A symbol from an input size is backed: at compile time there is an example value (a hint) to answer "is s75 > 1?". A symbol from .item() or nonzero() is unbacked: its value exists only when the graph runs. Dynamo breaks on both by default; with capture_scalar_outputs or capture_dynamic_output_shape_ops it keeps them in the graph as u0, and any branch on them must be answered without a value. torch._check(n >= 0); torch._check(n <= idx.shape[1]) states facts the compiler can reuse, the fix when a branch cannot be decided ("Could not guard on data-dependent expression", the error in section 3); torch.cond is the fix when you really need both branches.

The captured graphs with unbacked sizes, and the asserts Dynamo added (recorded)

On two small functions, the captured graphs (abridged):

At 2.14.1 slicing by an unbacked size needed no help: Dynamo added the runtime asserts u1 >= 0 and u1 <= 64 itself. torch._check moves the same asserts to your line.

Check. TORCH_LOGS=recompiles names the failing guard for every recompile; TORCH_LOGS=dynamic shows each symbol as it is created ("create_symbol s75 = 32 for L['idx'].size()[1] [2, int_oo]", recorded) and every guard on it; torch.compiler.set_stance("fail_on_recompile") makes a test fail on any recompile.

Profile-guided dynamism across processes needs a job id (measured)

automatic_dynamic_local_pgo is on at 2.14.1: Dynamo can remember, in the cache directory, which dimensions turned out dynamic, so the next process compiles them dynamic from the start. But "PGO does nothing (even if explicitly enabled) unless a valid job_id is available" (torch.compiler.config.job_id, torch/compiler/config.py L48-L70 at v2.14.1). Two fresh processes calling T = 64 then 32, sharing one cache directory:

5. AOTAutograd: the backward graph, and what crosses to it

Dynamo captured only the forward. In eager mode the backward is decided op by op as the forward runs, each op saving what its own derivative needs; a compiler wants the backward as a graph ahead of time, and wants to choose what is saved.

How it works. AOTAutograd runs the captured forward once more, on fake tensors, through the real autograd machinery, and records forward and backward as one joint graph whose inputs are the forward inputs (primals_*) and the incoming gradients (tangents_*). On the way, functionalization replaces in-place and aliasing ops by pure ones (the block's joint graph has no in-place op, measured) and decomposition lowers composite ops to a smaller ATen set (F.linear becomes permute + addmm, GELU becomes erf, mul, add). Then a partitioner cuts the joint graph in two: every value that crosses the cut is saved by the forward for the backward; everything else the backward needs, it recomputes.

default_partitionSave whatever the backward needs that the forward produced; recompute nothing. Close to eager. (partitioners.py L1595)
min_cut_rematerialization_partitionInductor's default. A max-flow min-cut where cutting an edge means saving that tensor (cost: its bytes) and cheap ops may be recomputed instead; matmuls, reductions and long chains are banned from recompute (ban_recompute_*, functorch config.py L159-L174; partitioners.py L4109).
activation_memory_budgetBelow 1.0 (the default, L202) expensive ops may be recomputed too, chosen by a knapsack (solver "dp", L215) over runtime estimated from FLOPs (L209), until the saved bytes fit the fraction asked for.

One block of the running example (training, CPU, input (8, 64, 256)), cut every way on the real Inductor path (its joint-graph passes, then the partitioner, wrapped to record what it received and returned). Fig. 3 draws all 144 operations of its joint graph and steps through the cuts:

Fig. 3: the block's 144-op joint graph, which values each cut saves, and which it recomputes

  1. The joint graph. 56 forward operations in front, 88 backward behind, as AOTAutograd handed them to the partitioner after Inductor's joint-graph passes. Everything the backward reads from the forward must either cross the cut or be computed again.
  2. default_partition: save what the backward needs. 15 activations cross the wall (orange, height and dots by bytes): 8,404,992 bytes, with 88 backward ops and nothing recomputed. The two tallest, 2,097,152 bytes each, belong to the MLP, whose hidden layer is four times wider than the block.
  3. Min-cut, budget 1.0 (Inductor's default). 17 cheap operations turn green: recomputed in backward instead of saved, among them the GELU intermediates and the reshaped attention output (the input of proj). 14 activations cross, 7,880,704 bytes; 98 backward ops.
  4. Budget 0.5. Allowed half the activation bytes: some matrix multiplies and the attention are recomputed too. 4 activations cross (3,670,016 bytes); 39 operations recomputed, 121 backward ops.
  5. Budget 0.2. A fifth of the bytes: 3 activations (1,572,864 bytes); most of the block is recomputed (40 operations), 122 backward ops.
  6. Budget 0.0. No activation crosses, only inputs are saved: the backward reruns the matrix multiplies and the attention, like full activation checkpointing. 52 operations recomputed, 134 backward ops instead of 88.
What this cut saves, value by value (follows the figure's step: default_partition)

Saved values that are graph inputs (the block input, parameters) are kept by the caller anyway and are listed but not counted. default_partition saves transposed views of the weights where min-cut saves the weights themselves; views share the weights' memory, so both cost nothing extra. Recorded with torch 2.14.1 (exp/aot.py).

default_partition keeps 8,404,992 bytes, eager's number to within 4 bytes (8,404,996 live after one eager block forward, measured on the sibling page): the accounting is right. Min-cut at budget 1.0 keeps 7,880,704 bytes: the 524,288-byte .contiguous() copy of the attention output (the input of proj) can be rebuilt in backward from the attention output it saves anyway, and saving the parameters themselves is free where default saved transposed views of them. So 6% less memory for 10 more backward ops.

Predict: the running example's training step on the CPU with activation_memory_budget = 0.0 (save nothing, recompute everything) against the default budget: how much slower?

When it matters: when activations, not parameters, set the batch you can fit (long sequences, many layers). It is the compiler's activation checkpointing, and composes with it: a checkpointed region is recomputed whatever the partitioner thinks. On this model the default min-cut barely moves memory; the budget is the lever. Check: TORCH_LOGS=aot_graphs prints the forward graph (its return statement lists what is saved) and the backward graph; TORCH_LOGS=aot_joint_graph the joint graph.

The whole model under each cut, and a larger model (measured)

The whole model behaves the same way: 36,862,468 bytes saved under default_partition (plus 12.63 MB of transposed parameter views, which cost nothing), 34,814,468 at budget 1.0 (the same figure the Compile lab measured), 17,301,504 at 0.5, 6,903,808 at 0.2 and 0 at 0.0, with 427, 578, 593 and 635 backward ops. On a larger configuration Making training fast (section 9) measured the same knob at 546.8, 273.0 and 0 MB for budgets 1.0, 0.5 and 0.0.

Memory is bought with recompute: from 8.40 MB and 88 backward ops to 0 MB and 134

Lowering already did most of the fusing: 16 nodes, 6 fusions, 4 kernels

reductionpointwiseextern (library call)

6. Inductor: from ATen graph to fused kernels

The graphs AOTAutograd hands over are still one ATen op per line; run op by op, each element-wise op would read its input from memory and write its output back (the Compile lab's fused GELU moved 4 MiB instead of 36 MiB). Inductor works in three passes:

Lowering
ATen to loops

Each op becomes a loop body written as a small Python function over indices (Inductor's "define-by-run" IR, PyTorch 2 paper, section 4). Element-wise ops are inlined into their consumer here, so LayerNorm's subtract, multiply, rsqrt never become separate nodes. Matmuls and attention become extern nodes: library calls.

Scheduling
fuse nodes

The scheduler fuses pairs that can share one loop: a producer with its consumer (vertical), or two nodes reading the same data (horizontal). It refuses when an unfused node would have to run between them, or sizes do not match.

Codegen
kernels + wrapper

One kernel per fused group: C++ with OpenMP and vector intrinsics on a CPU, Triton on a GPU, Metal on MPS; plus a Python wrapper, call(), that allocates buffers (reusing dead ones) and launches kernels and library calls in order.

One block's forward on the CPU (inference, (8, 64, 256)), every scheduler decision recorded with TORCH_LOGS=fusion. Predict before you step: how many kernels does the scheduler end with?

Step through the scheduler

  1. Lowering hands the scheduler 16 nodes. They already contain whole chains: op3 is LayerNorm's normalisation with sub, mul, rsqrt, add folded in; op14 is all of GELU. Extern nodes (orange) are library calls: addmm and attention.
  2. The first LayerNorm becomes one node. Three fusions join its two statistics passes and its normalisation (op0 with op1, op2 with op3, then the two pairs): they read the same activation row by row, so one loop does all of it and the intermediates never go to memory.
  3. The second LayerNorm, with the residual add. The same three fusions on op9 to op12. The residual add after attention travels with it: the kernel reads the sum while computing the statistics instead of writing it out first. (The log interleaves the six fusions of round 1; they are grouped here by LayerNorm.)
  4. Round 2: nothing more fuses. The scheduler rejected 27 other pairs, every one for the same reason ("intermediate nodes between node1 & node2"): a LayerNorm and the next one cannot share a loop, because the attention and matmuls (extern) must run between them.
  5. Codegen: 10 nodes, 4 C++ kernels. Each non-extern group is one kernel (cpp_fused_native_layer_norm_0, cpp_fused_add_native_layer_norm_view_1, cpp_fused_gelu_view_2, cpp_fused_add_view_3); the externs become 4 addmm calls into the BLAS library and 1 call to the CPU flash-attention kernel (one extern node only unpacks the attention result). The wrapper reuses dead buffers 8 times (lines ending # reuse).

The same fused GELU kernel as Inductor wrote it for the CPU, and as it writes it for a GPU (Triton 3.8.0 in Docker with a stand-in driver that only answers "which GPU target?"; generated, never run; where that Triton goes next is section 1 of The compiler stack):


Both do the same arithmetic (0.5 x (1 + erf(x / sqrt 2))) in one pass over 524,288 floats and differ in how the loop is cut: the C++ splits it across 4 OpenMP threads and steps 4 floats at a time with NEON vectors (Vectorized<float>); the Triton kernel handles one block of XBLOCK elements per program instance and leaves the block size to an autotuner. Triton came out of the same fusion decisions: the same 4 groups (two "per" persistent-reduction kernels for the LayerNorms, two "poi" pointwise kernels).

Inductor knobs on this block, counted (measured; most change nothing on a CPU)

Counting launches in the generated code (training, forward and backward): default 4 + 9 generated kernels, 4 + 8 library matmuls; aggressive_fusion=True, epilogue_fusion=False and pattern_matcher=False changed nothing; cpp_wrapper=True writes the wrapper in C++ instead of Python (611 and 904 lines instead of 491 and 728), removing Python from the per-call path; freezing=True (inference) gave the same 9 launches. On a GPU the large knobs are max_autotune (try Triton templates against cuBLAS for each matmul), coordinate_descent_tuning and CUDA graphs, which is what the modes bundle (section 7).

Check. TORCH_LOGS=output_code prints every kernel and the wrapper; fusion or schedule the decisions; ir_pre_fusion,ir_post_fusion the scheduler's nodes. Kernel names are unique by default at 2.14.1 (TORCHINDUCTOR_UNIQUE_KERNEL_NAMES defaults to 1, inductor config.py L2102-L2104), so a profiler trace maps each kernel back to its source; the old advice to set it is no longer needed.

7. Modes: bundles of Inductor options

A mode is only a preset of Inductor config; torch._inductor.list_mode_options() prints it. At 2.14.1, recorded:

"reduce-overhead" turns on CUDA graphs (record a whole sequence of kernel launches once, replay it with one call: for small batches, at the cost of memory, and only for CUDA graphs that do not mutate inputs); "max-autotune" adds Triton or template matmuls and also enables CUDA graphs on a GPU. On the laptop's CPU neither did anything: the Compile lab measured mode="max-autotune" at 23.94 ms against 23.20 default (the BLAS call won every matmul) and "reduce-overhead" at 23.85 ms. CUDA graphs need an NVIDIA GPU, static shapes and static addresses, and are owned by Streams, CUDA graphs and multi-GPU (its section 4: CUDAGraph Trees and Inductor's graph partitions, which split a graph around the parts that cannot be captured; graph_partition is on by default at 2.14.1, read from the config). Not run here: no NVIDIA GPU.

The docstring's words, and the undocumented "lite" preset (torch 2.14.1 source)

From the docstring at 2.14.1 (torch/__init__.py L3103-L3119): "reduce-overhead" "reduces the overhead of python with CUDA graphs, useful for small batches", at the cost of memory, and "today, we only reduce overhead for CUDA only graphs which do not mutate inputs"; "max-autotune" "leverages Triton or template based matrix multiplications on supported devices" and "enables CUDA graphs by default on GPU". A fifth preset, "lite", appears in the table but not in the docstring: it turns most graph passes and buffer reuse off and falls back to eager by default unless a region is marked for compilation (torch/_inductor/__init__.py L335-L351).

8. Compiled autograd: the backward captured when it runs

AOTAutograd builds the backward ahead of time, but only for the compiled region. What the autograd engine does around it stays eager: gradient hooks, accumulation into .grad, and the communication that DDP and FSDP hook into the backward. A hook on a parameter cannot be in the ahead-of-time graph: it is attached to a tensor, not to code Dynamo traced. With torch._dynamo.config.compiled_autograd = True (config.py L770, off by default), when loss.backward() runs inside a compiled function the engine's whole graph is traced at that moment, hooks and accumulation included, into one FX graph that Dynamo and Inductor compile. The price: that graph is traced on every backward and guarded on the autograd graph's structure. The running example's training step, CPU, recorded:

Without it, a hook on blocks[0].mlp.fc.weight (lambda g: g * 0.5) became a separate one-op graph compiled when the engine called it. With it, the backward is one graph of 730 ops including 52 AccumulateGrad nodes (one per parameter), and the hook is the 731st op inside it. Gradients match eager to 3.6e-07 in every case. Speed on the CPU: 23.36 ms without, 23.57 ms with (medians of 5 x 20 steps, bench lock): no gain, because the backward kernels were already compiled and there is no communication to overlap. When it matters: when the backward holds things worth fusing or overlapping that AOTAutograd cannot see, above all distributed communication.

Correction to the old page
It said torchtitan uses compiled autograd for compiled FSDP2. The torchtitan 0.3.0 source has no reference to compiled_autograd; it compiles each transformer block with fullgraph=True (torchtitan/distributed/compile.py L70) and sets capture_scalar_outputs = True for MoE routing (L56).
DDP under compile: ddp_optimizer splits the graph at bucket boundaries (measured on 2 CPU processes)

Dynamo's DDP support documents the trade (optimize_ddp, config.py L406-L432): the default "ddp_optimizer" splits the forward graph at DDP's bucket boundaries so each bucket's all-reduce can start while the rest of the backward runs, and "python_reducer" (experimental) instead "requires the usage of compiled_autograd" to trace the communication without graph breaks. The split is real; on 2 CPU processes (gloo), the compiled DDP model became:

Distributed internals are owned by Distributed PyTorch.

9. Regional compilation: compile the block, not the model

Compile time grows with graph size, and an LLM is one block repeated 32 to 128 times; compiling the whole model traces and optimises every copy. Compile the repeated module instead: for b in model.blocks: b.compile() (nn.Module.compile compiles in place). Dynamo compiles Block.forward once; because parameters are graph inputs (inlined built-in modules, always on at 2.14.1), every other block instance passes the same guards and reuses the code. torchtitan does exactly this with fullgraph=True. A newer variant keeps one compile of the whole model but marks the block as a region compiled once and called many times: torch.compiler.nested_compile_region (in the 2.14.1 API). Cold first training step, fresh process, empty cache:

The whole model went from 9.19 s to 10.85 s when the blocks doubled from 4 to 8; per block stayed flat (5.72 s, 5.66 s) because the extra blocks cost nothing to compile; nested_compile_region sat between (8.04 s, 8.42 s), since the rest of the model is still traced around the region. Steady-state step time did not suffer (whole 24.11 ms, regional 23.80, nested 23.91, medians of 5 x 20 steps): the fusion lost across block boundaries (a residual add that could have joined the next LayerNorm) is too small to see on a CPU. Always worth trying first on a deep model; the gap grows with depth (1.9 times at 8 blocks here; production models have tens to hundreds). Check: the cache counter fxgraph_cache_miss was 2 in every variant: one forward and one backward graph compiled, whether that graph is the whole model or one block.

Per block stays flat as the model doubles; whole-model compile grows

Dynamo tracingforward: AOTAutograd + Inductorbackward compile (at first backward)running the step, the rest

10. Caches: paying the compile once

A cold compile of this tiny model's step takes about 9 seconds; real models take minutes, and a job on 1,000 GPUs restarted after a failure pays it on every rank. Several caches on disk, all under TORCHINDUCTOR_CACHE_DIR (a per-user temporary directory by default), each keyed by a hash of its input graph, the config and the versions: the FX graph cache (Inductor's output for a post-AOTAutograd graph; fx_graph_cache, on, inductor config.py L109), the AOTAutograd cache (forward and backward graphs for a Dynamo graph, so AOTAutograd is skipped too; enable_autograd_cache, on, functorch config.py L71), the compiled kernels (C++ shared objects, Triton binaries) and autotuning results. Dynamo still traces in every new process: guards are not cached. Mega-cache packs the entries a process used into one blob: torch.compiler.save_cache_artifacts() returns bytes, load_cache_artifacts(bytes) installs them in another process's cache directory. Predict: a mega-cache loaded into an empty directory, how close to warm?

Warm, the first step took 0.85 s against 9.08 s cold (medians): both Inductor graphs and the AOTAutograd entry hit, nothing was compiled, and what is left is Dynamo tracing again plus loading cached code, the floor of a warm start. The mega-cache gave 5.06 s: the same hits (2 FX graph, 1 AOTAutograd), but 4.0 s still went to async_compile.wait, compiling the C++ kernels again. The blob (1,265,370 bytes) carries generated source, not this machine's compiled .so files, so on a CPU it saves the Python half of the compile and not the C++ half. On a GPU the large win is the Triton kernels and autotuning results it carries (not measured here).

Warm skips the compile; a mega-cache on a CPU still rebuilds the C++

Every timed run, with its phases and cache hits (3 runs each, bench lock)

Phases are Dynamo's own timers (calculate_time_spent()): Dynamo = entire_frame_compile minus backend_compile; forward = backend_compile; backward = entire_backward_compile; the rest = first-step time minus both. Waiting for the C++ compiler (async_compile.wait) sits inside the forward and backward phases and is listed per run. CPU, 4 threads, torch 2.14.1; the figures above use the run closest to the median of three.

A cache can serve a wrong program
The sibling Extending PyTorch found that the AOTAutograd cache key does not include whether a custom op's autograd formula is registered: a process that registered it late produced a backward that silently dropped gradients, and a later, correct process reading the same cache reused that broken backward. TORCHINDUCTOR_AUTOGRAD_CACHE=0 avoided it there. When you change custom-op registrations or other code the key cannot see, use a fresh cache directory.

Check. The counters torch._dynamo.utils.counters["inductor"]["fxgraph_cache_hit"] and counters["aot_autograd"]["autograd_cache_hit"] (used for the figure); TORCH_LOGS=cache; torch._dynamo.utils.calculate_time_spent() for the phase split. To be sure you measure a cold compile, point TORCHINDUCTOR_CACHE_DIR at an empty directory, or set torch.compiler.config.force_disable_caches.

11. torch.export and AOTInductor: one graph to ship

torch.compile is a just-in-time compiler inside a Python process: it needs your code, falls back to Python at breaks and recompiles when guards fail. To deploy where there is no Python, or hand a graph to another tool, the whole program must be captured once, ahead of time, with its assumptions written down. torch.export.export(model, args, dynamic_shapes=...) captures one graph with no breaks allowed and returns an ExportedProgram: the graph (ATen ops), a graph signature saying which inputs are parameters, buffers or user inputs, the state_dict, and range constraints on every symbolic size. Two tracers: non-strict (the default at 2.14.1, strict=False in its signature) runs your Python normally with fake tensors and records the ATen calls; strict traces through Dynamo, which can reject Python it cannot prove safe. On the running example (logits only, eval) both gave the same 94-op graph, measured; its signature lists 53 parameter inputs (the tied embedding twice, under its two names) and 1 user input; ep.run_decompositions() lowers it to the core ATen set, 326 ops. What export did with each specification, recorded:

Two lessons. A dynamic dimension you declare is checked: the reshape to 8 rows made export fail with "You marked batch as dynamic but your code specialized it to be a constant (8)" and a suggested fix. A range is not checked against data: T up to 128 exported fine although the position table has 64 rows, so T > 64 would index past it at run time; with the correct range a T = 100 input was rejected on entry ("Guard failed: idx.size()[1] <= 64", recorded). torch._inductor.aoti_compile_and_package(ep) (AOTInductor) compiles the program ahead of time into a shared library in a 14,358,669-byte package that aoti_load_package runs from Python, or a C++ runner without Python; outputs matched eager within 1.25e-06 at (8, 64).

Dim.AUTO, control flow and draft_export; saving a .pt2; what the package holds (recorded)

Dim.AUTO found both dimensions dynamic but from 2, not 1 (0/1 specialisation again). Data-dependent Python control flow cannot be exported in either mode; torch.cond can. torch.export.draft_export exports it anyway and reports the problem; here it picked the branch the example took (cos) and inserted a runtime assert, with the advice to add torch._check.

torch.export.save wrote a 12,986,850-byte .pt2 archive (52 weight files, since tied weights are stored once, plus the graph as JSON); loading it gave identical outputs. In the AOTInductor package, the 14,163,036-byte wrapper.so holds the weights.

Measured here: AOTInductor and a non-contiguous input
A slice x[:3, :20] of the batch (strides (64, 1), not contiguous) passed to the AOTInductor package returned logits with a maximum error of 1.81 against eager, with no error or warning; the same input after .contiguous() matched within 9.5e-07, and the exported program's own ep.module() handled the slice exactly (0.0). The compiled library assumed the strides it was compiled for. Call .contiguous() on inputs to an AOTInductor model.

Where it leads. ExecuTorch (on-device) and the ONNX exporter (dynamo-based by default since 2.9) start from torch.export; what a model file holds in each format is section 3 of Local and on-device inference.

12. Debugging: a workflow and its tools

The symptom is one of four: slow to compile, not faster, different numbers, or a crash. The workflow, each step with the tool used on this page:

  1. Count graphs and breaks first. torch._dynamo.explain(model)(x, y) (sections 3 and 4). Then TORCH_LOGS="graph_breaks,recompiles" on a real run.
  2. Bisect the stack. backend="eager" runs Dynamo only, "aot_eager" adds AOTAutograd, the default adds Inductor. Whichever first changes the numbers or crashes is the culprit.
  3. Read one compile end to end. Set TORCH_TRACE=<dir> and run tlparse on the log: one HTML report with every frame compiled, every graph (Dynamo, joint, forward, backward, post-grad), the generated code, guards, breaks and recompile reasons per compile id.
  4. Shrink a crash. torch._dynamo.config.repro_after = "aot" (or "dynamo") makes a failing compile write a launcher script; running it minifies the graph.
  5. Find where compile time goes. torch._dynamo.utils.calculate_time_spent() (section 10), or the compilation_metrics pages tlparse writes.
tlparse on a real run: the compile ids of a model with a print in each block (tlparse 0.4.3, recorded)

The running example with a print in Block.forward, run for two steps with batch 8 then 4 (one recompile), traced and parsed with tlparse 0.4.3 (installed here). The compile ids it lists, [frame/attempt]:

Frame 0 is GPT.forward: its only artifact is the break ("Failed to handle graph break gracefully. Skipping the function and falling back to eager"), confirming section 3. Frame 1 is Block.forward before the print, frame 2 the resume function after it ("torch_dynamo_resume_in_blk_print_at_10"); each compiled twice, the second time because "tensor 'x' size mismatch at index 0. expected 8, actual 4". Each compiled frame lists about 30 artifacts, from the Dynamo graph to the cache misses.

The minifier on purpose: a crash shrunk to the failing op (recorded)

Inductor has a test-only switch that makes every relu fail to compile (torch._inductor.config.cpp.inject_relu_bug_TESTING_ONLY = "compile_error"). With repro_after = "aot", a five-line function (matmul, scale, add, relu, matmul, LayerNorm, sum) crashed with a C++ compile error and left a launcher script; running it, recorded:


That is the deliverable you attach to a bug report: a self-contained script whose graph is just the failing op. The minifier's strategies (dead-code elimination, removing inputs and outputs, truncating the graph, delta debugging) ran 25 times; on a large model this takes hours rather than the 65 seconds here, so run it on a small reproduction when you can.

13. What carries over to NVIDIA GPUs, and what does not

Measured hereOn an NVIDIA GPU
Bytecode walk, VariableTrackers, guards, guard treeIdentical: Dynamo is device-independent; only TENSOR_MATCH's device and dispatch keys change.
Graph breaks, nested breaks, recompiles, dynamic shapes, unbacked symbols, recompile limitIdentical behaviour; the cost of each break is usually larger (more launches, CUDA graphs cannot span it).
Partitioner decisions and saved bytesSame algorithm; Inductor's GPU path can also recompute through fusible chains, and the budget's runtime estimate uses FLOPs either way. The time a recompute costs differs.
Fusion groups, 4 kernels per block forwardThe same groups (the Triton code above came from the same decisions); matmuls go to cuBLAS or, with max_autotune, Triton templates; attention to a flash or cuDNN kernel.
Step time: no gain on CPU, 1.18x on MPS (Compile lab)Does not transfer. Vendor figure: 43% faster training on average on an A100 over 163 models (PyTorch team, 2023, PyTorch 2.x).
Compile times (9.2 s cold, 0.85 s warm, 5.7 s regional)The shape transfers (regional flat in depth, warm far below cold); absolute values do not. On GPU the mega-cache also carries Triton binaries and autotuning (not measured here).
reduce-overhead, max-autotune, CUDA graphsNot run here: CUDA only. See Streams, CUDA graphs and multi-GPU.

Depth: common mistakes and interview rehearsal

Common mistakes, each measured on this page (nine)

Logging inside the model with print or .item(). Each is a graph break; inside the block loop it costs the whole forward (section 3). Log outside the compiled function, or keep values as tensors and read them every N steps.

Calling mark_dynamic on one tensor of several that share a dimension. The targets carry the same length as the inputs and are guarded too (Compile lab); mark every tensor with the dimension, or give the bound with min and max so violations are errors you see.

Assuming nested_graph_breaks keeps a model compiled. It did nothing for a break inside a for loop over blocks, measured (section 3).

Passing a different Python string, dtype or config value each call. Guarded by value with no symbolic fallback: after 8 versions, eager mode with only a warning (section 4).

Timing the first call. It includes 9 seconds of compiling here; warm up, then time, and synchronise on a GPU (Making training fast section 1).

Compiling the whole model when compile time hurts. Compile the block (section 9): 5.7 s instead of 9.2 s here, and it does not grow with depth.

Measuring a "cold" compile with a warm cache. The caches are on by default and survive processes: 0.85 s looks like a fast compiler. Use an empty TORCHINDUCTOR_CACHE_DIR.

Feeding a sliced tensor to an AOTInductor package. Wrong answers with no warning, measured (section 11). Make inputs contiguous.

Reading activation_memory_budget from torch._dynamo.config. It lives in torch._functorch.config at 2.14.1 (the sibling page found the blog's spelling does not exist).

Interview rehearsal, with short answers (ten)

How does Dynamo capture a graph without running the model on real data? It installs a PEP 523 frame evaluator and symbolically executes each frame's bytecode with VariableTrackers; tensors are fake tensors carrying shapes, so ops add FX nodes and Python values are computed at trace time and protected by guards.

What is a guard, and what happens when one fails? A condition the compiled code assumed (shape, dtype, object identity, global state), checked in C++ before each call. On failure Dynamo recompiles and caches another version, up to recompile_limit (8), then runs eagerly.

Why might one graph break cost the whole model? A break inside a loop cannot be resumed, so Dynamo skips the enclosing frame: everything outside the blocks runs eagerly and the blocks compile in pieces.

Backed versus unbacked symbolic sizes? Backed come from input sizes and have an example value to answer branches; unbacked come from data (.item(), nonzero) and do not, so branches on them need torch._check or torch.cond.

What does the min-cut partitioner optimise? Which joint-graph values the forward saves for backward: it minimises saved bytes, recomputing cheap ops; activation_memory_budget lets it recompute expensive ones too.

Where does Inductor fuse? Mostly at lowering (pointwise ops are inlined into consumers), then in the scheduler (vertical and horizontal fusion of loops); matmuls and attention stay library calls unless autotuning picks a template.

What do the modes change? Only Inductor config: reduce-overhead turns on CUDA graphs; max-autotune adds matmul autotuning, coordinate-descent tuning and CUDA graphs; -no-cudagraphs drops the graphs.

Compiled autograd: what and why? Tracing the autograd engine's graph at backward time, including hooks and accumulation, so the backward compiles as one graph and distributed communication can be traced and overlapped.

How do you cut compile time for a 70B model? Regional compilation of the repeated block, warm caches shared across ranks (mega-cache), avoiding recompiles (mark dynamic dims, stable Python args), and profiling compile time by phase.

torch.compile versus torch.export? compile is a JIT inside Python that tolerates breaks and recompiles; export captures one full graph with explicit dynamic-shape constraints for deployment (ExecuTorch, AOTInductor, ONNX).