Overview
torch.export provides APIs for exporting PyTorch models to a graph-based representation that can be deployed, optimized, and serialized. It produces a traced graph representing only the Tensor computation in an Ahead-of-Time (AOT) fashion.
The exported graph:
- Produces normalized operators in the functional ATen operator set
- Eliminates Python control flow and data structures
- Records shape constraints for soundness verification
Core Functions
torch.export.export()
torch.export.export()
Export a PyTorch model to an Returns:
ExportedProgram.The module to export.
Example positional inputs to the module.
Example keyword arguments to the module.
Specification of dynamic dimensions using the
Dim API.If True, enforces stricter rules during export.
Module paths whose call signatures should be preserved.
ExportedProgram - The exported program that can be serialized or optimized.torch.export.save()
torch.export.save()
torch.export.load()
torch.export.load()
Load an Returns:
ExportedProgram from a file.File path or file-like object to load from.
ExportedProgram - The loaded exported program.torch.export.unflatten()
torch.export.unflatten()
Unflatten an exported program back to a module-like structure.Returns:
The exported program to unflatten.
UnflattenedModule - Module with the original structure restored.Dynamic Shapes
Dim API
Use theDim API to specify dynamic dimensions in input tensors.
torch.export.Dim()
torch.export.Dim()
torch.export.dims()
torch.export.dims()
Create multiple named dynamic dimensions at once.
ExportedProgram
TheExportedProgram class represents an exported PyTorch model.
Methods
Call the exported program with new inputs.
The underlying FX graph module.
Signature describing inputs, outputs, and state.
Preserved module call hierarchy.
Constraints
Use constraints to specify relationships between dynamic dimensions.Common Patterns
Export with Multiple Inputs
Export with State Dict
Deployment Workflow
Best Practices
Use Representative Inputs
Use Representative Inputs
Provide example inputs that represent the full range of shapes and values your model will encounter in production.
Specify Dynamic Dimensions
Specify Dynamic Dimensions
For inputs with variable shapes, always specify dynamic dimensions using the
Dim API to avoid re-exporting for different sizes.Test Exported Programs
Test Exported Programs
Validate that the exported program produces the same outputs as the original model with various inputs.
Handle Control Flow
Handle Control Flow
torch.export may not support all Python control flow. Use torch.cond for conditionals in exported code.Related APIs
torch.jit
TorchScript JIT compilation (alternative export approach)
torch.compile
Just-in-time compilation for performance
ONNX Export
Export to ONNX format for broader deployment
Quantization
Optimize exported models with quantization