Sub topic 12
ONNX: a graph format built on protobuf
Prerequisites and purpose
This chapter assumes basic Python, familiarity with trained model weights, and basic PyTorch or another deep learning framework. You should also know that a byte stream is a sequence of bytes used to store or transmit data.
ONNX, or Open Neural Network Exchange, is a format for representing machine learning models. It describes a model as a computation graph: a set of operations connected by tensors. An ONNX file usually has the .onnx extension.
ONNX uses Protocol Buffers, often called protobuf. Protobuf is a language-neutral format that encodes structured data into compact bytes. An ONNX file is therefore a serialized protobuf message called ModelProto.
The graph inside an ONNX file
An ONNX graph contains:
- Input and output definitions.
- Nodes, such as matrix multiplication, convolution, or activation.
- Initializers, which hold learned weights and biases.
- Tensor shapes and data types.
- An operator set version, which identifies the meaning of operations.
- Optional metadata, such as the producer name and model version.
The graph is normally directed and acyclic. Data flows from input tensors through nodes to output tensors.
A runtime reads this graph and executes equivalent operations. The runtime does not need the original Python class or training code. This separation makes ONNX useful for deployment across languages, operating systems, and hardware providers.
Creating and inspecting an ONNX model
The following program creates a small graph, saves it, and checks its structure. Install the dependency first with pip install onnx.
import onnx
from onnx import TensorProto, checker, helper
x = helper.make_tensor_value_info("x", TensorProto.FLOAT, [None, 2])
y = helper.make_tensor_value_info("y", TensorProto.FLOAT, [None, 2])
weights = helper.make_tensor(
name="weights",
data_type=TensorProto.FLOAT,
dims=[2, 2],
vals=[1.0, 0.0, 0.0, 1.0],
)
node = helper.make_node(
"MatMul",
inputs=["x", "weights"],
outputs=["y"],
)
graph = helper.make_graph(
nodes=[node],
name="IdentityLike",
inputs=[x],
outputs=[y],
initializer=[weights],
)
model = helper.make_model(
graph,
producer_name="format-demo",
opset_imports=[helper.make_opsetid("", 13)],
)
checker.check_model(model)
onnx.save(model, "identity_like.onnx")
loaded = onnx.load("identity_like.onnx")
print(loaded.graph.name)
print([node.op_type for node in loaded.graph.node])onnx.load parses the protobuf data into Python objects. It does not run the graph. Execution happens later when an inference engine, such as ONNX Runtime, receives the model and input tensors.
Security and portability trade-offs
ONNX is safer to parse than a general-purpose pickle because its standard representation describes data and graph structure rather than arbitrary Python callables. Loading an ONNX file should not reconstruct arbitrary Python objects.
That does not make every ONNX model harmless. A model can request excessive memory or computation. It can also use custom operators or provider-specific extensions. Those extensions may load native libraries or execute implementation-specific code.
| Property | ONNX |
|---|---|
| Main representation | Protobuf graph |
| Requires original Python classes | No |
| Typical portability | High across supported runtimes |
| Arbitrary Python execution during parsing | Not part of standard loading |
| Main risks | Resource exhaustion and custom runtime extensions |
Exercise
Exercise
Why can an ONNX model usually move between frameworks more easily than a pickled Python model?
Show answer
ONNX stores operations, tensors, shapes, and metadata in a standardized protobuf graph, while pickle can depend on Python classes and importable code from the original environment.