Whats ONNX
(Open Neural Network Exchange) is open source format (2017) created by Microsoft and Facebook for machine learning models, allows interoperability between different frameworks and enables optimized inference using hardware accelerators. Its used when deploying models for production, running models on different hardware. Builds a static graph making dynamic computation harder.
How does ONNX optimizes computation?
- graph-level optimizations: merges NN blocks to reduce computation
- constant folding: precomputes static values to eliminate runtime calculations
- Removes redundant nodes
- Supports post-training quantization multiple variations
- Supports Hardware acceleration
Why does ML frameworks require the graph to be dynamic at each forward pass?
- some models require if-else conditions during inference, static graph cannot easily handle dynamic control flow
- dynamic graphs allow easy modification of architecture without recompiling the entire model
- some models process inputs of different sizes, e.g. NLP models with variable-length sentences, static graph requires fixed input shapes, making it harder to handle variable sized data
When not to use ONNX
- when models has conditional branches, loops depending on input values, recursion
- ONNX supports many but not all operations on Pytorch, Tensorflow
- When your target platform doesn’t supports ONNX
- When your model uses variable input sizes alot
What to do when a Model has dynamic flow?
- use opset_version=12+ which supports limited dynamic control
- Use dynamic_axes when exporting
- use custom inference loops for sequential text generation
torch.onnx.export(
model,
dummy_input,
"dynamic_model.onnx",
input_names=["input"],
output_names=["output"],
dynamic_axes={
"input": {0: "batch_size", 2: "height", 3: "width"},
"output": {0: "batch_size", 2: "height", 3: "width"}
}
)In pytorch, tensors follow the NCHW format by default for images
(batch_size, channels, height, width)
0 -> Batch size
1 -> Channels
2 -> Height
3 -> Widthdynamic_axes={
"input": {0: "batch_size", 2: "height", 3: "width"},
"output": {0: "batch_size", 2: "height", 3: "width"}
}
"input": {0: "batch_size"} → Batch size can change.
"input": {2: "height", 3: "width"} → Height and width can also vary.
(1, 3, 224, 224), (4, 3, 512, 512), or (8, 3, 300, 400)What if model is a NLP model?
dynamic_axes={
"input": {0: "batch_size", 1: "seq_length"},
"output": {0: "batch_size", 1: "seq_length"}
}
inputs are usually in (batch_size, sequence_length, embedding_dim) format.Whats Batch size?
number of input samples processed together in one forward pass of a model. for NLP models, the shape might be (16, sequence_length, embedding_dim) → 16 sentences at a time
Why do we pass dummy input to ONNX export?
ONNX requires tracing to define model’s computational graph. Dummy input provides a reference shape and dtype for ONNX to infer tensor dimensions