liveBook · Manning

PyTorch Dynamo compiler

As explained in Deep Learning with PyTorch, Second Edition

A PyTorch runtime graph-capture tool that intercepts Python execution to trace and optimize computation graphs.

PyTorch Dynamo is a runtime graph-capture tool that intercepts Python bytecode, records model operations, and optimizes the resulting computation graph without requiring changes to the model code. It appeared with PyTorch 2.0 and supports a more dynamic workflow than earlier static tracing approaches. section 17.2.2

Given a function and example input, Dynamo traces a linear sequence of instructions into an FX graph. The graph acts as a container for operations and parameters that can later support compilation or export. section 17.2.2

Dynamo supports two closely related workflows:

  • torch.export uses Dynamo to capture a model ahead of time for an exported program and later deployment. section 17.2.2
  • torch.compile captures and optimizes execution while allowing the model to remain in eager-mode Python. section 17.3.1
  • When torch.compile encounters an unrecognizable control path, it can split the graph and fall back to regular Python instead of failing outright. section 17.3.1

Dynamic control flow

A model that chooses between two linear layers according to whether x.sum() is positive can be compiled with torch.compile and called like the original model. Direct torch.export of the same conditional raises an unsupported dynamic-control-flow error.

torch.onnx.export(
    model,
    dummy_input,
    onnx_model_path,
    dynamo=True,      #1
)

This short call shows Dynamo-enabled ONNX export: setting dynamo=True routes graph capture through the newer PyTorch compiler path. section 17.2.2

How Deep Learning with PyTorch, Second Edition covers it

How deep it goes
Explains bytecode interception, FX graph creation, and graph splitting, but defers detailed compiler internals.
Examples
Uses ONNX export, torch.export, an inspected exported graph, and a conditional model to demonstrate capture behavior.
What it assumes
Assumes a PyTorch function or model and suitable example inputs for tracing, while introducing graph capture from Python execution.
What you can do after
Apply it via torch.compile or torch.export to optimize, capture, inspect, or deploy a PyTorch model.
How it connects
Connects runtime graph capture with PyTorch eager mode, torch.compile, torch.export, FX graphs, ONNX export, and TorchScript.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Deep Learning with PyTorch, Second Edition. The section links point to the parts of the book it draws on.