Sub topic 3
Exporting a PyTorch vision model to ONNX
This chapter assumes you can write basic Python and NumPy, you have trained or loaded a PyTorch vision model, and you know what an image classifier takes as input and returns as output. The export step runs on CPU, so you don't need a GPU for it.
By the end you will be able to export a model with a dynamic batch dimension, check the exported file, and recognize the usual export errors.
What the export does
torch.onnx.export runs your model once with an example input and records the operations that execute. It writes them to an ONNX file as a graph of operators, together with the trained weights. This is called tracing. The file no longer depends on your Python code, so ONNX Runtime or TensorRT can load it without PyTorch.
Tracing records what happened on one specific run. Two consequences follow:
- Python
ifstatements and loops are recorded only for the path the example input took. Data-dependent control flow gets frozen into the graph. - The shapes of the example input are baked in unless you declare them dynamic.
Standard classification backbones such as ResNet have no data-dependent branching, so tracing handles them well.
Export a ResNet-50
The script below loads a pretrained ResNet-50, switches it to evaluation mode, and exports it with a dynamic batch dimension.
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,
)Each argument matters:
| Argument | Purpose |
|---|---|
| `model` | The `nn.Module` to trace. |
| `dummy` | An example input. Its shape is `(batch, channels, height, width)`, here 1×3×224×224. Its values do not matter, but its shape and dtype do. |
| `"resnet50.onnx"` | Output path. |
| `input_names`, `output_names` | Names you will use later to feed and read tensors. Without them PyTorch invents names such as `input.1`. |
| `dynamic_axes` | Marks dimension 0 of the input and output as variable, labeled `batch`. |
| `opset_version` | The version of the ONNX operator set to target. |
Why `.eval()` matters
Some layers behave differently in training and inference. Batch normalization uses running statistics at inference, and dropout does nothing. If you export without calling .eval(), the exported graph can contain training behavior, and its outputs will differ from what you expect. This mistake is common and the export still succeeds, so you only find it in a parity check.
Why the batch dimension is dynamic
Without dynamic_axes, the file accepts only batch size 1. Feeding a batch of 8 later fails with a shape error. Declaring axis 0 dynamic lets one file serve single-image requests and batched requests.
Only axis 0 is dynamic here. Height and width stay fixed at 224, which matches how this model was trained. Making spatial dimensions dynamic is possible for fully convolutional models such as many detectors, but it affects optimization later. TensorRT, for example, needs shape ranges for every dynamic dimension.
Choosing an opset
The opset version defines which operators and semantics the file may use. A higher opset exposes newer operators, but your runtime must support it. Opset 17 is widely supported by recent ONNX Runtime releases. If you target an older runtime, you may need a lower value. If the exporter reports an unsupported operator, a newer opset often fixes it.
Verify the exported file
Check the file before you use it. The onnx package can validate the structure and show the input and output signatures.
import onnx
m = onnx.load("resnet50.onnx")
onnx.checker.check_model(m)
for tensor in list(m.graph.input) + list(m.graph.output):
dims = [d.dim_param or d.dim_value for d in tensor.type.tensor_type.shape.dim]
print(tensor.name, dims)Expected output:
input ['batch', 3, 224, 224]
logits ['batch', 1000]The string batch in the first position confirms the dynamic axis worked. A literal 1 there means dynamic_axes was not applied, often because the names in the dictionary did not match input_names and output_names.
Check dynamic batching works
Load the file and send two different batch sizes. If both succeed, the dynamic axis is working.
import numpy as np
import onnxruntime as ort
sess = ort.InferenceSession("resnet50.onnx", providers=["CPUExecutionProvider"])
for n in (1, 4):
x = np.random.rand(n, 3, 224, 224).astype(np.float32)
out = sess.run(None, {"input": x})[0]
print(n, out.shape)You should see (1, 1000) and (4, 1000).
Common errors and how to read them
- Shape error at run time, such as "Got invalid dimensions for input". The input shape does not match the graph. Either
dynamic_axeswas missing, or you are feeding spatial dimensions different from the exported ones. - Wrong dtype. ONNX Runtime does not convert types for you. NumPy creates
float64arrays by default, but the model expectsfloat32. Use.astype(np.float32). - Unsupported operator during export. The exporter has no mapping for a PyTorch operation at your chosen opset. Raise
opset_version, or rewrite that part of the model with supported operations. - Outputs differ from PyTorch. Look first for a missing
.eval(). Then look at preprocessing differences, which the next chapters cover. - Large model, large file. Models over 2 GB cannot be stored as a single protobuf file. The exporter then stores weights in external data files next to the
.onnxfile. Keep them together when you copy the model.
Practical habits
- Export from a model you have already put in
.eval()and moved to the same device as your dummy input. - Name inputs and outputs explicitly so that code and deployment configuration stay stable.
- Keep the export script in version control. Record the PyTorch, torchvision, and opset versions with the file.
- Check the exported shapes and run two batch sizes, as above, immediately after every export.
- Do not edit the ONNX file by hand unless you have to. Re-export from the source instead.
Exercise
You export a model without passing dynamic_axes, then call sess.run with a batch of 8 and get a shape error. What caused this, and what is the fix?
Show answer
Without dynamic_axes, the batch dimension is fixed at the dummy input's size, which was 1. Re-export with dynamic_axes={"input": {0: "batch"}, "logits": {0: "batch"}}, making sure the keys match input_names and output_names. Then confirm with onnx.load that the first input dimension is batch.
Exercise
The exported file passes onnx.checker.check_model, yet its outputs differ noticeably from PyTorch. Name the most likely cause and the check that would catch it.
Show answer
The most likely cause is exporting the model without .eval(), so batch normalization and dropout were traced in training mode. check_model only validates the file structure. A numerical parity check that runs the same input through PyTorch and ONNX Runtime and compares the outputs within a tolerance would catch it.