Graph Breaks, Recompilation & Dynamic Shapes

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 usually works by adding one line. When it does not give a speedup, the cause is almost always one of three things: Dynamo could not trace part of your code (a graph break), it keeps throwing away compiled code and compiling again (recompilation), or the input shapes change and the compiler has to decide how much to specialise on them (dynamic shapes). This page explains how to see each of them, what the relevant switches mean and how to fix the common cases.

Examples were run on Python 3.13 with PyTorch 2.15 (CPU) on 2026-10-31. Compiler internals (config names, log categories) move faster than the rest of PyTorch: the names below are the ones documented for 2.15, and torch._dynamo.* is an internal namespace whose members can change between releases.

How Dynamo captures a program

torch.compile runs your Python function under Dynamo, which reads the bytecode, builds an FX graph of the tensor operations and installs guards: cheap runtime checks (tensor shapes, dtypes, values of Python constants and so on) that must still be true for the compiled graph to be reused. The graph is then handed to a backend (Inductor by default). On every call the guards are evaluated; if they pass, the compiled code runs, and if they fail, Dynamo traces again and adds another compiled variant to the cache.

Two consequences follow, and they explain everything below:

  • Anything Dynamo cannot trace splits the function into several graphs with ordinary Python in between (a graph break), and every graph boundary costs kernel-launch and fusion opportunities.

  • Anything the graph depends on must be guarded, and a guard that fails means compiling again (a recompilation).

Graph breaks

When Dynamo meets code it cannot trace it compiles the graph built so far, runs the unsupported statement in regular Python and then resumes tracing afterwards. Your program stays correct, but each break splits the optimisation scope. The official guide "Working with Graph Breaks" recommends checking for them whenever a compiled model is not faster than eager.

Finding graph breaks

The simplest tools are an environment variable and a compile flag.

# Print where each graph break happens and why
TORCH_LOGS="graph_breaks" python train.py

# Show bytecode, source lines and the resulting FX graph
TORCH_LOGS="trace_bytecode,trace_source,graph_code" python train.py

The same logging can be enabled from code with torch._logging.set_logs(graph_breaks=True). For a browsable report, collect a structured trace and render it with tlparse:

TORCH_TRACE="/tmp/tracedir" python train.py
pip install tlparse
tlparse /tmp/tracedir

tlparse produces an HTML report listing every compiled graph, its guards, the break reasons and the generated code, which is the best starting point for a bug report as well.

fullgraph=True and error_on_graph_break

fullgraph=True turns every graph break into an error, so you find the first one immediately and cannot ship a silently fragmented model:

import torch
import torch.nn as nn


class Net(nn.Module):
    def __init__(self):
        super().__init__()
        self.fc = nn.Linear(16, 16)

    def forward(self, x):
        y = self.fc(x)
        if y.sum() > 0:           # data-dependent Python control flow
            y = y * 2
        return y


model = torch.compile(Net(), fullgraph=True)
try:
    model(torch.randn(4, 16))
except Exception as exc:          # the exception text names the construct and a hint
    print(type(exc).__name__)

Where fullgraph=True is too strict, the 2.15 documentation describes torch._dynamo.error_on_graph_break(flag), which can be used as a decorator or a context manager and can be switched on or off for parts of the code. It only has an effect when fullgraph=False; with fullgraph=True it is ignored, and fullgraph=True cannot be switched back off. The distinction matters: fullgraph=True guarantees a single captured graph, while error_on_graph_break(True) does not.

import torch


@torch._dynamo.error_on_graph_break(True)
@torch.compile
def fn(x):
    x = x + 1
    with torch._dynamo.error_on_graph_break(False):
        torch._dynamo.graph_break()   # tolerated here
    return x + 2

Common causes and fixes

The official "Common Graph Breaks" page groups the causes into incorrect code, data-dependent operations and printing or logging. The recurring fixes are:

Cause Typical symptom Fix

Data-dependent control flow (if tensor.sum() > 0)

Break on a tensor-valued condition

Express the branch with torch.cond, use torch.where, or keep the decision outside the compiled region.

Tensor.item(), .tolist(), int(tensor)

Break on a scalar read-back

Set torch._dynamo.config.capture_scalar_outputs = True so the scalar stays symbolic, or restructure to avoid the read.

print, logging, file I/O

Break on unsupported builtins such as open

Remove from the hot path, decorate the helper with @torch.compiler.disable, or add logging functions to torch._dynamo.config.reorderable_logging_functions.

Calls into code that cannot be traced

Break inside a third-party call

Wrap the call in a custom operator, use torch._dynamo.nonstrict_trace for pure functions, or exclude it from compilation.

