Sub topic 2
The ONNX format and why it is the common interchange point
This chapter assumes you can train or load a PyTorch vision model, you know what a tensor and a layer are, and you have run a Python script that uses NumPy. You do not need a GPU yet. Later chapters export a model and run it, and this one explains what the exported file is.
What ONNX is
ONNX (Open Neural Network Exchange) is a file format and a specification for describing a neural network as a graph of operators. A .onnx file holds the structure of the computation, the trained weights, and the declared input and output tensors. It does not hold Python code, and it does not depend on the framework that produced it.
The file is a Protocol Buffers message. Protocol Buffers is a binary serialization format with a schema, so any tool with the ONNX schema can read the file. The same file can be loaded from Python, C++, C#, Java, or a browser runtime.
Why an interchange point matters
Without a shared format, every training framework would need a separate path to every inference engine. With N frameworks and M engines, that is N × M integrations. With ONNX in the middle, each framework writes one exporter and each engine reads one format, so you need N + M.
For this tutorial the path is PyTorch to ONNX, then ONNX to ONNX Runtime, then optionally ONNX to TensorRT. ONNX Runtime reads the file directly. TensorRT can read it either through ONNX Runtime's TensorRT execution provider or through its own ONNX parser, which trtexec uses.
There is a practical benefit beyond tooling. The inference side no longer needs your training code, your custom Python classes, or your PyTorch version. You ship one file and a runtime.
What is inside the file
An ONNX model has a small number of parts. Knowing them helps you read error messages.
| Part | What it holds |
|---|---|
| `ModelProto` | The top-level message: IR version, opset imports, producer name, and the graph |
| `GraphProto` | Nodes, inputs, outputs, initializers, and value info |
| `NodeProto` | One operator call, such as `Conv` or `Relu`, with input and output names and attributes |
| Initializers | The weights and constants, stored as tensors |
| `ValueInfoProto` | The name, element type, and shape of a graph input or output |
| Opset import | The version of the operator set that the graph uses |
The graph is a directed acyclic graph. Each node reads named tensors and produces named tensors. Execution order follows from the data dependencies. The nodes are stored in topological order, so every tensor is produced before it is used.
You can inspect a model with the onnx Python package. Install it with pip install onnx.
import onnx
model = onnx.load("resnet50.onnx")
onnx.checker.check_model(model)
print("IR version:", model.ir_version)
print("Opset:", [(o.domain or "ai.onnx", o.version) for o in model.opset_import])
graph = model.graph
for inp in graph.input:
dims = [d.dim_param or d.dim_value for d in inp.type.tensor_type.shape.dim]
print("input:", inp.name, dims)
for out in graph.output:
dims = [d.dim_param or d.dim_value for d in out.type.tensor_type.shape.dim]
print("output:", out.name, dims)
print("nodes:", len(graph.node))
print("first nodes:", [n.op_type for n in graph.node[:5]])This script reads the file produced in the next chapter, so run it after the export. For a ResNet-50 exported with a dynamic batch axis, the input dimensions print as ['batch', 3, 224, 224]. A named dimension such as batch is stored in dim_param. A fixed size such as 224 is stored in dim_value. The code prints whichever one is set.
onnx.checker.check_model validates the structure and the schema of each operator. It raises an exception if the file is malformed. It does not prove that the model gives the right answers. That is a separate check covered later in the tutorial.
Operators and opsets
An operator is a named computation with a defined meaning, such as Conv, MatMul, Softmax, or Resize. The ONNX specification defines what each operator takes as inputs and attributes, and what it returns.
Operators change over time. A new version may add an attribute, change an input from an attribute to a tensor, or support more data types. To keep old files valid, ONNX groups operator definitions into numbered opsets. A model declares which opset it uses, and a runtime interprets each node by the rules of that version.
This has three consequences you will meet in practice:
- Export opset must be supported by the runtime. If you export with opset 17 and your ONNX Runtime build supports only up to 15, loading fails. Newer runtimes read older opsets, but the reverse is not true.
- Some features need a minimum opset. For example, certain resize modes or newer normalization operators are only expressible in later opsets. The exporter can fall back to a longer sequence of simple operators when the opset is too low, which still works but is slower or harder to fuse.
- A pinned opset makes the file reproducible. The tutorial's export uses
opset_version=17explicitly instead of relying on the exporter's default, which changes between PyTorch releases.
Beyond the standard domain ai.onnx, a model can use other domains. ONNX Runtime defines com.microsoft operators for fused kernels, and you can register custom operators. A model that uses a custom domain is no longer portable, since only runtimes that implement that domain can run it. Keep this in mind if a model loads in one engine and fails in another.
Static and dynamic shapes in the graph
Each input and output carries a shape. Each dimension is one of three things:
- A fixed integer, such as 3 channels or 224 pixels.
- A named symbolic dimension, such as
batch, which can take any value at run time and is the same wherever the name appears. - An unknown dimension with no name.
Shape declarations matter for performance as well as correctness. A runtime can plan memory and choose kernels more aggressively when sizes are known ahead of time. Fully static shapes give the best optimization. Dynamic dimensions give flexibility. The next chapter exports with a dynamic batch axis only, and keeps height and width fixed at 224. That compromise is common for classifiers, since the batch size varies with traffic while the image size is set by the model.
Weights and file size
Initializers hold the weights. For ResNet-50 in FP32, this is about 25.6 million parameters at 4 bytes each, roughly 100 MB. Protocol Buffers limits a single message to 2 GB. Larger models store tensors in an external data file next to the .onnx file. If you move a model that uses external data, you must move both files, and the relative path inside the model must stay valid. Vision classifiers and detectors rarely reach this limit, but large transformer backbones can.
What ONNX does not do
ONNX describes a computation. It does not make that computation fast on its own. Speed comes from the runtime that executes the graph. The same file runs on ONNX Runtime's CPU kernels, its CUDA kernels, or TensorRT, with very different latency. The following chapters cover those choices.
ONNX also does not capture everything in your PyTorch pipeline:
- Only the traced computation is saved. The exporter records what happens to the tensors during the forward pass. Python control flow that depends on tensor values may be frozen to the branch taken during export.
- Preprocessing is usually outside the file. Resizing, cropping, and normalization typically run in your own code. If the training pipeline and the inference pipeline differ, accuracy drops while the model file stays correct.
- Training behavior is gone. Dropout and batch normalization must be in evaluation mode at export time. Otherwise the file may record the training behavior.
Common errors
- Unsupported operator at export. The exporter has no mapping for a PyTorch operation at the chosen opset. Raise the opset or rewrite that part of the model with supported operations.
- Loading fails with an opset or IR version message. The runtime is older than the exporter. Upgrade the runtime or export with a lower opset.
- Input name mismatch at run time.
sess.runneeds the exact input names from the graph. Print them from the file instead of guessing. - Shape or type mismatch at run time. An FP64 NumPy array, which is NumPy's default float type, fed to an FP32 input raises an error. Cast with
.astype(np.float32). - Model moved without its external data. The load fails because the weight file cannot be found.
Exercise
A teammate exports a model with a fixed input shape of 1x3x224x224, then asks why the service cannot batch 16 requests together. What is wrong, and what would you change in the export?
Show answer
The graph records the batch dimension as the fixed integer 1, so the runtime rejects other batch sizes. Re-export with a dynamic axis for the batch dimension, for example dynamic_axes={"input": {0: "batch"}, "logits": {0: "batch"}}. Then the input dimension is stored as the named symbol batch, and a batch of 16 is accepted.
Exercise
You inspect a model and find that onnx.checker.check_model passes. Does that show the ONNX model gives the same predictions as the PyTorch model? Why or why not?
Show answer
No. The checker only validates that the file is structurally valid and that each operator follows the ONNX schema. It does not run the model. To confirm the predictions match, run both models on the same input and compare the outputs within a tolerance, as done in the parity check chapter.