Sub topic 3
Exporting a PyTorch Vision Model to ONNX
This chapter assumes basic Python and NumPy, familiarity with PyTorch, and a basic understanding of image classification models. You should also know a model's expected input shape and preprocessing steps.
Why export to ONNX?
ONNX, or Open Neural Network Exchange, is a portable format for representing a machine-learning model as a computation graph. The graph contains operators, such as convolutions and matrix multiplications, plus the learned weights.
Exporting a PyTorch model to ONNX separates model definition from the framework used to run it. ONNX Runtime, TensorRT, and other inference systems can load the resulting file. This makes the ONNX file a useful interchange point for deployment.
An export does not automatically guarantee correct inference. The exported graph must support the model's operators, input shapes, and data types.
Prepare the model for export
Use evaluation mode before exporting. Evaluation mode changes layers such as dropout and batch normalization to inference behavior. Also create an example input, called a dummy input. PyTorch traces or analyzes the model using this input to determine its computation graph.
import torch
import torchvision
model = torchvision.models.resnet50(
weights=torchvision.models.ResNet50_Weights.DEFAULT
).eval()
dummy = torch.randn(1, 3, 224, 224)
torch.onnx.export(
model,
dummy,
"resnet50.onnx",
input_names=["input"],
output_names=["logits"],
dynamic_axes={
"input": {0: "batch"},
"logits": {0: "batch"},
},
opset_version=17,
)The dummy input has the shape (batch, channels, height, width). ResNet-50 expects three color channels and 224-by-224 pixels.
input_names and output_names make the graph easier to use from an inference runtime. dynamic_axes marks the batch dimension as dynamic. The exported file can therefore accept batch sizes other than one, while the channel and spatial dimensions remain fixed.
The opset_version selects a version of the ONNX operator specification. A newer opset can represent more operations, but your runtime and accelerator must support it. Pin the opset in deployment code so that exports remain reproducible.
Understand common export failures
An export can fail when the model uses a PyTorch operation without an ONNX equivalent. Data-dependent Python control flow can also produce an incomplete or incorrect graph. Test the export with representative inputs, including the batch sizes and image dimensions that production will use.
The output file contains graph structure and weights, but it does not automatically contain class names or a description of preprocessing. Store that metadata separately.
Exercise
Why does the example mark only dimension 0 as dynamic?
Show answer
Dimension 0 represents the batch size, which can vary between requests. The model still expects three channels and 224-by-224 images.