Module contents
Lesson 18 of 24Advanced 75 min

torch.compile: graph capture and fusion

How torch.compile works: TorchDynamo captures graphs from Python bytecode with guards, AOTAutograd traces backward and Inductor generates fused kernels (Triton on GPU, C++ on CPU). Measure speedup separately from compilation, eliminate graph breaks and recompilations, select modes and know when compilation pays off, including Windows support.

After this lesson you can

  • Describe the Dynamo, AOTAutograd and Inductor pipeline and each component’s contribution.
  • Measure torch.compile speedup separately from compilation time.
  • Detect graph breaks and recompilations with TORCH_LOGS and torch._dynamo.explain and rewrite code to avoid them.
  • Choose among default, reduce-overhead and max-autotune modes and relate them to CUDA Graphs.
  • Explain why elementwise operator fusion speeds up bandwidth-bound code.

Before you start

Motivation: one line that speeds up, or slows down

A chain of elementwise operations like F.gelu(x * a + b), followed by eight more unary operations, takes about 7.4 ms on tensors of 16.8 million elements on the lab GPU. Wrapped in torch.compile, it takes 1.25 ms: almost six times less without changing a single line of the function. This is the result of this lesson’s first local cell with a free GPU, and it is not a trick example: it has the form of normalizations, activations, masks, residuals and scaling found throughout modern models.

The same line, applied to the previous lesson’s MLP with batch 64, can leave the training step as slow as or slower than eager, costs several seconds of compilation before the first step and, if input shapes change in each batch, recompiles repeatedly until giving up. And if a debugging print or .item() remains inside forward, the compiler cuts the function into pieces and loses precisely the opportunities that made it worthwhile, without an error message.

This lesson explains what torch.compile does internally so you can predict which outcome will happen:

  1. TorchDynamo intercepts your function’s Python bytecode and extracts a tensor operation graph protected by guards specifying when it can be reused.
  2. AOTAutograd also traces the backward pass before executing it and divides work between forward and backward.
  3. Inductor generates fused kernels: Triton on GPU, C++ on CPU.

Above all, learn to measure: separate compilation from steady state, find graph breaks and recompilations, choose a mode and know when it does not pay off. You need the model of asynchronous CUDA execution, benchmarking methodology and bottleneck classification: compilation remedies two of those regimes, overhead and bandwidth, and does almost nothing for the other two.

Eager versus graph: what is left on the table

In eager mode, PyTorch executes your program as written: every operation in y = F.gelu(x * a + b) is a Python call that passes through the dispatcher, chooses a kernel and launches it on the GPU. This operation-by-operation execution is what makes PyTorch so convenient (you can put a print anywhere, use a debugger, mix arbitrary Python), and has two costs a compiler seeing the whole program could avoid.

The first is overhead. Each operation costs the CPU 5 to 30 µs of Python, dispatcher and launch, whether the GPU does much work or little. If kernels last less than that, the GPU waits for the CPU: the previous lesson’s overhead regime.

The second is memory traffic. Each kernel is an independent program: it reads its inputs from HBM, GPU global memory, and writes its entire result there, because the next kernel can only find it there. In the chain above, x * a writes a 64 MiB tensor t1 that + b immediately rereads, and so on. For elementwise operations, which perform one or a few calculations per byte, that traffic is the time: their arithmetic intensity is one or two orders of magnitude below the roofline model’s ridge point.

A compiler that sees the whole chain can attack both at once.

Savings can be counted exactly, and the result is stronger than it looks: fusion is not merely better than eager, it is optimal.

Proof
  1. Each eager kernel starts with a cold cache relative to its inputs (by assumption, the previous tensor did not fit), so it reads its full rjr_j inputs, rj sNr_j\,sN bytes, and writes its complete output, sNsN bytes. Summing over the mm operations gives the formula.
  2. The fused kernel divides the NN indices among thread blocks. Each block loads its indices’ elements of each tensor in II from global memory once, calculates the entire chain in registers, because element ii of each intermediate depends only on elements ii of its inputs, and stores its indices’ elements of each tensor in OO. Each index is loaded and stored once per tensor: sN∣I∣+sN∣O∣sN\abs{I} + sN\abs{O}.
  3. Initially inputs exist only in global memory and outputs must end there. By the extra assumption, changing any element of an input may change a result, so a program not reading it would give an incorrect result for some value of that element. Any correct program must therefore read every element of II at least once and write every element of OO at least once. This is the computation’s compulsory traffic, and the fused kernel moves not one byte more.

For the chain of kk unary operations, rj=1r_j = 1 for all jj, ∣I∣=∣O∣=1\abs{I} = \abs{O} = 1, and the ratio is sN⋅2k/(sN⋅2)=ksN \cdot 2k / (sN \cdot 2) = k.

∎

Traffic determines time when kernels are bandwidth-bound; overhead determines it when they are tiny. The asynchronous launch model from lesson 16 can bound both effects in a single inequality.

Proof

Kernel ii (counting from 1) is ready at iℓi\ell and starts at inii=max⁡(iℓ,fini−1)\text{ini}_i = \max(i\ell, \text{fin}_{i-1}), with fin0=0\text{fin}_0 = 0. Lower bound: the last does not start before KℓK\ell, and the GPU executes kernels one at a time, so T≥∑igiT \ge \sum_i g_i. Upper bound by induction: if fini−1≤(i−1)ℓ+∑j<igj\text{fin}_{i-1} \le (i-1)\ell + \sum_{j \lt i} g_j, then inii≤iℓ+∑j<igj\text{ini}_i \le i\ell + \sum_{j \lt i} g_j and fini≤iℓ+∑j≤igj\text{fin}_i \le i\ell + \sum_{j \le i} g_j. For i=Ki = K this is the bound. In each limiting regime, one of the two quantities dominates and both bounds agree to first order.

∎

That is what the first interactive shows. Above is data flow between HBM and a streaming multiprocessor’s (SM) registers; below are the two executions on a common timeline, calculated using the corollary’s model.

InteractiveFusion saves trips to memory
HBM: GPU global memorymoved 656 MiBxabt1t2t3ymaskSM: each operation is a separate kernel×a+bGELUdropoutEager×a+bGELUdropoutFusedfused kernel0500 µs1.00 ms1.50 ms2.00 ms2.50 ms3.00 ms
t1 = x * a                # k1: reads 128 MiB, writes 64.0 MiB
t2 = t1 + b               # k2: reads 128 MiB, writes 64.0 MiB
t3 = F.gelu(t2)           # k3: reads 64.0 MiB, writes 64.0 MiB
y = F.dropout(t3, 0.1)    # k4: reads 64.0 MiB, writes 80.0 MiB
  • HBM read
  • HBM write
  • kernel eager
  • fused kernel
  • tensor never written
