Foundations to Frontier
Tests
C. Programming, Tools and HPC › C3 Deep Learning Frameworks

ONNX and Model Export

A trained model is useful only where it can run: a server without Python, a phone, a GPU inference engine, a robot's onboard computer. ONNX (Open Neural Network Exchange) is a framework-neutral file format describing a model as a graph of standard operators with its weights, so a network trained in PyTorch, TensorFlow or JAX can be executed by ONNX Runtime, TensorRT, OpenVINO and others. This topic covers the ONNX graph (nodes, initializers, opsets, dynamic axes), exporting by tracing and its pitfalls, validation by parity testing, runtime graph optimizations (constant folding, operator fusion, batch-norm folding), and post-training quantization to int8. In the exercises you build a mini-ONNX in NumPy (exporter, checker, runtime, optimization passes, parity tests, the traced-branch pitfall), then study int8 quantization: per-tensor versus per-channel scales, cross-layer equalization and calibration outliers.

Level 0: Foundation

★☆☆☆☆ Introductory⏱ 5 minGeneral audience. No mathematics required.

Writing the recipe down in a universal language

A model trained in one framework is like a recipe written in a private shorthand: it works in the kitchen where it was invented. To cook it anywhere, you rewrite it in a standard form that any kitchen understands: the list of steps (multiply, add, clip at zero…) and the exact quantities (the weights). That standard form for neural networks is ONNX. Once a model is in it, specialized engines can run it fast on servers, phones or a robot’s computer. To fit small devices, the quantities can also be stored with fewer digits, which is quantization.