The graph-breaks index page orders the strategies as: rewrite the code with supported features, compile pure functions through an escape hatch, or do not compile the code at all. Excluding code is a one-line decorator:

import torch


@torch.compiler.disable
def log_metrics(step, loss_value):
    print(f"step={step} loss={loss_value:.4f}")


@torch.compile
def train_step(model, x, y, step):
    loss = torch.nn.functional.mse_loss(model(x), y)
    log_metrics(step, loss.detach())   # runs eagerly; the rest stays compiled
    return loss

A decorated function still causes one graph break at the call site, so prefer moving it entirely out of the compiled function if it runs every step. @torch.compiler.disable(recursive=False) disables only the decorated function and keeps its callees compilable.

Skipped functions

With fullgraph=False, if Dynamo cannot resume tracing after a graph break it may skip the whole function and run it eagerly. The documentation lists graph breaks inside loops, most context managers and try blocks as unresumable cases, each with a workaround that moves the break outside the construct. A skip loses optimisation opportunities silently, so check the logs rather than assuming the code was compiled. Source: https://docs.pytorch.org/docs/stable/user_guide/torch_compiler/compile/programming_model.skipped_functions.html

Recompilation

Each distinct set of guards produces another compiled entry. Common reasons for guard failures are a changed tensor shape, a different dtype, requires_grad or device, a Python number that changed value, a training/eval() flag flipped on a module, or an object whose identity changed. Frequent recompilation turns a one-off compile cost into a per-step cost.

# Why did it recompile? Prints the failing guard
TORCH_LOGS="recompiles" python train.py

# Every guard that failed, not just the first
TORCH_LOGS="recompiles_verbose" python train.py

The recompile limit

Dynamo caps the number of compiled variants per function. In 2.15 the documented names are torch._dynamo.config.recompile_limit and torch._dynamo.config.accumulated_recompile_limit. When a limit is exceeded the function falls back to eager execution and a warning is issued. Older tutorials and error messages call the first one cache_size_limit; treat that as the previous name. The documentation does not recommend one value: raise the limit only when the extra variants are worth their compile time, and lower it when they are not.

import torch._dynamo

torch._dynamo.config.recompile_limit = 16

Typical culprits

  • Python numbers guarded as constants. Python int and float arguments are specialised by value by default. A learning rate or step counter passed as a Python float to a compiled function recompiles whenever it changes; the troubleshooting page suggests wrapping such values in tensors. The more common structure is to keep schedulers outside the compiled function.

  • Train/eval toggling. model.eval() and model.train() change a module attribute that is guarded. Compiling once and flipping modes gives two variants, which is expected; flipping every step is not.

  • Many distinct shapes. See the next section.

  • Mutating global or module state that the compiled code reads, for example a Python list that grows each step.

Dynamic shapes

By default Dynamo treats shapes as static. The first call specialises on the exact sizes it sees. If a later call has different sizes, the guard fails and Dynamo recompiles, this time marking the dimensions that changed as dynamic (automatic dynamic). From then on the compiled graph handles any size for those dimensions, with symbolic integers (s0, s1, …​) tracked by a per-frame shape environment.

The dynamic argument of torch.compile has three settings:

Value Meaning

None (default)

Automatic dynamic: static first, dynamic for dimensions that changed after a shape-mismatch recompile.

False

Never use dynamic shapes. Each new size compiles again.

True

Use dynamic shapes up front for everything. The official guide advises against it for general use: it makes every size and integer dynamic, which can cause bugs, regressions and longer compile times, and it is described as suited to small models.

Annotating dimensions

When you know a dimension varies (batch size, sequence length), mark it before the first call and avoid the extra static compile:

import torch

model = torch.compile(torch.nn.Linear(32, 8))

x = torch.randn(10, 32)
torch._dynamo.mark_dynamic(x, 0)             # dimension 0 may vary
# torch._dynamo.mark_dynamic(x, 0, min=2, max=4096)   # optional bounds
y = model(x)

x2 = torch.randn(57, 32)                      # reuses the dynamic graph, no recompile
y2 = model(x2)

The documented properties of the annotation functions are:

  • torch._dynamo.mark_dynamic(tensor, dim) fails if the dimension ends up specialised. It must not be called inside a function being compiled, and it does not work on integers.

  • torch._dynamo.maybe_mark_dynamic(tensor, dim) behaves the same but does not fail on specialisation. Use it for inputs shared across several graphs. Sizes 0 and 1 are specialised even then (the 0/1 specialisation).

  • torch._dynamo.decorators.mark_unbacked(tensor, dim) is described as unlikely to be the tool you need; it can help when specialisation occurs in a context where mark_dynamic cannot be applied, and you should check it does not introduce a data-dependent error or a graph break.

  • Dynamic rank (tensors whose number of dimensions changes) is not supported.

