← Blog
An ivory and purple caliper measures the width of a small orange tile.
Published on
2026-11-25

Export PyTorch to ONNX and verify predictions on CPU

A model that loads on your training machine still has to earn its place on a CPU worker. Give it a row your application might send. Does it accept the same feature layout, return the same scores, and pick the same class? Then send several rows together. A successful export can leave that second question unanswered if the batch size was fixed during conversion.

We exported a small PyTorch classifier to one ONNX file and opened it in a separate environment with no PyTorch installed. For a single row, both probabilities matched exactly on our machine. For four rows, the largest absolute difference was about 4.47 × 10⁻⁸. Both runtimes chose the same class for every row.

Define what the CPU worker must reproduce

Our example takes three numeric features per row and returns two class probabilities. The batch size can change. The number, order and type of the features must stay consistent. We use fixed weights so anyone can reproduce the test without training a model or downloading a checkpoint. The example checks deployment behavior. It makes no claim about the classifier’s accuracy on a real task.

For your own model, first load the trained weights and switch to evaluation mode. If you still need to resume training, keep the checkpoint, which can include the optimizer and other training state. The ONNX file in this example contains the forward computation and its weights. Our guide to saving a PyTorch model covers what to preserve for training.

Keep the export and inference environments separate

These are the versions we tested on Windows x64 with Python 3.12. Run the following commands from an empty working directory in PowerShell. Keeping two environments catches the common mistake of importing training code from the inference script. We pinned onnx-ir because this exporter combination failed during graph conversion with version 1.1.0 and succeeded with 0.1.12.

py -3.12 -m venv .export-env
py -3.12 -m venv .cpu-env
.\.export-env\Scripts\python -m pip install --index-url https://download.pytorch.org/whl/cpu torch==2.9.1
.\.export-env\Scripts\python -m pip install numpy==2.2.6 onnx==1.19.1 onnxscript==0.5.6 onnx-ir==0.1.12
.\.cpu-env\Scripts\python -m pip install numpy==2.2.6 onnxruntime==1.23.2

Start export_model.py with the classifier and four reference inputs below. A fixed feature order matters even for a graph that accepts the right shape. Swapping two columns in a real application can change the prediction without producing a shape error.

from pathlib import Path
import json
import hashlib
import onnx
import torch
from torch import nn

class Classifier(nn.Module):
    def __init__(self):
        super().__init__()
        self.layer = nn.Linear(3, 2)
        with torch.no_grad():
            self.layer.weight.copy_(torch.tensor([[0.7, -1.2, 0.3], [-0.4, 0.8, 1.1]]))
            self.layer.bias.copy_(torch.tensor([0.15, -0.25]))

    def forward(self, features):
        return torch.softmax(self.layer(features), dim=1)

model = Classifier().eval()
rows = torch.tensor([[0.5, -1.2, 0.7], [0.1, 1.4, -0.6],
                     [1.5, -0.2, 0.4], [-1.0, 0.8, 0.2]], dtype=torch.float32)

Export with a variable batch dimension

Append the following block to the same file. The example input has two rows. Declaring dimension zero as batch allows the exported graph to accept a different number at inference time. Dimension one stays fixed at three features. The names features and probabilities become the interface that the worker calls.

path = Path("classifier.onnx")
torch.onnx.export(
    model, (rows[:2],), path,
    input_names=["features"], output_names=["probabilities"],
    dynamic_shapes={"features": {0: torch.export.Dim("batch")}},
    dynamo=True, opset_version=18, external_data=False, verbose=False,
)
graph = onnx.load(path)
onnx.checker.check_model(graph)
reference = {"torch": torch.__version__, "onnx": onnx.__version__, "opset": 18,
             "model_sha256": hashlib.sha256(path.read_bytes()).hexdigest(), "batches": []}
with torch.inference_mode():
    for n in (1, 4):
        inputs = rows[:n]
        reference["batches"].append({"features": inputs.tolist(), "expected": model(inputs).tolist()})
Path("reference.json").write_text(json.dumps(reference, indent=2), encoding="utf-8")

The export targets ONNX operator set 18. For this small model, external_data=False keeps the weights in the ONNX file. The checker validates the graph structure. The reference JSON serves a different purpose: it records the actual PyTorch outputs for batches of one and four. Its SHA-256 digest pairs the reference with the exact artifact we tested. If a larger model uses external weight files, package and verify those files with the graph. See the PyTorch ONNX exporter documentation for export options.

Compare the probabilities on CPU

Save the next block as verify_cpu.py. It uses the CPU execution provider explicitly. Before comparing any numbers, it checks the output shape and verifies that the scores are finite. It then checks every probability within a relative tolerance of 1e-5 and an absolute tolerance of 1e-6, followed by the winning class for each row. A class label can stay the same even when the underlying scores drift.

from pathlib import Path
import hashlib
import json
import numpy as np
import onnxruntime as ort

reference = json.loads(Path("reference.json").read_text(encoding="utf-8"))
path = Path("classifier.onnx")
assert hashlib.sha256(path.read_bytes()).hexdigest() == reference["model_sha256"]
session = ort.InferenceSession(str(path), providers=["CPUExecutionProvider"])
for case in reference["batches"]:
    features = np.asarray(case["features"], dtype=np.float32)
    expected = np.asarray(case["expected"], dtype=np.float32)
    actual, = session.run(["probabilities"], {"features": features})
    assert actual.shape == expected.shape
    assert np.isfinite(actual).all() and np.isfinite(expected).all()
    np.testing.assert_allclose(actual, expected, rtol=1e-5, atol=1e-6)
    np.testing.assert_array_equal(actual.argmax(1), expected.argmax(1))
    print(actual.shape, actual.argmax(1), np.max(np.abs(actual - expected)))

Run the scripts from the same working directory, using a different Python executable for each.

.\.export-env\Scripts\python -X utf8 export_model.py
.\.cpu-env\Scripts\python verify_cpu.py
  • One row. The output shape was [1, 2]. Both runtimes chose class 0 and the maximum absolute difference was zero.
  • Four rows. The shape was [4, 2]. Both returned classes [0, 1, 0, 1]. The largest probability difference was 4.47e-8.

We also passed a float32 array of shape [1, 4] to the same session. ONNX Runtime rejected dimension one with Got: 4 Expected: 3. That check distinguishes adding a row, which the graph supports, from adding a feature, which changes the model’s input. To diagnose a mismatch, inspect session.get_inputs() and compare its names, types and shapes with the payload your application sends. The ONNX Runtime Python API reference documents the session interface.

Decide whether the model is ready for a worker

For this classifier, the exported artifact passed the two batch tests and rejected an incompatible width. For an application, keep representative inputs with each model release. Include cases close to a decision threshold and compare the values your application actually uses. If the application normalizes data or maps class indices to labels outside the graph, test those steps too. A matching probability vector can still be assigned the wrong label.

Once the predictions check out, measure latency and memory separately using your actual model, batch sizes and concurrency. Time session startup separately from repeated requests. Our batch inference guide covers how to choose a batch for a queue. To evaluate a CPU instance with Hivenet, take the same ONNX artifact and reference cases to the candidate instance, rerun the correctness checks there, then time the workload. This local test establishes numerical agreement for the example; it does not establish VM sizing or a speed advantage.

Your next workload belongs on Hivenet.

Pick one AI, compute, or storage workload and see the difference for yourself. Spin it up in minutes, or let our team map your fastest path to production.