Quantizing weights for export: one scale per tensor or per channel?
ch 017.3 dBch 120.9 dBch 245.6 dBch 320.0 dBch 418.4 dBch 519.3 dBch 618.1 dBch 719.4 dB
overall SQNR 36.1 dB
weights rounded to 0: 19 of 192
size: 8 bits vs 32 (4.0× smaller)
In each row the upper dots are the float weights and the lower dots their quantized values (orange when crushed to zero). With a per-tensor scale all rows share one axis, so narrow channels huddle in the middle; with per-channel scales each row is drawn on its own range. The SQNR at the right is the signal-to-quantization-noise ratio of that channel (about 6 dB per bit at best). With a per-tensor scale, raising channel 2's range coarsens every channel's grid; per-channel scales (standard for convolution weights in TensorRT and TFLite, and the per_channel=True option of ONNX Runtime's quantizer) keep each channel's resolution. Activations usually get one scale per tensor, calibrated on representative data.
Why engineers care

Flight and robot software rarely runs Python. A perception or anomaly-detection network has to become a self-contained artifact that a C or C++ runtime can load, whose numerical behaviour is verified against the training framework, and that fits the memory and power budget of the target processor. Export, parity testing and quantization are that path.

📝 Quick check (Level 0)
0/3 answered
  1. 1. ONNX stores a model as…
  2. 2. Why quantize a model?
  3. 3. In the demo, what happens to small weights when one channel has a huge range and the scale is shared?

Level 1: Beginner

★★☆☆☆ Basic⏱ 20 minSecondary-school mathematics: arithmetic and elementary algebra.

Exporting from PyTorch

import torch, onnx, onnxruntime as ort, numpy as np

model.eval()                                            # export inference behaviour (dropout off, BN frozen)
x = torch.randn(1, 4)
torch.onnx.export(model, (x,), "model.onnx", input_names=["input"], output_names=["output"],
                  dynamic_axes={"input": {0: "batch"}, "output": {0: "batch"}}, opset_version=17)

onnx.checker.check_model(onnx.load("model.onnx"))       # structural validity
sess = ort.InferenceSession("model.onnx", providers=["CPUExecutionProvider"])
xs = np.random.randn(64, 4).astype(np.float32)
np.testing.assert_allclose(sess.run(None, {"input": xs})[0],
                           model(torch.from_numpy(xs)).detach().numpy(), rtol=1e-4, atol=1e-5)

An ONNX file is a protobuf ModelProto: a GraphProto with nodes (op_type, input and output names, attributes), initializers (the weights), typed inputs and outputs with shapes (symbolic dimensions such as batch for dynamic axes), and an opset version that fixes the semantics of each operator. Newer PyTorch versions also offer torch.onnx.export(..., dynamo=True), based on torch.export.

📝 Quick check (Level 1)
0/3 answered
  1. 1. Why call model.eval() before export?
  2. 2. dynamic_axes={'input': {0: 'batch'}} means…
  3. 3. The opset version determines…

Level 2: Intermediate

★★★☆☆ Intermediate⏱ 35 minUndergraduate students and practising engineers.

How export works and how it fails

The classic exporter traces: it runs the model on the example input and records the operations that executed. Consequences:

  • Data-dependent control flow is baked in. if x.mean() > 0: records only the branch taken for the example. (Scripting, torch.cond, or rewriting the branch as tensor operations like torch.where keeps both.)
  • Python values become constants. Shapes read with .shape and turned into Python ints may be frozen unless dynamic axes are declared.
  • Unsupported operators need a newer opset, a decomposition, or a custom operator.
  • Numerics differ slightly between runtimes (operator order, fused kernels, fp16). Compare with tolerances over many varied inputs, not one.

Runtime optimizations

ONNX Runtime rewrites the graph before running it: constant folding (precompute subgraphs whose inputs are all constants), redundant-node elimination (Identity, duplicate casts), operator fusion (MatMul + Add → Gemm, Conv + BatchNorm folded into one Conv, GELU and LayerNorm patterns, attention), and layout changes, then dispatches nodes to execution providers (CPU, CUDA, TensorRT, OpenVINO, CoreML, …).

🐍 Exercise 1: a mini-ONNX
Define Node and Graph (nodes, inputs, outputs, initializers, opset); a checker (defined-before-use, single assignment, produced outputs, supported ops); a reference runtime; an exporter that traces a Python model with symbolic values; optimization passes (constant folding, MatMul+Add → Gemm fusion, Identity elimination, dead-code removal); and parity tests. Show that a data-dependent branch is baked in by tracing and caught by parity testing.
📝 Quick check (Level 2)
0/3 answered
  1. 1. A model with 'if x.sum() > 0' is exported by tracing with a positive example. For negative inputs the ONNX model…
  2. 2. MatMul followed by Add of a bias can be fused into…
  3. 3. Why test parity on many inputs?

Level 3: Advanced

★★★★☆ Advanced⏱ 30 minGraduate level, with full derivations and proofs.

Quantization

Store weights (and often activations) as 8-bit integers with a scale (and zero-point): w ≈ s·q with q an integer from −127 to 127. Memory shrinks about 4× and integer kernels are faster and cheaper in energy.

  • Dynamic quantization: weights int8 offline, activation scales computed on the fly. Easy; good for MatMul-heavy models (LSTMs, transformers on CPU).
  • Static quantization: activation scales fixed from a calibration set (min-max, percentile, entropy/KL); represented in ONNX as QuantizeLinear/DequantizeLinear (QDQ) pairs around operators.
  • Granularity: per-tensor scales are simplest; per-channel scales (one per output channel) handle channels with very different ranges.
  • Cross-layer equalization: for ReLU networks, scaling a hidden channel by s in one layer and 1/s in the next leaves the function unchanged; choosing s to balance the ranges makes per-tensor quantization work.
  • Quantization-aware training simulates rounding during training (with a straight-through estimator, C3.2) when post-training quantization loses too much.

Other export paths

TorchScript (legacy), torch.export and ExecuTorch (mobile and embedded), TensorRT engines (NVIDIA, with fp16 and int8), TFLite / LiteRT (C3.6), Core ML, OpenVINO; jax2tf or jax2onnx for JAX models. Choose by target hardware and its supported operators.

📝 Quick check (Level 3)
0/3 answered
  1. 1. Static int8 quantization needs…
  2. 2. Per-channel weight quantization helps when…
  3. 3. Cross-layer equalization relies on ReLU being…

Level 4: Expert

★★★★★ Expert⏱ 35 minResearchers: original papers and open problems.

Export and quantization, measured

Exercise 1. Tracing a 4-16-16-2 ReLU MLP gives 3 MatMul, 3 Add, 2 Relu, 1 Mul and 1 Identity nodes. Optimization fuses them to 3 Gemm, 2 Relu, 1 Mul and 1 Identity, and both graphs match the Python model exactly on 20 random batches. Constant folding turns Add(2, 3) into an initializer. The checker rejects an undefined input. A model with relu if mean > 0 else tanh, traced on a positive example, contains no Tanh node: it passes parity on positive inputs and fails on negative ones.

Exercise 2: int8 post-training quantization. A 1-32-32-1 ReLU network fitted with Adam to sin(3x) + 0.3x² (fit RMSE 0.0107) is quantized (symmetric int8 weights, float biases). RMSE of the quantized output against the float model, as computed in the browser:

Weights per-tensor per-channel
original network 0.0219 0.0091
same function, one hidden channel rescaled 30× 0.0650 0.0374
after cross-layer equalization 0.0205 0.0128

Rescaling channel 3 of layer 1 by 30 and the matching row of layer 2 by 1/30 changes the function by 7e−17 but triples the per-tensor error. Per-output-channel scales fix the wide column in layer 1 but not the shrunken input row of layer 2 (its scale is shared with other rows), so they recover only part of the loss. Equalization restores the per-tensor error fully and most of the per-channel one.

Activations (uint8, per-tensor, with per-channel weights): calibrating with min-max on 500 samples plus one corrupted sample at x = 40 gives RMSE 0.183; the 99.9th-percentile range gives 0.0137, as good as min-max on clean data (0.0157). The quantized model is 3.4× smaller (biases kept in 32 bits).

Your numbers may differ in the last digits

3000 Adam steps amplify last-bit rounding differences between NumPy builds (the browser’s Pyodide NumPy versus a desktop one with a different BLAS), so the trained weights and the RMSE values differ slightly from platform to platform: on a desktop CPython the table reads 0.0281/0.0200, 0.0775/0.0437 and 0.0349/0.0228. The comparisons, which the tests check, hold on both. This is the reproducibility issue of C2.4 in miniature.

🐍 Exercise 2 (research): int8 quantization, scales and calibration
Train a small ReLU network, create an equivalent network with one channel rescaled 30×, quantize weights to int8 with per-tensor and per-channel symmetric scales, apply cross-layer equalization, and compare output RMSE against the float model; then quantize activations with min-max and percentile calibration on data containing one outlier, and compute the size reduction.

Model export in AI, robotics and aerospace

  • Onboard perception: detection and terrain-relative navigation networks exported to ONNX and compiled with TensorRT for embedded GPUs (Jetson-class) on drones and rovers.
  • Space-qualified processors and FPGAs: int8 networks for onboard image triage, so that only useful images are downlinked; toolchains import ONNX.
  • ROS 2 nodes that load ONNX Runtime in C++ for real-time inference.
  • Verification: the exported artifact, not the training script, is what is tested and certified; parity suites and versioned opsets make it reproducible.

References

  1. ONNX specification and operators (onnx.ai; github.com/onnx/onnx), and ONNX Runtime documentation (onnxruntime.ai): graph optimizations, quantization.
  2. PyTorch documentation (pytorch.org/docs): torch.onnx, torch.export.
  3. B. Jacob et al. (2018). “Quantization and training of neural networks for efficient integer-arithmetic-only inference.” CVPR.
  4. M. Nagel, M. van Baalen, T. Blankevoort, M. Welling (2019). “Data-free quantization through weight equalization and bias correction.” ICCV.
  5. R. Krishnamoorthi (2018). “Quantizing deep convolutional networks for efficient inference: a whitepaper.” arXiv:1806.08342.