For inputs that are hard to reach from code there are two switches: TORCH_COMPILE_DYNAMIC_SOURCES (or torch.compiler.config.dynamic_sources) lists sources to treat as dynamic, and TORCH_COMPILE_STATIC_SOURCES (or torch.compiler.config.static_sources) pins sources static. Entries are comma separated, for example "L['x'], L['y']", and regular expressions are accepted. The names can be copied from the tlparse report. A third option, torch.compiler.set_stance("eager_then_compile"), derives the dynamic inputs automatically at the cost of the first batch.

Seeing what the compiler decided

TORCH_LOGS="dynamic,recompiles" python train.py

Look for eval lines in the dynamic output: they show the guards the compiler added about symbolic sizes. A branch on a symbolic value such as if x.shape[0] > 5 adds a guard (s0 > 5), and a later call that violates it forces another compile. If a dimension keeps being specialised you will see it replaced by a constant in the guards.

Giving the compiler facts

torch._check tells the compiler a fact it may rely on, and refines the value range of symbols:

import torch


def fn(batch_size, x):
    torch._check(batch_size < 100)
    return x[:batch_size]

Unbacked symbolic integers (values only known at run time, such as the result of nonzero or .item() once capture_scalar_outputs is on) cannot be guarded on; code that branches on them raises a data-dependent error, and the usual remedy is torch._check calls that supply the missing facts. The official "Troubleshooting Dynamic Shapes" page covers these errors in detail.

Padding and bucketing as the practical fix

Unlimited distinct sequence lengths are expensive even with dynamic shapes, and kernels tuned by mode="max-autotune" are shape specific. A common production approach is to pad to a small set of bucket sizes (for example multiples of 64) so that both static and dynamic compilation see only a handful of shapes. Compiling with dynamic=False and bucketing is predictable; dynamic shapes trade some kernel quality for fewer compiles.

Warm-up and compile time

Compilation happens on the first call, and again on every recompile, so benchmark after warm-up and report compile time separately. A short checklist when a compiled model is not faster:

  1. Run with fullgraph=True on a small input. If it errors, fix or fence the construct it names.

  2. Run with TORCH_LOGS="graph_breaks,recompiles" for a few steps and count the lines.

  3. Confirm the number of compiled graphs stays flat after the first iterations.

  4. Profile with the profiler: a compiled region should show fused Triton or generated kernels, with few small eager operators between them.

  5. Confirm the bottleneck is not elsewhere (the data pipeline, host-device copies), see Performance Tuning Guide.

Compiled autograd and the backward pass

By default torch.compile compiles the forward pass and traces the backward with AOTAutograd ahead of time. Compiled autograd captures a larger backward graph at run time from the actual autograd graph, which helps when the backward contains hooks, custom functions or distributed communication that AOTAutograd cannot see. According to the tutorial it is enabled either by setting torch._dynamo.config.compiled_autograd = True before the compiled function runs, or by wrapping loss.backward() in torch._dynamo.compiled_autograd.enable(...) with a compiler. It is a specialised feature with its own limitations, so read the tutorial before using it in a training job. Source: https://docs.pytorch.org/tutorials/intermediate/compiled_autograd_tutorial.html

DDP and compile

When combining torch.compile with DistributedDataParallel, wrap the model in DDP first and compile the wrapper. The DDP notes explain that compiling first can stop AOTAutograd from overlapping the gradient all-reduce with backward compute. Dynamo’s DDPOptimizer splits the graph at bucket boundaries to preserve that overlap; it can be inspected with TORCH_LOGS="ddp_graphs" and disabled with torch._dynamo.config.optimize_ddp = False, which keeps correctness but loses performance. Source: https://docs.pytorch.org/docs/stable/notes/ddp.html

Checklist of pitfalls

  • Benchmarking including the first (compile) call.

  • Calling .item(), print or tensor.tolist() inside the compiled step.

  • Passing changing Python scalars (learning rate, epoch) into compiled functions.

  • Flipping train()/eval() every iteration.

  • Letting sequence lengths vary freely without bucketing or mark_dynamic.

  • Treating dynamic=True as a free fix.

  • Ignoring a recompile-limit warning: the function then silently runs in eager mode.

  • Relying on torch._dynamo.* names from old blog posts. Check the 2.15 documentation, for example recompile_limit replaced the older cache_size_limit wording.

For the general usage of the compiler, modes (default, reduce-overhead, max-autotune) and backends, see torch.compile. For the broader performance picture see Hardware & Mixed Precision.