Why a compiler needs a graph
Eager PyTorch runs a model one operation at a time: Python calls layer_norm, a kernel runs and writes its result to memory, Python calls the next op, and so on. That is easy to write and debug, but a compiler that wants to fuse operations, plan memory or pick kernels for exact shapes has to see the whole computation first. Something has to turn a Python forward into a graph: a list of tensor operations with their inputs and outputs.
There are several ways to get one. Tracing runs the function once with stand-in values and records the ops it sees (torch.jit.trace, JAX's jit); it cannot see Python control flow, only the branch it happened to take. Scripting parses the source into a smaller language (TorchScript), which rejects much ordinary Python. Lazy tensors record ops as they are called and compile when a value is needed. TorchDynamo, the front end of torch.compile, takes a fourth route: it reads the function's Python bytecode and executes it symbolically, before Python would run it.
Stepping through bytecode
CPython lets a library replace the function that evaluates each frame (PEP 523). Dynamo installs its own, and when a compiled function is called it walks the frame's bytecode instruction by instruction, keeping a symbolic stack of variable trackers in place of real values. A tensor on that stack is a proxy for an FX node, backed by a fake tensor that has a shape, dtype and device but no data. The Capture view steps through all 277 instructions Dynamo executed for GPT-2's block 0 on 16 tokens: LOAD_FAST x pushes the input, LOAD_ATTR ln_1 pushes a module, and a CALL on a tensor function adds a node to the graph.
Calls into other Python functions are inlined: Dynamo steps into nn.LayerNorm.forward and nn.Linear.forward (indented rows in the Bytecode panel) and records the F.layer_norm and F.linear calls inside them. Parameters are not baked in; each weight becomes a graph input the first time the code reads it. The FX graph so far panel grows as the walk goes on and ends with 44 nodes: 13 inputs (x and the twelve weights and biases), 30 calls and the output.
When the walk reaches RETURN_VALUE, Dynamo hands the graph to a backend (here one that runs it unchanged, so this tab shows Dynamo alone) and rewrites the frame's bytecode: the new forward loads the compiled graph, passes it the inputs and returns its result. The rewritten bytecode card shows it.
Guards
The graph is only correct under the assumptions made while tracing: that x is a float32 CPU tensor of shape with these strides, that self.attn is still the same kind of module, that torch.ones is still torch.ones, that grad mode is off. Dynamo records each assumption as a guard at the instruction that relied on it (◆ in the Bytecode panel): TENSOR_MATCH for a tensor's dtype, device, shape and strides, TYPE_MATCH and ID_MATCH for objects, GLOBAL_STATE for grad mode and autocast.
Before every later call, Dynamo checks the guards of each cached graph, in C++. If all pass, the rewritten bytecode runs the graph without tracing again. The guard tree card counts the 141 checks it runs. The A cached call card times what this costs here: 2.1 µs to check them all, against 1.90 ms for the block itself on 16 tokens; a cached call through Dynamo took no measurably longer than eager.
Graph breaks
Some Python cannot become graph nodes. The Graph breaks view adds three such lines to the same block: a print, an .item() that turns a tensor into a Python float, and an if that depends on a tensor's value. At each one Dynamo stops, compiles the graph it has so far, emits bytecode that runs the offending line in plain Python, and continues tracing the rest of the function as a new frame (a resume function). torch._dynamo.explain reports 4 graphs and 3 breaks, and the reasons in Dynamo's own words.
A break costs more than the Python in between. Each graph is compiled and guarded on its own, and the backend can only optimise inside a graph: an elementwise op before a break and one after it can never be fused into one kernel (the Fusion tab). torch.compile(fullgraph=True) turns breaks into errors; torch._dynamo.config.capture_scalar_outputs lets .item() stay in the graph as a symbolic number, and torch.cond expresses a data-dependent branch as an op.
Recompiles
When every cached graph fails its guards, Dynamo traces and compiles again. The Recompiles view calls one compiled block seven times. A new length fails the shape guard; Dynamo then marks that dimension dynamic and compiles a graph where the length is a symbol (s27 in the recorded graph), guarded by its range instead of its value, so later lengths reuse it. Turning grad mode on fails the GLOBAL_STATE guard, and casting the weights to bfloat16 fails the dtype guards; each compiles another graph. Dynamo keeps at most a fixed number of graphs per function (8 by default) and falls back to eager beyond that.
Where it came from
PEP 523 added the frame-evaluation hook to CPython 3.6 in 2016. TorchDynamo was built on it at Meta in 2021–22 and shipped as the front end of torch.compile in PyTorch 2.0, described in the PyTorch 2 paper (Ansel et al., 2024) with the Inductor backend that the next three tabs follow: Fusion (what Inductor does with the graph), Tiling (the loops it writes) and Autotuning (how it picks between kernels). The graph format itself is torch.fx (Reed et al., 2022).
Papers
- PyTorch 2: Faster Machine Learning Through Dynamic Python Bytecode Transformation and Graph Compilation TorchDynamo and TorchInductor: capturing graphs from bytecode with guards, graph breaks and dynamic shapes, then compiling them.
- Torch.fx: Practical Program Capture and Transformation for Deep Learning in Python The FX graph format Dynamo emits, and symbolic tracing, the simpler capture it improves on.
- LazyTensor: combining eager execution with domain-specific compilers Capturing graphs by recording ops lazily as they run, the approach behind PyTorch/XLA.
- TensorFlow Eager: A Multi-Stage, Python-Embedded DSL for Machine Learning Eager execution with graph functions staged by tracing, and the retracing it needs when inputs change.
- AutoGraph: Imperative-style Coding with Graph-based Performance Source-to-source conversion of Python control flow into graph ops, another answer to data-dependent branches.
- PyTorch: An Imperative Style, High-Performance Deep Learning Library The eager, define-by-run design that a bytecode-level capture has to preserve.