Data-flow view
t = 3.29 ms
2²⁴ (16.78 M)
0
Precision
210 GB/s
15 µs
Kernels (eager · fused)4 · 2 (seed + chain)
Bytes moved, eager656 MiB
Bytes moved, fused272 MiB
Byte ratio×2.41
Estimated time3.29 ms → 1.39 ms
Estimated speedup×2.37
Intermediates in HBM (eager)3 × 64.0 MiB
Moved up to t656 MiB · 272 MiB
Each kernel is bandwidth-bound (intensity 0.88 FLOP/B, well below the 29 FLOP/B ridge): time is proportional to bytes, and speedup ×2.37 approaches byte ratio ×2.41. Add operations: eager pays fully for each; the fused kernel pays almost nothing.
The chain x⋅a+bx \cdot a + b, GELU, kk unary operations and dropout, in eager (one kernel per operation) and fused (one kernel, plus a tiny one generating dropout's random seed). Play the animation in both views and compare bytes moved. Add operations to the chain: the byte ratio grows and speedup follows it. Then reduce size to 2142^{14} elements: kernels last less than their launch, GPU waits for CPU and the gain becomes the launch ratio. Defaults: 210 GB/s, measured on the lab RTX 4060.

What you should have seen:

  • With large tensors, time follows bytes. The default chain moves 41 bytes per element in eager (12 for x * a, 12 for + b, 8 for GELU and 9 for dropout, which also writes a one-byte mask) and 17 fused: it reads xx, aa and bb and writes yy and the mask, which the fused kernel must also save because backward needs it and AOTAutograd does not recompute random operations. The byte ratio is 41/17≈2.4141/17 \approx 2.41, and estimated speedup, ×2.37\times 2.37, nearly reaches it: the difference is launches. Each additional unary operation adds 8 bytes per element to eager and nothing to the fused version.
  • With small tensors, overhead dominates. With 2142^{14} elements each eager kernel lasts less than 2 µs and the GPU spends most of its time waiting for CPU. Fusion still wins, but by launching fewer kernels, not bytes.
  • Precision does not change the ratio. BF16 moves half as many bytes in both versions (except the mask), so eager and fused speed up in almost the same proportion. Reduced precision and fusion are remedies that add rather than compete.

Measured in the lab with a free GPU, the model is nearly exact. With the motivating chain and kk extra unary operations, the Inductor section’s local cell obtained speedups of ×2.0\times 2.0, ×3.0\times 3.0, ×3.9\times 3.9 and ×5.9\times 5.9 for k=0,2,4,8k = 0, 2, 4, 8, versus byte ratios 22, 33, 44 and 66 predicted by the proposition, and both versions moved data at about 215 GB/s: both are at the bandwidth ceiling and differ only in how many bytes they request. With other processes using the GPU, figures vary 20 or 30% in either direction, but the trend holds.

TorchDynamo: capturing the graph by reading bytecode

To fuse, the whole program must be visible, and in PyTorch the program is arbitrary Python. Before PyTorch 2 there were two ways to obtain a graph and both had a serious problem:

  • Trace by execution (torch.jit.trace, torch.fx.symbolic_trace): call the function with special values that record each operation instead of calculating. This works while code does not make decisions using data. If it does, tracing with an example freezes the branch that example took and at most emits an easily missed TracerWarning; symbolic tracing simply fails. You will implement it in the next section.
  • Rewrite in a Python subset (TorchScript): the compiler understands if and loops, but only in a restricted language, and porting a real model required rewriting it.

TorchDynamo solves the problem one level lower, in the interpreter. Since PEP 523, CPython permits installing a function that evaluates execution frames instead of the standard evaluator. Dynamo installs its own: when you execute a compiled function, it intercepts its frame before it runs, executes its bytecode symbolically, instruction by instruction, and records each tensor operation in an FX graph. Everything else—module attributes, constants, lists, Python function calls—is evaluated during tracing and turned into graph constants or conditions that must hold.

Guards are the idea making everything else possible. The graph for h = x @ w is only correct for tensors with the shape, type and device used for tracing, and for torch and torch.relu as they were at that moment. Dynamo records all these assumptions and checks them on each call, in C++ and microseconds: tensors (type, device, shape, strides, requires_grad), identity of global objects used, Python constant values, each module’s training attribute, gradient mode. An if x.shape[0] > 16 breaks nothing: shape is known at trace time, so the branch is resolved and a guard remains.

A graph break, by contrast, does not give a wrong result: it gives a slow one. Each break splits the graph into two Inductor optimizes separately, without fusion across the cut; forces a return to Python in mid-step; and, if caused by needing a GPU value on CPU (.item(), an if on a tensor), adds a synchronization that empties the stream queue. These are the most frequent causes, checked with torch._dynamo.explain in PyTorch 2.11:

Code inside compiled functionGraph break?Reason
print(h.shape)yesDynamo does not trace the print builtin
h.mean().item(), int(h.sum()), bool(t)yesreturns a Python number; captured only with capture_scalar_outputs
if h.mean() > 0.1:yesbranch depends on a tensor value
h[h > 0]yesoutput shape depends on data
h.tolist() on floatsyesunsupported
special.expit(h.numpy()) from SciPyyesDynamo cannot trace a SciPy ufunc
np.exp(h.numpy()), np.clip(...)noDynamo translates NumPy code into torch operations
if x.shape[0] > 16:, math.sqrt(x.shape[-1])noshape is known during tracing: a guard remains

The last two rows are surprising. Since PyTorch 2.1, Dynamo traces NumPy functions it recognizes and replaces them with torch equivalents, so torch.from_numpy(1 / (1 + np.exp(-h.numpy()))) is captured whole. What breaks the graph is not NumPy, but any compiled library Dynamo does not know.

The second interactive uses real data: each function variant was run with TorchDynamo and what you see (fragments, operations in each, reasons, guards and compilations per call) is what it returned.

InteractiveHunting graph breaks
1@torch.compile
2def paso(x, w):
3 h = x @ w
4 print("h:", h.shape)⟳ print
break: Dynamo cannot trace builtin print
5 h = torch.relu(h)
6 escala = h.abs().amax().item()⟳ .item()
break: .item() returns a Python number
7 h = h / escala
8 if h.mean() > 0.1:⟳ if
break: branch depends on a tensor value
9 h = h * 2
10 if x.shape[0] > 16: # guard, not a break
11 h = h - h.mean(0)
12 h = torch.from_numpy(special.expit(h.numpy()))⟳ SciPy
break: Dynamo cannot trace SciPy ufunc
13 return h.sum(-1)
Captured graphs (select one)
Guards of G1 (batch 32)
  • x: float32 tensor on CPU, shape [32, 64], same strides, requires_grad=False
  • w: float32 tensor on CPU, shape [64, 64], same strides, requires_grad=False
  • print remains the builtin
  • global state: gradient mode, default device, deterministic algorithms, autograd hooks
Successive calls to paso(x, w): rows in batch x (select one)
  • G1
  • G2
  • G3
  • G4
  • G5
  • break
  • compiles
  • reuses
Debugging
Scale
Condition
Sigmoid
Batch sequence
dynamic
Captured graphs5
Graph breaks4
Operations in graphs13
Compilations in sequence12
Eager calls due to limit0
4 graph breaks: the function runs as 5 graphs with Python between them. Breaks cut fusion, and those requiring a tensor value in Python force GPU/CPU synchronization.
A function with four common traps. Click each marked line to replace it with its rewritten version and watch the fragments regroup. Click a fragment to see its guards: notice the escala == … guard after .item(). Then choose a batch sequence and a dynamic value, and click a call to learn why it compiles. Goal: one graph and no recompilation with ‘smaller last’. PyTorch 2.11 CPU data.

Three things the interactive shows that are not obvious:

  • One break multiplies recompilations. With the four traps, a new batch shape recompiles five fragments, not one: each resume function has its own guards on the shape of h.
  • The value of an .item() becomes a constant. The resume function receives escala as a Python float and Dynamo specializes it: guard escala == 3.8726. The next call brings another value and recompiles; with dynamic=None, that recompilation makes the float symbolic and stops, but with dynamic=False it recompiles on every call until the limit is exhausted.
  • Each branch of a data-dependent if is a fragment. The first time the other branch is taken, another resume function compiles. No error or warning: just one more compilation on an arbitrary call.

From scratch: a toy tracer and fuser

The best way to understand why graph breaks exist is to build a tracer that does not have them. The following uses operator overloading from the Python data model: a Proxy has no value, and each operation with it adds a graph node and returns another Proxy. It is torch.fx.symbolic_trace in miniature.

[ ]A tracer using operator overloadingBrowser
import numpy as np

ELEMENTO_A_ELEMENTO = {"add", "sub", "mul", "div", "neg", "tanh", "exp", "gelu", "gt"}

class Nodo:
    def __init__(self, op, args):
        self.op, self.args = op, args          # args: otros Nodos o constantes de Python
        self.nombre = None

class Grafo:
    def __init__(self):
        self.nodos, self.entradas, self.salida = [], [], None
    def nuevo(self, op, args):
        n = Nodo(op, args)
        n.nombre = f"v{len(self.nodos)}"
        self.nodos.append(n)
        return n
    def __str__(self):
        fmt = lambda a: a.nombre if isinstance(a, Nodo) else repr(a)
        lineas = [f"{n.nombre} = {n.op}({', '.join(fmt(a) for a in n.args)})" for n in self.nodos]
        return "\n".join(lineas + [f"return {self.salida.nombre}"])

class TrazaImposible(Exception):
    pass

class Proxy:
    """Un valor simbólico: operar con él no calcula nada, añade un nodo al grafo."""
    def __init__(self, grafo, nodo):
        self.g, self.n = grafo, nodo
    def _op(self, op, *otros):
        args = [self.n] + [o.n if isinstance(o, Proxy) else o for o in otros]
        return Proxy(self.g, self.g.nuevo(op, args))
    def __add__(self, o): return self._op("add", o)
    def __radd__(self, o): return self._op("add", o)
    def __sub__(self, o): return self._op("sub", o)
    def __mul__(self, o): return self._op("mul", o)
    def __rmul__(self, o): return self._op("mul", o)
    def __truediv__(self, o): return self._op("div", o)
    def __neg__(self): return self._op("neg")
    def __gt__(self, o): return self._op("gt", o)
    def __bool__(self):
        raise TrazaImposible("bool() de un valor simbólico: el trazador no conoce los datos")

def _gelu(x):
    return 0.5 * x * (1.0 + np.tanh(0.7978845608 * (x + 0.044715 * x * x * x)))

# funciones que entienden tanto arrays como Proxies
def tanh(x): return x._op("tanh") if isinstance(x, Proxy) else np.tanh(x)
def exp(x): return x._op("exp") if isinstance(x, Proxy) else np.exp(x)
def gelu(x): return x._op("gelu") if isinstance(x, Proxy) else _gelu(x)
def suma(x): return x._op("sum") if isinstance(x, Proxy) else np.sum(x)

def trazar(f, n_entradas):
    g = Grafo()
    entradas = []
    for i in range(n_entradas):
        nodo = g.nuevo("entrada", [i])
        g.entradas.append(nodo)
        entradas.append(Proxy(g, nodo))
    g.salida = f(*entradas).n
    return g

def f(x, a, b):
    y = x * a + b
    y = gelu(y)
    y = 2 * tanh(y) - 1
    return y / (1 + exp(-y))

g = trazar(f, 3)
print(g)

The graph is exactly the sequence of operations, with no Python around it: 2 * becomes mul(v6, 2) thanks to __rmul__, and v8 appears twice because y is used in numerator and denominator. Now an eager interpreter executes one node per “kernel” and materializes each result, and a fusion pass groups consecutive elementwise nodes and evaluates the group in chunks: load a piece of each external input, chain all operations on that piece, and save only the group’s outputs, like the Triton kernel in the first interactive.

[ ]Eager versus fused: traffic and memoryBrowser
import time, tracemalloc

NUMPY = {"add": np.add, "sub": np.subtract, "mul": np.multiply, "div": np.divide, "neg": np.negative,
         "tanh": np.tanh, "exp": np.exp, "gelu": _gelu, "gt": np.greater, "sum": np.sum}

def usuarios(g):
    u = {n: [] for n in g.nodos}
    for n in g.nodos:
        for a in n.args:
            if isinstance(a, Nodo):
                u[a].append(n)
    return u

def ejecutar_eager(g, *xs):
    """Un kernel por nodo: cada resultado se materializa entero. Cuenta los bytes leídos y escritos."""
    pendientes = {n: len(v) for n, v in usuarios(g).items()}
    val, trafico = {}, 0
    for n in g.nodos:
        if n.op == "entrada":
            val[n] = xs[n.args[0]]
            continue
        args = [val[a] if isinstance(a, Nodo) else a for a in n.args]
        val[n] = NUMPY[n.op](*args)
        trafico += sum(x.nbytes for x in args if isinstance(x, np.ndarray)) + np.asarray(val[n]).nbytes
        for a in n.args:                       # como PyTorch: un temporal se libera cuando nadie lo usa ya
            if isinstance(a, Nodo):
                pendientes[a] -= 1
                if pendientes[a] == 0 and a.op != "entrada" and a is not g.salida:
                    del val[a]
    return val[g.salida], trafico

class Fusionado:
    """Un grupo de nodos elemento a elemento que se evalúa como un único «kernel»."""
    def __init__(self, nodos, externos, salidas):
        self.nodos, self.externos, self.salidas = nodos, externos, salidas

def fusionar(g):
    """Agrupa nodos elemento a elemento consecutivos. Un nodo del grupo solo se escribe en memoria
    si alguien de fuera del grupo lo usa o si es la salida del grafo."""
    u = usuarios(g)
    plan, grupo = [], []
    def cerrar():
        if not grupo:
            return
        dentro = set(grupo)
        externos = []
        for n in grupo:
            for a in n.args:
                if isinstance(a, Nodo) and a not in dentro and a not in externos:
                    externos.append(a)
        salidas = [n for n in grupo if n is g.salida or any(v not in dentro for v in u[n])]
        plan.append(Fusionado(list(grupo), externos, salidas))
        grupo.clear()
    for n in g.nodos:
        if n.op in ELEMENTO_A_ELEMENTO:
            grupo.append(n)
        else:
            cerrar()
            plan.append(n)
    cerrar()
    return plan

def ejecutar_fusionado(g, plan, *xs, bloque=4096):
    val, trafico = {}, 0
    for p in plan:
        if isinstance(p, Nodo):
            if p.op == "entrada":
                val[p] = xs[p.args[0]]
                continue
            args = [val[a] if isinstance(a, Nodo) else a for a in p.args]
            val[p] = NUMPY[p.op](*args)
            trafico += sum(x.nbytes for x in args if isinstance(x, np.ndarray)) + np.asarray(val[p]).nbytes
            continue
        N = val[p.externos[0]].shape[0]
        for s in p.salidas:
            val[s] = np.empty(N)
        for i in range(0, N, bloque):          # cada bloque: cargar, encadenar en «registros», guardar
            loc = {e: val[e][i:i + bloque] for e in p.externos}
            for n in p.nodos:
                loc[n] = NUMPY[n.op](*[loc[a] if isinstance(a, Nodo) else a for a in n.args])
            for s in p.salidas:
                val[s][i:i + bloque] = loc[s]
        trafico += sum(val[e].nbytes for e in p.externos) + sum(val[s].nbytes for s in p.salidas)
    return val[g.salida], trafico

plan = fusionar(g)
for p in plan:
    if isinstance(p, Fusionado):
        print(f"kernel fusionado: {len(p.nodos)} nodos [{', '.join(n.op for n in p.nodos)}]\n"
              f"   lee {[e.nombre for e in p.externos]}, escribe {[s.nombre for s in p.salidas]}")

rng = np.random.default_rng(0)
N = 2**20
x, a, b = (rng.standard_normal(N) for _ in range(3))
resultados = {}
for nombre, correr in [("eager", lambda: ejecutar_eager(g, x, a, b)),
                       ("fusionado", lambda: ejecutar_fusionado(g, plan, x, a, b))]:
    tracemalloc.start()
    t0 = time.perf_counter()
    y, trafico = correr()
    t = time.perf_counter() - t0
    _, pico = tracemalloc.get_traced_memory()
    tracemalloc.stop()
    resultados[nombre] = (y, trafico)
    print(f"{nombre:10s} tráfico {trafico / 2**20:6.1f} MiB | memoria extra pico {pico / 2**20:5.1f} MiB | {t * 1e3:6.1f} ms")
print("igual que la función original:", np.allclose(resultados["fusionado"][0], f(x, a, b)),
      "| igual que eager:", np.allclose(resultados["fusionado"][0], resultados["eager"][0]))
print(f"cociente de tráfico: {resultados['eager'][1] / resultados['fusionado'][1]:.2f}")

The ten operations form a single group reading v0, v1 and v2 and writing only v12. The eager interpreter moves 23 complete 8 MiB arrays, 184 MiB, and the fused one 4, 32 MiB: a ratio of 5.755.75, which is ∑j(rj+1)/(∣I∣+∣O∣)=23/4\sum_j (r_j + 1) / (\abs{I} + \abs{O}) = 23/4, the proposition applied to a graph with two uses of v8. Peak extra memory also falls because group intermediates exist only chunk by chunk. Time, in contrast, does not tell a GPU’s story: NumPy cannot truly fuse (every operation on a chunk is still a call with overhead) and there is no slow HBM to wait for here, so eager and fused remain in the same order of magnitude. What transfers to the GPU is traffic, and that is exact.

The underlying question remains. What does this tracer do with a function that decides based on data?

[ ]Data-dependent control flowBrowser
def h(x, a, b):
    y = x * a + b
    if suma(y) > 0:                 # la rama depende de los DATOS
        return tanh(y)
    return -y

# 1. Trazador simbólico: no puede decidir la rama
try:
    trazar(h, 3)
except TrazaImposible as e:
    print("trazador simbólico:", e)

# 2. Trazador con ejemplo, como torch.jit.trace: decide con el ejemplo y no avisa
class ProxyConcreto(Proxy):
    """Proxy que además lleva el valor del ejemplo: puede responder a bool(), pero la respuesta queda congelada."""
    def __init__(self, grafo, nodo, valor):
        super().__init__(grafo, nodo)
        self.v = valor
    def _op(self, op, *otros):
        p = super()._op(op, *otros)
        args = [self.v] + [o.v if isinstance(o, ProxyConcreto) else o for o in otros]
        return ProxyConcreto(self.g, p.n, NUMPY[op](*args))
    def __bool__(self):
        self.g.guardas.append((self.n, bool(self.v)))    # anotamos la condición y la rama que se tomó
        return bool(self.v)

def trazar_con_ejemplo(f, *ejemplo):
    g = Grafo()
    g.guardas = []
    entradas = []
    for i, v in enumerate(ejemplo):
        nodo = g.nuevo("entrada", [i])
        g.entradas.append(nodo)
        entradas.append(ProxyConcreto(g, nodo, v))
    g.salida = f(*entradas).n
    return g

x1 = np.abs(rng.standard_normal(8)); a1 = np.ones(8); b1 = np.zeros(8)      # suma(y) > 0: rama tanh
gc = trazar_con_ejemplo(h, x1, a1, b1)
print("\ngrafo trazado con un ejemplo positivo:\n" + str(gc))
x2 = -x1                                                                       # ahora suma(y) < 0
y_grafo, _ = ejecutar_eager(gc, x2, a1, b1)
print("\n¿coincide con Python en un ejemplo negativo?", np.allclose(y_grafo, h(x2, a1, b1)))

# 3. Lo que hace Dynamo, en miniatura: comprobar la condición antes de reutilizar, y retrazar si falla
class Compilado:
    def __init__(self, f):
        self.f, self.cache, self.compilaciones = f, [], 0
    def _guardas_ok(self, g, xs):
        for nodo, esperado in g.guardas:
            prefijo = Grafo()                                  # el grafo hasta la condición...
            prefijo.nodos, prefijo.salida = g.nodos[: g.nodos.index(nodo) + 1], nodo
            if bool(ejecutar_eager(prefijo, *xs)[0]) != esperado:   # ...y Python decide con su valor
                return False
        return True
    def __call__(self, *xs):
        for g in self.cache:
            if self._guardas_ok(g, xs):
                return ejecutar_eager(g, *xs)[0]
        self.compilaciones += 1
        g = trazar_con_ejemplo(self.f, *xs)
        self.cache.append(g)
        return ejecutar_eager(g, *xs)[0]

hc = Compilado(h)
for xs in [(x1, a1, b1), (x2, a1, b1), (2 * x1, a1, b1), (3 * x2, a1, b1)]:
    assert np.allclose(hc(*xs), h(*xs))
print("con guardas: 4 llamadas correctas,", hc.compilaciones, "compilaciones (una por rama)")

The three answers summarize the history of graph capture. The symbolic tracer refuses, because at trace time no data exists to decide with. The example tracer decides from the example, leaves the condition computation (sum and gt) unused in the graph and returns incorrect results for any input that would have taken the other branch: the almost silent failure that made torch.jit.trace famous. The third version picks up Dynamo’s idea: to decide, calculate the condition, so execute the prefix up to the condition, Python makes the decision with the real value, and use the graph of the corresponding branch, compiled the first time it is needed. Our miniature is rougher: it checks the condition by executing the prefix and then executes the whole graph again, including the prefix. Dynamo repeats nothing because it cuts the graph at the condition: the first graph ends by returning the condition tensor, Python converts it to bool and the rest of each branch is a resume function with its own graph. Both versions are always correct, and the price is exactly that of a break: two graphs instead of one and a value that must travel from GPU to CPU.

AOTAutograd and Inductor

Dynamo delivers an FX graph of the forward pass. Training needs backward, which in eager autograd builds on the fly, as you saw with the dynamic autograd graph. AOTAutograd (ahead-of-time autograd) builds it before executing anything, in four steps:

  1. Trace the joint graph. Run forward with fake tensors (no data, only metadata) under autograd and also trace the backward call: the result is a single graph with forward and backward, written in ATen operators.
  2. Functionalize. Remove in-place mutations and views, rewriting them as pure operations with explicit copies where needed. A graph without side effects can be reordered and fused safely.
  3. Decompose. Translate more than 2000 ATen operators to a canonical set of a few hundred. F.gelu, layer_norm or addmm become simpler operations the compiler can fuse.
  4. Partition the graph into forward and backward with a minimum-capacity cut (min-cut), deciding which forward tensors to save for backward and which to recompute there. Recomputing a cheap elementwise operation often costs less than writing it to memory in forward and reading it in backward: this is rematerialization, the same byte calculation from the proposition applied to the boundary between the two graphs.

Inductor receives those graphs and generates code. It lowers each operation into a loop representation (“for each index, load these values and calculate this”), decides which nodes fuse into the same loop (producers with consumers, sibling operations, reductions with their surroundings), and emits one kernel per group: Triton on NVIDIA and AMD GPUs, C++ with OpenMP and vectorization on CPU. Matrix multiplications and convolutions go to cuBLAS and cuDNN, or Triton templates if autotuning selects them. Finally it generates a Python wrapper program that allocates buffers and launches kernels in order.

The first local cell measures the motivating chain on GPU, first checks that the compiled version computes the same thing and compares speedup with the proposition’s byte ratio. It needs the local CUDA lab, and the Windows section explains what to do if it fails on your machine.

[ ]Fusion, measuredLocal GPU
import time
import torch
import torch.nn.functional as F
from torch.utils import benchmark
from torch.profiler import profile, ProfilerActivity

dev = "cuda"
torch.manual_seed(0)

def mediana(fn, *args):
    return benchmark.Timer(stmt="fn(*args)", globals={"fn": fn, "args": args}).blocked_autorange(min_run_time=0.4).median

def kernels_por_llamada(fn, *args):
    fn(*args)
    torch.cuda.synchronize()
    with profile(activities=[ProfilerActivity.CUDA]) as prof:
        fn(*args)
        torch.cuda.synchronize()
    return sum(1 for e in prof.events() if e.device_type == torch.autograd.DeviceType.CUDA)

def cadena(k):
    """x * a + b, GELU y k operaciones unarias más: k + 3 kernels en eager."""
    def f(x, a, b):
        y = F.gelu(x * a + b)
        for i in range(k):
            y = torch.tanh(y) if i % 2 == 0 else 2 * y
        return y
    return f

N = 2**24                                         # 16.8 M elementos, 64 MiB por tensor en FP32
x, a, b = (torch.randn(N, device=dev) for _ in range(3))
print(f"{'k':>2} {'kernels':>9} {'eager':>9} {'compilado':>10} {'acel.':>6} {'bytes':>7}   GB/s eager | compilado")
for k in [0, 2, 4, 8]:
    f = cadena(k)
    g = torch.compile(f)
    torch.testing.assert_close(g(x, a, b), f(x, a, b))      # antes de medir, comprobar que calcula lo mismo
    te, tc = mediana(f, x, a, b), mediana(g, x, a, b)
    bytes_e = (12 + 12 + 8 + 8 * k) * N                      # x*a: 3 tensores; +b: 3; GELU: 2; cada unaria: 2
    bytes_c = 16 * N                                         # leer x, a, b y escribir y
    ke, kc = kernels_por_llamada(f, x, a, b), kernels_por_llamada(g, x, a, b)
    print(f"{k:>2} {ke:>4} → {kc:<2} {te * 1e3:7.2f} ms {tc * 1e3:7.2f} ms {te / tc:5.2f}× {bytes_e / bytes_c:5.2f}×"
          f"   {bytes_e / te / 1e9:5.0f} | {bytes_c / tc / 1e9:5.0f}")
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

Each row confirms the proposition: k+3k + 3 kernels become one, speedup follows the byte ratio and the GB/s column, each version’s bytes divided by its time, is practically the same in both: HBM bandwidth, 200 to 220 GB/s on the lab RTX 4060 with a free GPU. Both versions go equally fast; one requests far fewer bytes. If another process shares the GPU, effective bandwidth of each measurement falls unevenly and speedup can land above or below the ratio: rerun the cell and focus on the trend, not the second decimal.

You can read the kernel Inductor generates. run_and_get_code returns the source of everything compiled:

[ ]The Triton kernel generated by InductorLocal GPU
from torch._inductor.utils import run_and_get_code

torch._dynamo.reset()
_, codigos = run_and_get_code(torch.compile(lambda x, a, b: F.gelu(x * a + b)), x, a, b)
fuente = codigos[0]
ini = fuente.index("@triton.jit")
fin = fuente.index("''', device_str", ini)
print(fuente[ini:fin].strip())
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

The kernel name, triton_poi_fused_add_gelu_mul_0, already says what it is: a pointwise kernel fusing addition, GELU and multiplication. Its body follows the first interactive: three tl.load, the whole chain in temporary variables (GELU decomposed into products and an erf call), and a single tl.store. If you ever wonder what the compiler fused, TORCH_LOGS="output_code" prints all this for any model.

Dynamic shapes and recompilations

Guards have a hidden cost: each time one fails, Dynamo recaptures and Inductor recompiles, taking seconds. The most frequent source of failures is input shape.

Symbolic dimensions have their own guards. Code compiled for s0s_0 rows works for any s0≥2s_0 \ge 2, but if the function contains if x.shape[0] > 16, code depends on the branch and Dynamo adds guard s0>16s_0 > 16 (or s0≤16s_0 \le 16): a batch of 9 rows recompiles even though the dimension was already dynamic. You saw this in the interactive’s “variable” sequence.

Other guards causing recompilations in practice are: a change of dtype or device; passing a tensor with different requires_grad; calling model.eval() on a model compiled in training mode (the training guard fails once, and returning to train() reuses the first version); Python int or float arguments changing value (specialized the first time and made symbolic the second, with dynamic=None); and values returning to Python through .item() before a break.

The most common training case is the last batch, smaller: with 50 000 examples and batches of 64, the last has 16. With dynamic=None it costs one recompilation per epoch, only the first time, and then dynamic code serves both sizes. With sequence models, by contrast, length changes each batch and the decision really matters. The next cell compares three variable-length strategies, counting compilations with a counting backend and disabling disk caches so times reflect real compilation:

[ ]Variable lengths: three strategiesLocal GPU
import time
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch._inductor.config as inductor_config
from torch._dynamo.testing import CompileCounterWithBackend

dev = "cuda"
torch.manual_seed(0)
capa = nn.Sequential(nn.Linear(64, 256), nn.GELU(), nn.Linear(256, 64), nn.LayerNorm(64)).to(dev)
def bloque(x):                                    # x: (lote, longitud, 64), una secuencia de tokens
    return capa(x)

longitudes = [128, 128, 96, 128, 64, 100, 77, 128, 50, 113]

def rellenar(x, multiplo=64):                     # padding hasta un múltiplo fijo de la longitud
    return F.pad(x, (0, 0, 0, -x.shape[1] % multiplo))

def recorrer(nombre, relleno=False, **kw):
    torch._dynamo.reset()
    contador = CompileCounterWithBackend("inductor")
    f = torch.compile(bloque, backend=contador, **kw)
    tiempos, nuevas = [], []
    for T in longitudes:
        x = torch.randn(8, T, 64, device=dev)
        antes = contador.frame_count
        torch.cuda.synchronize()
        t0 = time.perf_counter()
        y = f(rellenar(x) if relleno else x)[:, :T]   # con relleno, se descartan las posiciones añadidas
        torch.cuda.synchronize()
        tiempos.append(time.perf_counter() - t0)
        nuevas.append(contador.frame_count - antes)
        torch.testing.assert_close(y, bloque(x))
    marcas = " ".join(f"{T}{'*' if n else ''}" for T, n in zip(longitudes, nuevas))
    print(f"{nombre:26s} {contador.frame_count:2d} compilaciones, {sum(tiempos):5.1f} s | {marcas}")

inductor_config.force_disable_caches = True          # tiempos de compilación en frío
recorrer("dynamic=False", dynamic=False)
recorrer("dynamic=None (por defecto)")
recorrer("relleno a múltiplos de 64", relleno=True, dynamic=False)
inductor_config.force_disable_caches = False
print("(* = esa llamada compiló)")
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

With dynamic=False every new length compiles for several seconds: seven in ten calls, and if there were more than eight distinct lengths, the rest would run eager. With dynamic=None there are two: the first specialized for 128, and the second on reaching 96, already symbolic and serving all the others. Padding to multiples of 64 also stays at two (lengths fall into 64 or 128) and retains specialized kernels, at the cost of calculating positions later discarded; in an attention model those positions must also be masked. Grouping examples by length in the sampler reduces wasted padding without multiplying shapes.

Modes: default, reduce-overhead and max-autotune

torch.compile has three main modes, each targeting a different regime.

CUDA Graphs are not free, and their restrictions explain most problems with reduce-overhead. A recorded graph reads fixed addresses, so Inductor copies every input into a static buffer before replay; a new shape requires recording another graph; nothing inside can synchronize with CPU; and graph memory lives in a private pool reused on each replay, so one call’s output is overwritten by the next. If you save outputs of several calls in a list without copying them, PyTorch raises RuntimeError: accessing tensor output of CUDAGraphs that has been overwritten by a subsequent run. The solution is .clone() for anything you want to retain. The first call compiles, the second or third records the graph, and only then does steady state appear: measuring earlier measures recording.

There is a lab hardware detail worth knowing. Inductor only considers Triton templates for matmul in max-autotune if the GPU has at least 68 multiprocessors; a laptop RTX 4060 has 24, and Inductor warns “Not enough SMs to use max_autotune_gemm mode”. On this machine, max-autotune tunes pointwise and reduction kernels, uses CUDA Graphs and leaves matmul to cuBLAS.

When compilation pays off

Compilation is an investment: pay CC seconds at the start to save te−tct_e - t_c per step. The arithmetic is simple, but recompilations change its nature.

Proof
  1. K(n)−E(n)=C−n(te−tc)K(n) - E(n) = C - n(t_e - t_c), which is ≤0\le 0 exactly when n≥C/(te−tc)n \ge C/(t_e - t_c).
  2. and 3. Write ⌊n/k⌋=n/k−θn\lfloor n/k \rfloor = n/k - \theta_n with θn∈[0,1)\theta_n \in [0, 1). Then
K(n)−E(n)=C−θnCr⏟∈ (C−Cr,  C]+  n(tc+Crk−te).K(n) - E(n) = \underbrace{C - \theta_n C_r}_{\in\, (C - C_r,\; C]} + \;n\Big(t_c + \frac{C_r}{k} - t_e\Big).

The first term is bounded, so the sign of the coefficient of nn determines the limit.

∎

The condition in case 3 can be read as a frequency: compilation pays off in the long run only if recompilations occur less than once every Cr/(te−tc)C_r/(t_e - t_c) steps. With Cr=6C_r = 6 s and a saving of 40 ms per step, recompiling every 150 steps already cancels all gain.

InteractiveWhen does compilation pay off?

Long training with fixed shapes: all three modes eventually pay off, each after its own break-even point.

0 min5 min10 min15 min02 k4 k6 k8 k10 kstepscumulative timen* = 1500
  • eager
  • default
  • reduce-overhead
  • max-autotune
Scenario
100 ms
10 000
Mode to adjust
30 s
×1.25
never
0.50 (15 s)
Compiled step, tct_c80.0 ms
Break-even point1500 steps
Difference after 10 k steps (eager − compiled)2.8 min
Fraction of time compiling3.6 %
reduce-overhead break-even1575 steps
max-autotune break-even7200 steps
default catches eager at step 1500, which is ⌈C/(te−tc)⌉=⌈30 s/20.0 ms⌉\lceil C/(t_e - t_c) \rceil = \lceil 30\text{ s} / 20.0\text{ ms} \rceil. Each subsequent step saves 20.0 ms: 2.8 min less over 10 k steps.
Cumulative time versus steps for eager and three modes, each with initial cost CC and speedup. Choose a scenario and adjust the selected mode. In ‘prototype’, no mode recovers compilation; in ‘inference’, reduce-overhead amortizes three times earlier than default, and max-autotune, with long compilation, does not do so in the horizon. Enable recompilations and find the frequency at which the compiled curve separates from eager forever. Scenario values are illustrative: yours come from measurement.

Compilation time also has a part amortized across processes. Inductor saves generated code (FX graph cache), compiled Triton kernels and autotuning results to disk, so compiling the same graph again in another session costs a fraction of the first time. That is why a script’s second run seems to compile almost for free, and why an honest compilation benchmark says whether it measures cold or warm.

The next cell compiles the previous lesson’s MLP training step with each mode, measures the first, second and third calls, and steady state with interleaved rounds, and compares losses with eager from the same initialization:

[ ]Compile the training step: modes, cost and equivalenceLocal GPU
import copy, statistics, time
import torch
import torch.nn as nn
import torch._inductor.config as inductor_config
from torch.utils import benchmark

dev = "cuda"
D, CLASES, LOTE = 256, 10, 64
torch.manual_seed(0)
base = nn.Sequential(nn.Linear(D, 512), nn.GELU(), nn.LayerNorm(512),
                     nn.Linear(512, 512), nn.GELU(), nn.LayerNorm(512), nn.Linear(512, CLASES)).to(dev)
datos = [(torch.randn(LOTE, D, device=dev), torch.randint(0, CLASES, (LOTE,), device=dev)) for _ in range(8)]
perdida_fn = nn.CrossEntropyLoss()

def preparar(modo, compilar_opt):
    modelo = copy.deepcopy(base)                                    # misma inicialización en todas las variantes
    opt = torch.optim.AdamW(modelo.parameters(), lr=1e-3)
    red = modelo if modo is None else torch.compile(modelo, mode=modo)
    paso_opt = torch.compile(opt.step) if compilar_opt else opt.step
    def paso(x, y):
        perdida = perdida_fn(red(x), y)
        perdida.backward()
        paso_opt()
        opt.zero_grad(set_to_none=True)
        return perdida.detach()
    return paso

def llamada(paso, x, y):
    torch.cuda.synchronize()
    t0 = time.perf_counter()
    paso(x, y)
    torch.cuda.synchronize()
    return time.perf_counter() - t0

variantes = [("eager", None, False, True),
             ("default, caché fría", "default", False, False),
             ("default", "default", False, True),
             ("default + optimizador", "default", True, True),
             ("reduce-overhead + optimizador", "reduce-overhead", True, True),
             ("max-autotune + optimizador", "max-autotune", True, True)]
pasos, perdidas = {}, {}
for nombre, modo, copt, cache in variantes:
    torch._dynamo.reset()
    inductor_config.force_disable_caches = not cache            # la fría recompila todo desde cero
    paso = preparar(modo, copt)
    t_llamadas = [llamada(paso, *datos[i]) for i in range(3)]   # 1.ª: compila; reduce-overhead graba el grafo después
    perdidas[nombre] = torch.stack([paso(*datos[i % 8]) for i in range(3, 23)])
    pasos[nombre] = paso
    print(f"{nombre:30s} 1.ª llamada {t_llamadas[0]:6.2f} s | 2.ª {t_llamadas[1] * 1e3:5.1f} ms | 3.ª {t_llamadas[2] * 1e3:5.1f} ms")
inductor_config.force_disable_caches = False

# régimen estable: rondas intercaladas (A B C ... A B C ...) para que la deriva afecte a todas por igual
x0, y0 = datos[0]
rondas = {n: [] for n in pasos}
for _ in range(5):
    for nombre, paso in pasos.items():
        t = benchmark.Timer(stmt="paso(x, y)", globals={"paso": paso, "x": x0, "y": y0}).blocked_autorange(min_run_time=0.3)
        rondas[nombre].append(t.median)
t_eager = statistics.median(rondas["eager"])
print()
for nombre, ts in rondas.items():
    t = statistics.median(ts)
    dif = (perdidas[nombre] - perdidas["eager"]).abs().max().item()
    print(f"{nombre:30s} {t * 1e3:5.2f} ms/paso (rondas {min(ts) * 1e3:.2f} a {max(ts) * 1e3:.2f})  ×{t_eager / t:4.2f}  máx. |Δ pérdida| {dif:.1e}")
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

This cell is the lesson’s humility check, and its conclusions are robust although figures vary between runs:

  1. Cold compilation costs seconds; warm, tenths. The “cold cache” variant takes 3 to 5 s on its first call; the same compilation with disk cache, a few tenths.
  2. Compiling only the model barely changes this step, and sometimes slows it. With batch 64, the step is overhead-bound (as classified in the previous lesson), the model has little elementwise work to fuse and the optimizer, which launches its own kernels, remains eager.
  3. Variants that consistently win are those using CUDA Graphs, reduce-overhead and max-autotune with compiled optimizer, because they alone target the real regime: they eliminate launches. In the lesson preparation runs they gained between 10% and slightly more than twice, and more when CPU was busier with other processes. Their second call, tens of milliseconds, records the graph.
  4. max-autotune adds nothing of its own here: it matches reduce-overhead, because on this GPU it does not tune matmul and what it does tune (tiny pointwise and reduction kernels) is not the bottleneck. It only adds compilation seconds.
  5. Losses do not match bit for bit, but do within precision: differences of order 10−710^{-7} compiling the model and 10−510^{-5} also compiling AdamW, after 20 steps. Fusion reorders floating-point operations, and floating-point addition is not associative.

Debugging: logs, explain and comparison with eager

When something goes wrong with torch.compile, it is almost always one of four things: graph breaks, recompilations, a different numerical result or a compiler error. Each has its tool.

  • TORCH_LOGS enables logs by topic before launching Python (or, in a notebook, torch._logging.set_logs(...)): graph_breaks shows each break with its reason and line; recompiles each recompilation with the failed guard (the interactive’s “tensor 'x' size mismatch at index 0. expected 32, actual 17”); guards all guards of each version; output_code generated code. TORCH_LOGS="+dynamo" is the exhaustive version.
  • torch._dynamo.explain(f)(*args) captures without compiling and returns graph count, break count and reasons. It is the programmatic way to check whether a forward is captured whole, and the code exercise uses it.
  • fullgraph=True turns the first break into an error. Use it for code that must compile whole: a new break added months later then breaks a test instead of silently costing 30%.
  • Backend bisection. backend="eager" executes only Dynamo; "aot_eager", Dynamo and AOTAutograd; "inductor", everything. If a result is wrong with Inductor and right with aot_eager, the problem is in code generation; if already failing with eager, it is in capture. This is the same bisection logic you will use with git bisect.
  • torch.compiler.disable as a decorator excludes a function from compilation: useful for logging or debugging code you do not want to rewrite.
  • Compare with eager, always, with tolerances rather than exact equality: torch.testing.assert_close defaults to reasonable tolerances for each type, the same ideas as in tolerance-based assertions.
[ ]Find breaks and check the fixLocal GPU
import torch
import torch._dynamo as dynamo

dev = "cuda"
def paso_con_trampas(x, w):
    h = x @ w
    print("h:", h.shape)                        # depuración olvidada
    h = torch.relu(h)
    escala = h.abs().amax().item()              # un número de Python
    h = h / escala
    if h.mean() > 0.1:                          # rama que depende de los datos
        h = h * 2
    return torch.sigmoid(h).sum(-1)

def paso_limpio(x, w):
    h = torch.relu(x @ w)
    h = h / h.abs().amax()                      # el máximo se queda en la GPU, como tensor 0-d
    h = torch.where(h.mean() > 0.1, h * 2, h)   # las dos ramas se calculan; where elige
    return torch.sigmoid(h).sum(-1)

x, w = torch.randn(32, 64, device=dev), torch.randn(64, 64, device=dev) / 8
for f in [paso_con_trampas, paso_limpio]:
    dynamo.reset()
    info = dynamo.explain(f)(x, w)
    print(f"{f.__name__}: {info.graph_count} grafos, {info.graph_break_count} rupturas, {info.op_count} operaciones")
    for r in info.break_reasons:
        codigo = r.user_stack[-1].line.split("#")[0].strip()
        print(f"   {codigo:34s} → {str(r.reason).splitlines()[0][:70]}")

dynamo.reset()
torch.testing.assert_close(torch.compile(paso_limpio, fullgraph=True)(x, w), paso_con_trampas(x, w))
print("paso_limpio compila con fullgraph=True y coincide con la versión con trampas")
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

The clean version does a little more work (torch.where calculates h * 2 even when unused), and in exchange is a single graph: Inductor fuses division, condition, selection and sigmoid in the same kernel, and there is no synchronization with CPU. Calculating both branches and selecting with where is almost always cheaper than a break when branches are elementwise operations. With expensive or very different branches, torch.cond can capture a data-dependent if as a graph control-flow operation.

torch.compile on Windows

This course’s lab is a Windows laptop, and here torch.compile has its own status worth checking before designing an experiment around it.

  • On GPU, Inductor needs Triton. PyPI’s triton package does not publish Windows wheels; triton-windows exists, a port maintained separately from the main project (currently at github.com/triton-lang/triton-windows), installed with pip and declaring torch.compile support with NVIDIA GPUs and CUDA 12. Each triton-windows release targets a specific PyTorch version: check its notes before updating either.
  • On CPU, Inductor generates C++ and needs the MSVC compiler, cl.exe, on PATH: launch Python from an “x64 Native Tools Command Prompt” or after running vcvars64.bat, as prepared in C++ toolchain setup. The official guide documents it as a feature in development.
  • Alternatives: eager and aot_eager backends always work (they generate no code) and suffice for debugging capture; WSL2 provides the Linux environment in which PyTorch tests torch.compile daily.

The following cell checks all that on your machine:

[ ]Which backends work on this machine?Local GPU
import importlib.metadata as md, platform, shutil, sys, time
import torch
from torch._inductor.runtime.cache_dir_utils import cache_dir

print(platform.platform(), "| Python", sys.version.split()[0], "| torch", torch.__version__, "| CUDA", torch.version.cuda)
for paquete in ["triton", "triton-windows"]:
    try:
        print(f"  {paquete}: {md.version(paquete)}")
    except md.PackageNotFoundError:
        print(f"  {paquete}: no instalado")
print("  cl.exe (MSVC) en el PATH:", shutil.which("cl") or "no")
print("  caché de Inductor:", cache_dir(), "| ¿tiene espacios?", " " in cache_dir())
if torch.cuda.is_available():
    p = torch.cuda.get_device_properties(0)
    print(f"  GPU: {p.name}, {p.multi_processor_count} SMs (max-autotune ajusta las matmul desde 68)")

def probar(backend, dispositivo):
    torch._dynamo.reset()
    f = torch.compile(lambda x: torch.sin(x) * 2 + 1, backend=backend)
    x = torch.randn(1000, device=dispositivo)
    t0 = time.perf_counter()
    try:
        ok = torch.allclose(f(x), torch.sin(x) * 2 + 1)
        return f"funciona ({time.perf_counter() - t0:.1f} s la primera llamada; igual a eager: {ok})"
    except Exception as e:                       # InductorError, BackendCompilerFailed...
        return f"FALLA: {str(e).strip().splitlines()[0][:120]}"

for backend in ["eager", "aot_eager", "inductor"]:
    print(f"{backend:9s} en CPU:", probar(backend, "cpu"))
if torch.cuda.is_available():
    print(f"{'inductor':9s} en GPU:", probar("inductor", "cuda"))
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

In the lab, GPU works with triton-windows and CPU fails with “Compiler: cl is not found”. There is a second, subtler trap discovered while preparing this lesson: with cl.exe on PATH, CPU compilation still fails if the virtual environment or Inductor cache path contains a space, because the compile command generated by PyTorch 2.11 does not quote /I paths (for example, /I C:/Users/Nombre Apellido/...). The cache can be moved with TORCHINDUCTOR_CACHE_DIR, but torch header paths come from the virtual environment itself: an environment on a path without spaces, or WSL2, avoids this. That is why the cell’s cache line says whether it has spaces.

Common mistakes

Exercises

QuizWhich lines break the graph?
Each option is a line inside a function compiled with torch.compile (h is a tensor and x the input). Which cause a graph break in PyTorch 2.11 with default configuration?

More than one answer may be correct.

NumericWhen does it pay off?
Compiling a model costs 40 s and reduces a training step from 120 ms to 80 ms. Without recompilations, from how many steps is total compilation time less than or equal to eager?
NumericBytes in a four-operation chain
A chain of 4 elementwise operations, each with one input and one output of the same size, on tensors that do not fit in cache. How many times more bytes does eager (one kernel per operation) move than the fused version?
NumericThe dropout mask
The chain y=dropout⁡(GELU⁡(x⋅a+b))y = \operatorname{dropout}(\operatorname{GELU}(x \cdot a + b)) in BF16 (2 bytes per element) and training, where the eager dropout kernel also writes a 1-byte-per-element mask. How many bytes per element does eager move (four kernels: product, sum, GELU and dropout)?
NumericCounting compilations
A function f(x) = torch.relu(x) * 2, without an if, is compiled with default settings (dynamic=None) and called with tensors of shape (B, 16) for BB = 64, 64, 50, 64, 1, 37, in that order. How many compilations occur in total?
NumericMaximum recompilation frequency
With te=120t_e = 120 ms, tc=80t_c = 80 ms and recompilations costing Cr=6C_r = 6 s every kk steps, what threshold value of kk makes compiled average cost per step, tc+Cr/kt_c + C_r/k, equal eager? (For compilation to pay off in the long run, recompilations must be farther apart than that.)
QuizInference with small batches
You serve a classification model on GPU with batches of 4 examples and always identical shapes. The profiler shows kernels of a few microseconds with gaps between them and CPU busy launching them the whole time. Which torch.compile mode do you choose?
QuizDisappearing outputs
With modelo_c = torch.compile(modelo, mode='reduce-overhead') and under torch.no_grad(), you execute salidas = [modelo_c(x) for x in lotes] and then torch.cat(salidas). What happens?
QuizA loss that does not match
After compiling an FP32 model, first-step loss differs from eager by 2.4×10−72.4 \times 10^{-7} (with losses of order 2.3). What do you conclude?
QuizBefore the experiment
You will compare eager and compiled training on your Windows laptop, on CPU and GPU. What do you do first?
CodeRow clipping without graph breaks
recorta_filas(x, tope) scales each row of x so its Euclidean norm does not exceed tope and leaves rows already satisfying it unchanged. The starter version is correct, but loops over rows in Python with an if on the norm: Dynamo cannot capture it. Rewrite it to be captured in one graph, without loops or if on tensor values (hint: torch.where). Tests compare with the definition, test a zero row and check with torch._dynamo.explain that there is one graph and no breaks.
import torch

def recorta_filas(x, tope=1.0):
  """Escala cada fila de x para que su norma no pase de tope; las demás filas no cambian."""
  filas = []
  for fila in x:
      n = fila.norm()
      if n > tope:                      # depende de los datos: rompe el grafo
          fila = fila * (tope / n)
      filas.append(fila)
  return torch.stack(filas)
Shift+Enter to run
ProofWhy excessive recompilation never amortizes
Prove: With K(n)=C+n tc+⌊n/k⌋CrK(n) = C + n\,t_c + \lfloor n/k \rfloor C_r and E(n)=n teE(n) = n\,t_e, if tc+Cr/k>tet_c + C_r/k \gt t_e, then K(n)−E(n)→+∞K(n) - E(n) \to +\infty.
0
The constants are positive: C,Cr,tc,te>0C, C_r, t_c, t_e \gt 0 and k≥1k \ge 1 an integer.

Step 1 of 4. How do you handle the floor ⌊n/k⌋\lfloor n/k \rfloor?

Summary

Key idea
torch.compile changes operation-by-operation execution into graphs: Dynamo captures them from bytecode with guards deciding when to reuse them, AOTAutograd adds backward and Inductor generates fused kernels. Fusion brings memory traffic close to its minimum (each input read once, each output written once) and CUDA Graphs eliminate launches; everything else—breaks, recompilations and compile cost—determines whether that gain reaches your experiment.
  • Fusion: a chain of kk unary operations moves kk times fewer bytes fused, and fusion reaches the lower bound on compulsory traffic. Time satisfies max⁡(Kℓ,β/B)≤T≤Kℓ+β/B\max(K\ell, \beta/B) \le T \le K\ell + \beta/B: gain is the byte ratio for large tensors and launch ratio for small ones.
  • Dynamo: intercepts Python frames (PEP 523), traces symbolically and protects each graph with guards on shapes, types, devices, global objects and constants. What needs a tensor value in Python (print, .item(), data-dependent if, Boolean masks) or an unknown library breaks the graph; shapes and NumPy do not.
  • Recompilations: each failed guard recompiles. dynamic=None makes a dimension dynamic at the second distinct shape, sizes 0 and 1 are always specialized and the limit is 8 versions per function. Padding to fixed sizes or marking dynamic dimensions prevents recompilation storms.
  • Modes: default fuses, reduce-overhead adds CUDA Graphs (fixed shapes, overwritten outputs), max-autotune tunes kernels for much greater compilation time. Compilation pays off from n∗=C/(te−tc)n^* = C/(t_e - t_c) steps and never if tc+Cr/k>tet_c + C_r/k \gt t_e.
  • Method: measure steady state and compilation separately, cold and warm; find breaks with explain and TORCH_LOGS; require fullgraph=True where it matters; always compare with eager using tolerances; and on Windows check which backend works before designing the experiment.