Sub topic 12
ONNX: a graph format built on protobuf
This chapter assumes you know what pickle risks are from the earlier chapters, and that you have used a framework such as PyTorch. ONNX (Open Neural Network Exchange) is a different kind of model file. A pickle file is a program that the unpickler runs. An ONNX file is a description of a computation, stored as structured data. This chapter explains how that description is laid out, why loading it does not execute code, and where the remaining risks are.
What an ONNX file stores
An ONNX file holds one serialized protobuf message. Protocol Buffers (protobuf) is a binary format where a schema, written in a .proto file, fixes every field's name, number, and type. The ONNX schema defines ModelProto as the top-level message. A parser reads bytes and fills those fields. It never looks up a Python callable or imports a module, because the schema has no field that could mean "call this function".
The main parts of a ModelProto are:
ir_version: the version of the file format itself.opset_import: which operator set versions the graph uses, per domain. The empty domain, also writtenai.onnx, is the standard set.graph: aGraphProtothat holds the computation.metadata_props: free-form string key/value pairs, such as a producer note.
The GraphProto contains four things:
- Nodes, each naming an operator such as
MatMulorConv, with input and output tensor names. - Initializers, which are the weights, stored as
TensorProtovalues. - Inputs and outputs, with element type and shape.
- Value info, which is optional shape information for intermediate tensors.
Because the graph is data, any runtime that implements the operators can execute it. This is why ONNX is a portability format: you export from PyTorch, then run with ONNX Runtime, TensorRT, or OpenVINO.
Building a model by hand
The following script builds a tiny linear layer, computing y = x @ W + b, using only the onnx package. It is useful because it shows that a model is just constructed protobuf messages.
import numpy as np
import onnx
from onnx import TensorProto, helper, numpy_helper
W = numpy_helper.from_array(
np.array([[1.0, 2.0], [3.0, 4.0]], dtype=np.float32), name="W"
)
b = numpy_helper.from_array(np.array([0.5, -0.5], dtype=np.float32), name="b")
x = helper.make_tensor_value_info("x", TensorProto.FLOAT, [None, 2])
y = helper.make_tensor_value_info("y", TensorProto.FLOAT, [None, 2])
matmul = helper.make_node("MatMul", ["x", "W"], ["xw"])
add = helper.make_node("Add", ["xw", "b"], ["y"])
graph = helper.make_graph(
[matmul, add], "tiny_linear", [x], [y], initializer=[W, b]
)
model = helper.make_model(graph, opset_imports=[helper.make_opsetid("", 17)])
model.ir_version = 8 # IR 8 matches opset 17 and loads in most runtimes
onnx.checker.check_model(model)
onnx.save(model, "tiny.onnx")
print("saved tiny.onnx")The None in the shape marks a dynamic batch dimension. onnx.checker.check_model validates the structure: known operators, consistent names, and legal types. It is a structural check and says nothing about whether the model is trustworthy.
Running the model
ONNX Runtime executes the graph. Pin the execution provider explicitly so the result does not depend on what hardware is installed.
import numpy as np
import onnxruntime as ort
session = ort.InferenceSession("tiny.onnx", providers=["CPUExecutionProvider"])
out = session.run(None, {"x": np.array([[1.0, 1.0]], dtype=np.float32)})
print(out[0]) # [[4.5 5.5]]The input [1, 1] times W gives [4, 6], and adding b gives [4.5, 5.5].
Inspecting a file without running it
Since a model is data, you can audit it before you hand it to a runtime. The function below loads the structure only (not external weight files), then lists operators, non-standard domains, and externally stored tensors.
import onnx
from onnx import TensorProto
def audit(path):
model = onnx.load(path, load_external_data=False)
print("ir_version:", model.ir_version)
for opset in model.opset_import:
print("opset:", opset.domain or "ai.onnx", opset.version)
ops = sorted({(n.domain or "ai.onnx", n.op_type) for n in model.graph.node})
for domain, op in ops:
flag = "" if domain == "ai.onnx" else " <-- non-standard domain"
print(f"op: {domain}.{op}{flag}")
for init in model.graph.initializer:
if init.data_location == TensorProto.EXTERNAL:
info = {e.key: e.value for e in init.external_data}
print("external tensor:", init.name, info.get("location"))
audit("tiny.onnx")This version only looks at the top-level graph. Operators such as If and Loop carry subgraphs in their attributes, so a complete audit must recurse into those too.
Where the risks remain
ONNX removes the pickle problem, but it does not make an untrusted file safe. The risks have moved.
| Risk | How it arises | Mitigation |
|---|---|---|
| Parser bugs | The protobuf parser and the runtime are native code. A crafted file can target memory-safety bugs in them. | Keep `onnx` and the runtime updated. Parse untrusted files in a sandboxed process. |
| External data paths | Large tensors can live in a separate file. The `location` field names it. A hostile path such as `../../etc/passwd` could make a loader read an unintended file. The `onnx` package has had path traversal advisories in this area. | Load with `load_external_data=False` first, inspect the `location` values, and use current library versions. |
| Custom operators | A graph can reference an operator from a custom domain. This only runs native code if you register a shared library that implements it. | Do not register libraries supplied alongside a model. Reject unknown domains in your audit. |
| Resource exhaustion | A tiny file can declare huge shapes or deep control flow, causing large allocations or long runs. | Set memory and time limits on the loading process. |
| Metadata and names | `metadata_props` and tensor names are untrusted strings. | Treat them as data. Do not put them into shell commands, SQL, or log formats unescaped. |
Compared with pickle-based checkpoints
A PyTorch checkpoint stores a Python object graph that the unpickler rebuilds, and the file can name any importable callable. An ONNX file stores a closed vocabulary: operator names from a versioned set, plus tensors. The loader has no mechanism to import arbitrary code, so the pickle attack from earlier chapters has no equivalent here.
The trade-off is expressiveness. ONNX can only describe computations that the operator set covers. Exporting from PyTorch traces or compiles your model into that vocabulary. Python control flow, custom layers, and dynamic behavior may fail to export or need custom operators. A model's weights often survive the export, but its training code and its Python-level logic do not. If you need to resume training or load weights into the original architecture, a weights-only format such as safetensors is the better fit. ONNX targets deployment.
Practical checklist
- Prefer ONNX or safetensors over pickle-based files when you do not control the source.
- Run
auditfirst. Reject unknown operator domains and unexpected external data paths. - Run
onnx.checker.check_modelfor structure, and treat a pass as a lint result, not a safety verdict. - Keep
onnxandonnxruntimecurrent. - Load files from unknown sources in an isolated process with memory and time limits.
Exercise
A colleague sends you model.onnx from an unknown source. You run audit and see an operator com.example.FastAttention in a non-standard domain, plus an initializer whose external data location is ../weights.bin. Name two reasons you should not just call InferenceSession on it, and one action for each.
Show answer
First, the com.example domain means the model needs a custom operator. Running it would require you to register a native shared library, which is arbitrary code, so do not register any library that came with the model, and ask for a version using standard operators or a library you can review. Second, ../weights.bin points outside the model's own directory, which is the path traversal pattern, so do not let the loader resolve it. Load with load_external_data=False, verify that the path stays inside the model directory (or reject the file), and keep the libraries updated.