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.
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.
- 1. ONNX stores a model as…
- 2. Why quantize a model?
- 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.
- 1. Why call model.eval() before export?
- 2. dynamic_axes={'input': {0: 'batch'}} means…
- 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 liketorch.wherekeeps both.) - Python values become constants. Shapes read with
.shapeand 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, …).
- 1. A model with 'if x.sum() > 0' is exported by tracing with a positive example. For negative inputs the ONNX model…
- 2. MatMul followed by Add of a bias can be fused into…
- 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.
- 1. Static int8 quantization needs…
- 2. Per-channel weight quantization helps when…
- 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).
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.
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
- ONNX specification and operators (onnx.ai; github.com/onnx/onnx), and ONNX Runtime documentation (onnxruntime.ai): graph optimizations, quantization.
- PyTorch documentation (pytorch.org/docs): torch.onnx, torch.export.
- B. Jacob et al. (2018). “Quantization and training of neural networks for efficient integer-arithmetic-only inference.” CVPR.
- M. Nagel, M. van Baalen, T. Blankevoort, M. Welling (2019). “Data-free quantization through weight equalization and bias correction.” ICCV.
- R. Krishnamoorthi (2018). “Quantizing deep convolutional networks for efficient inference: a whitepaper.” arXiv:1806.08342.