ONNX: a Portable Model Format
A pickle is tied to Python and to the exact library versions that wrote it (previous lesson). That is fine while training and serving share one environment, and a problem as soon as they do not: the scoring service is written in Java or C#, the model must run on a phone or in a browser, the serving image should not carry scikit-learn and its dependencies, or the model must still load in five years. ONNX (Open Neural Network Exchange) solves this by describing the model as data instead of as Python objects: a computation graph of standard operators, stored in a file whose format is defined by a public specification. Any runtime that implements those operators can execute it.
The idea: a graph of standard operators
An ONNX model is a directed graph. Its inputs have a name, an element type and a shape (float32, [None, 8], where None means "any batch size"). Each node applies one operator from the ONNX operator set (MatMul, Add, Sigmoid, Scaler, TreeEnsembleClassifier, …) to named tensors and produces named tensors. Initializers are constant tensors stored in the file (weights, means, scales). The outputs are named tensors too.
Two version numbers matter. The IR version is the version of the file format itself. The opset (operator set version) says which definition of each operator the graph uses: operators evolve (new attributes, new types), and a runtime declares which opsets it supports. Pin the opset when exporting, just as you pin library versions for a pickle, and check that your production runtime supports it. Besides the default domain (ai.onnx, neural-network style operators), there is an ai.onnx.ml domain with classical-ML operators such as Scaler, LinearClassifier, TreeEnsembleClassifier and ZipMap, which is what scikit-learn models map to.
Converters translate a framework's model into this graph: skl2onnx for scikit-learn, torch.onnx.export for PyTorch, tf2onnx for TensorFlow and Keras, onnxmltools for XGBoost and LightGBM. ONNX Runtime is the most common engine that executes the graph, on CPU or with GPU and other hardware back-ends, from Python, C, C++, C#, Java, JavaScript and others.
From scratch: the graph is just arithmetic
Before converting anything, it helps to see that the exported pipeline really is a short sequence of standard operations. The scaler is (x - mean) / scale, the logistic regression is a matrix product, an addition and a sigmoid. Written in NumPy with the fitted parameters, it reproduces predict_proba:
import numpy as np
from sklearn.datasets import make_classification
from sklearn.model_selection import train_test_split
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.linear_model import LogisticRegression
X, y = make_classification(n_samples=2000, n_features=8, n_informative=5, random_state=0)
X_tr, X_te, y_tr, y_te = train_test_split(X, y, test_size=0.25, random_state=0)
model = make_pipeline(StandardScaler(), LogisticRegression()).fit(X_tr, y_tr)
scaler, clf = model[0], model[1]
z = (X_te - scaler.mean_) / scaler.scale_ # node 1: Scaler (subtract, multiply)
logit = z @ clf.coef_[0] + clf.intercept_[0] # node 2: MatMul + Add
p = 1 / (1 + np.exp(-logit)) # node 3: Sigmoid
diff = np.abs(p - model.predict_proba(X_te)[:, 1]).max()
print(f"parameters: {scaler.mean_.size + scaler.scale_.size + clf.coef_.size + clf.intercept_.size} numbers")
print(f"max |numpy - sklearn| on {len(X_te)} test rows: {diff:.1e}")parameters: 25 numbers
max |numpy - sklearn| on 500 test rows: 0.0e+00
The NumPy version matches scikit-learn exactly (difference 0.0 on the 500 test rows): 25 numbers plus the names of three operations are the whole model. An ONNX file stores exactly that, in a form any runtime can read.
Export with skl2onnx, run with ONNX Runtime
skl2onnx.to_onnx takes the fitted model and a sample input, from which it infers the input type and shape (pass float32: most of ONNX's classical-ML operators produce single-precision outputs). The resulting ModelProto can be inspected, saved with SerializeToString() and loaded by onnxruntime.InferenceSession.
import numpy as np
import onnxruntime as ort
from skl2onnx import to_onnx
from sklearn.datasets import make_classification
from sklearn.model_selection import train_test_split
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.linear_model import LogisticRegression
X, y = make_classification(n_samples=2000, n_features=8, n_informative=5, random_state=0)
X_tr, X_te, y_tr, y_te = train_test_split(X, y, test_size=0.25, random_state=0)
model = make_pipeline(StandardScaler(), LogisticRegression()).fit(X_tr, y_tr)
onx = to_onnx(model, X_tr[:1].astype(np.float32), target_opset={"": 18, "ai.onnx.ml": 3})
print("IR version:", onx.ir_version, "| opsets:", {o.domain or "ai.onnx": o.version for o in onx.opset_import})
print("nodes:", [n.op_type for n in onx.graph.node])
for t in onx.graph.input:
dims = [d.dim_value or d.dim_param or None for d in t.type.tensor_type.shape.dim]
print("input:", t.name, dims)
print("outputs:", [o.name for o in onx.graph.output])
blob = onx.SerializeToString() # what you would write to model.onnx
print(f"file size: {len(blob)} bytes")
sess = ort.InferenceSession(blob, providers=["CPUExecutionProvider"])
labels, probs = sess.run(None, {sess.get_inputs()[0].name: X_te.astype(np.float32)})
print("first label:", labels[0], "| first probability output:", {k: round(v, 3) for k, v in probs[0].items()})IR version: 8 | opsets: {'ai.onnx.ml': 1, 'ai.onnx': 18}
nodes: ['Scaler', 'LinearClassifier', 'Cast', 'ZipMap']
input: X [None, 8]
outputs: ['output_label', 'output_probability']
file size: 735 bytes
first label: 0 | first probability output: {0: 0.908, 1: 0.092}
The converter mapped the scaler to a Scaler node and the classifier to a LinearClassifier node (which applies the sigmoid itself), then added a Cast for the label and a ZipMap. The opsets show that target_opset is an upper limit: the converter asked for version 18 of the default domain but only version 1 of ai.onnx.ml, because version 1 already defines every operator this graph needs. The whole file is 735 bytes. The probability output is not an array: it is a list with one dictionary per row, {class: probability}. That is ZipMap, which skl2onnx adds by default to mimic a "label to probability" mapping. It is convenient in some languages and awkward everywhere else (slow, and not a tensor), so most services turn it off with options={"zipmap": False} and get a plain float32 array of shape [n, 2].
Check that the export agrees with the original
An export is a re-implementation of the model by a different program, in a different precision. Never ship one without measuring the agreement on real data: the maximum absolute difference of the probabilities, and the share of rows where the predicted label differs. Small probability differences of the order of float32 rounding (about 1e-7) are expected; label disagreements can happen only for rows whose probability is within that tolerance of the 0.5 threshold.
import numpy as np
import onnxruntime as ort
from skl2onnx import to_onnx
from sklearn.datasets import make_classification
from sklearn.model_selection import train_test_split
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.linear_model import LogisticRegression
from sklearn.ensemble import RandomForestClassifier
X, y = make_classification(n_samples=2000, n_features=8, n_informative=5, random_state=0)
X_tr, X_te, y_tr, y_te = train_test_split(X, y, test_size=0.25, random_state=0)
models = {
"logistic pipeline": make_pipeline(StandardScaler(), LogisticRegression()).fit(X_tr, y_tr),
"random forest (100 trees)": RandomForestClassifier(n_estimators=100, random_state=0).fit(X_tr, y_tr),
}
for name, m in models.items():
onx = to_onnx(m, X_tr[:1].astype(np.float32), options={"zipmap": False}, target_opset={"": 18, "ai.onnx.ml": 3})
sess = ort.InferenceSession(onx.SerializeToString(), providers=["CPUExecutionProvider"])
labels, probs = sess.run(None, {"X": X_te.astype(np.float32)})
p_sk = m.predict_proba(X_te)
print(f"{name}: output type {type(probs).__name__} {probs.dtype} {probs.shape}")
print(f" max |p_onnx - p_sklearn| = {np.abs(probs - p_sk).max():.1e}, "
f"label disagreements {int((labels != m.predict(X_te)).sum())} of {len(X_te)}, "
f"ONNX accuracy {(labels == y_te).mean():.3f}, sklearn {m.score(X_te, y_te):.3f}")logistic pipeline: output type ndarray float32 (500, 2)
max |p_onnx - p_sklearn| = 1.0e-07, label disagreements 0 of 500, ONNX accuracy 0.864, sklearn 0.864
random forest (100 trees): output type ndarray float32 (500, 2)
max |p_onnx - p_sklearn| = 4.2e-07, label disagreements 0 of 500, ONNX accuracy 0.924, sklearn 0.924
Both exports agree: the largest probability difference is 1.0e-07 for the logistic pipeline and 4.2e-07 for the forest, no label changes on the 500 test rows, and the same test accuracy (0.864 and 0.924). Put this comparison in the pipeline that produces the artifact, with a tolerance (for example "max difference below 1e-4, no more than 0.1 % label changes"), and fail the build when it is exceeded. Run it on a sample of real inputs, including edge cases (very large values, zeros, the categories your converter handles specially), not just the training set.
Limits: what does not convert
A converter knows a fixed list of estimators and their options. Anything else fails at export time, which is good: you learn about the problem in the build, not in production. The typical failure is custom Python code inside the pipeline.
import numpy as np
from skl2onnx import to_onnx
from sklearn.datasets import make_classification
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import FunctionTransformer
from sklearn.linear_model import LogisticRegression
def clip_outliers(X):
return np.clip(X, -3, 3)
X, y = make_classification(n_samples=500, n_features=8, random_state=0)
model = make_pipeline(FunctionTransformer(clip_outliers), LogisticRegression()).fit(X, y)
try:
to_onnx(model, X[:1].astype(np.float32))
except Exception as e:
print(type(e).__name__ + ":", str(e).split(". ")[0] + ".")RuntimeError: FunctionTransformer is not supported unless the transform function is None (= identity).
The ways out, from most to least preferred: replace the custom step with a standard estimator that has a converter (here, clipping can often be dropped or done by a QuantileTransformer or by the upstream feature pipeline); move the step out of the model into the caller, and document it in the model's signature; or register a custom converter (a shape calculator plus a function that emits ONNX nodes such as Clip), which you then have to maintain and test like any other code.
Other limits to know:
- Strings and categories. Some encoders convert (
OneHotEncoderwith string categories does), others do not, and string inputs make the graph harder to call from other languages. Many teams encode categories before the model. - Precision. Most classical-ML operators compute in float32 (newer versions of some, such as
TreeEnsemble, also accept double). Models whose decisions depend on the seventh significant digit (long tree ensembles with thresholds very close to data values) can flip a few predictions; the agreement check catches it. - Dynamic Python logic. Data-dependent control flow in PyTorch models (
if x.sum() > 0) is traced as one fixed path by the older TorchScript-based exporter; thetorch.export-based exporter (dynamo=True, the default in recent PyTorch) instead refuses it unless the branch is rewritten withtorch.cond. Dynamic shapes only make the batch or sequence length variable, not the control flow. Check the export on several inputs. - Pre- and post-processing. Tokenizers, image decoding and business rules often stay outside the graph. Then the "portable" model is only portable together with that code.
Pitfalls
- Exporting with float64 sample data. The input type is inferred from the sample; pass
float32and sendfloat32at inference. - Not pinning the opset. A new converter may emit a newer opset that the production runtime (an older ONNX Runtime, a mobile build) does not support.
- ZipMap surprises. The default probability output is a list of dictionaries; use
zipmap: Falsefor an array. - Trusting the export without a check. Always compare with the original model on real data, with a tolerance.
- Assuming ONNX is a sandbox. Parsing a file is much safer than unpickling one, but runtimes have had bugs and custom-operator libraries are native code. Load models from trusted sources and keep runtimes updated (security).
Practice
- Why can a Java service score an ONNX model trained in scikit-learn, but not a joblib file of the same model?
- The export check reports a max probability difference of
3e-08and 1 label disagreement out of 500,000 rows. Is the export broken? - Your pipeline has a
FunctionTransformer(np.log1p)before the classifier, andto_onnxfails. Name two fixes.
Answers
- The joblib file is a pickle: a program that imports Python classes and restores Python objects, so only Python with the same libraries can load it. The ONNX file describes the model as a graph of operators defined by a specification, and ONNX Runtime has a Java API that executes that graph.
- Probably not. Differences of the size of float32 rounding are expected, and a single row whose probability lies within about 1e-7 of the threshold can flip. Look at that row; if it is right at 0.5, the export is fine. Many disagreements, or large probability differences, would indicate a real conversion problem.
- Apply the log transform before calling the model (in the caller or the feature pipeline) and document it in the signature; or write and register a custom converter that emits ONNX
AddandLognodes; or train on already-transformed features.
Test yourself
What does the opset of an ONNX model specify?
- The file compression level
- Which version of each operator's definition the graph uses
- The batch size
- The training framework
By default, skl2onnx returns classifier probabilities as a list of dictionaries. What produces that, and how is it turned off?
- The Scaler node; set
scale=False - A ZipMap node; pass
options={"zipmap": False} - ONNX Runtime; use the GPU provider
- It cannot be turned off
After exporting, what is the minimum check before shipping the ONNX model?
- The file size is smaller than the pickle
- Probabilities and labels agree with the original model on real data within a tolerance
- The file opens in a text editor
- The model has fewer nodes than the original pipeline has steps
Why does a pipeline with a custom Python function step usually fail to export?
- ONNX files cannot contain more than one step
- The converter only knows registered estimators; arbitrary Python code has no ONNX translation unless you write a custom converter
- Custom functions are too slow
- ONNX only supports neural networks