Example

Record a failed compilation instead of hiding it

Ask PyTorch to compile a small MLP, capture the compiler failure, and keep the eager path runnable and honest.

Compilation is an optimisation with a precondition: a compiler and a supported graph. When it works, it can remove Python overhead and fuse operations. When it fails, the service must either fall back or refuse the request; it must not report a compiled path that never ran.

This example asks torch.compile to compile a two-layer MLP. On this machine the Inductor backend failed because the C compiler cl was not found. The result object records available: false and the error, while the eager timings remain valid. That is a successful experiment about a failed optimisation. The page does not quote a compile speedup, because no compiled invocation completed.

Run it

From the canonical repository at commit f958967d70992d7b09d9c75000bd8c543f1644d4:

python examples/ch18/compile.py --dim 128 --batch 4 --json

Python 3.11 or later with PyTorch. CPU-only, seeded, no model download, network, GPU or credentials. The first run may take several seconds while Dynamo and Inductor try to compile; on this machine it returns a recorded failure.

Implementation

run_eager warms up once and times five calls. run_compiled wraps the model, times the first call as cold_seconds, then times five more. Both the compile call and the first invocation are wrapped, so an unsupported backend becomes a result field rather than a crash.

def run_compiled(x: torch.Tensor, model: nn.Module, iterations: int = 5) -> CompileResult:
    try:
        compiled = torch.compile(model)
    except Exception as exc:
        return CompileResult(mode="compiled", cold_seconds=0.0, warm_seconds=[], metadata={"available": False, "error": str(exc)})
    try:
        start = time.perf_counter()
        with torch.no_grad():
            _ = compiled(x)
        cold = time.perf_counter() - start
    except Exception as exc:
        return CompileResult(mode="compiled", cold_seconds=0.0, warm_seconds=[], metadata={"available": False, "error": str(exc)})
    times = []
    for _ in range(iterations):
        start = time.perf_counter()
        with torch.no_grad():
            _ = compiled(x)
        times.append(time.perf_counter() - start)
    return CompileResult(mode="compiled", cold_seconds=cold, warm_seconds=times, metadata={"available": True, "iterations": iterations})


def run(dim: int = 64, batch: int = 32, iterations: int = 5) -> dict:
    torch.manual_seed(0)
    model = SmallMLP(dim=dim)
    model.eval()
    x = torch.randn(batch, dim)
    eager = run_eager(x, model, iterations=iterations)
    compiled = run_compiled(x, model, iterations=iterations)
    return {"eager": eager.to_dict(), "compiled": compiled.to_dict()}

Expected outcome

Observed with the command above (exit 0). Selected stable fields:

  "compiled": {
    "mode": "compiled",
    "cold_seconds": 0.0,
    "warm_seconds": [],
    "metadata": {
      "available": false,

The metadata also carried the Inductor error, whose first line was RuntimeError: Compiler: cl is not found. The eager path ran and produced five warm timings; they are omitted because they vary. No compiled invocation completed, so there is no compiled warm time to compare.

Mechanism and limitations

Documented: run_eager warms up and times five calls. run_compiled catches both a failure from torch.compile and a failure from the first compiled call, returning available: false with the error. The tests check that both modes are present, that the eager warm list has the requested length, that a compiled warm list has the same length only when available, and that the result serialises.

Observed: the command exited 0 with available: false and the compiler error above. The targeted tests.test_ch18_compile is part of the canonical suite; no independent test count is claimed here.

Not shown: a successful compilation, a speedup, CUDA graphs, Inductor fusion, shape guards, or the cost of recompilation on a new shape. The failure is specific to this Windows environment and missing cl; it is not a claim that torch.compile cannot work elsewhere. A compile failure also does not prove the eager path is optimal.

Challenge this result

Run the command in an environment with a working C compiler for PyTorch Inductor. Before running, predict which field changes and whether cold_seconds should include compilation. Then run a second shape, such as --dim 256, and check whether the compiled path is reused or recompiled. Explain why a service must record the backend, the compiler version and the shape when it reports a compiled latency, and why a fallback is not the same as a successful compile.

Source and verification

Canonical source: examples/ch18/compile.py at commit f958967d70992d7b09d9c75000bd8c543f1644d4. Tests: tests/test_ch18_compile.py . Chapter: Compilation and Execution Graphs . The run above is a fresh local execution on Windows 11 with Python 3.13.15 and PyTorch 2.6.0+cu124; compilation failed and no speedup is claimed.

Understand this example

Copy this prompt into your AI tool. No code runs here.

Apply this example

Copy this prompt into your AI tool. No code runs here.