archive2022

CPU inference with ONNX Runtime in Python

How to export a PyTorch image model to ONNX, run it with ONNX Runtime on a CPU-only server or a Raspberry Pi, and avoid the common preprocessing and threading mistakes.

Training happens on a GPU, but my models run on CPUs: a home server, a cheap VPS, a Raspberry Pi next to a camera. Shipping the full PyTorch stack to those machines always felt too heavy, so for the last few projects I export to ONNX and run it with ONNX Runtime. These are the steps and the mistakes I made along the way.

pip install onnxruntime is much smaller than PyTorch, which matters on a device with little storage. ONNX Runtime applies graph optimizations (operator fusion, constant folding) and has fast CPU kernels. The .onnx file holds the graph and the weights, so the service does not need the training repository.

It is not always the right tool. Models with custom operators that ONNX does not support need extra work or fail to export. The newest architectures can take time to get export support. And if you already have a tuned GPU setup with PyTorch or TensorRT, ONNX Runtime may not add much.

Export from PyTorch

Example with a pretrained MobileNetV2 from torchvision:

import torch
import torchvision

model = torchvision.models.mobilenet_v2(weights="IMAGENET1K_V1")
model.eval()

dummy = torch.randn(1, 3, 224, 224)
torch.onnx.export(
    model,
    dummy,
    "mobilenet_v2.onnx",
    input_names=["input"],
    output_names=["logits"],
    dynamic_axes={"input": {0: "batch"}, "logits": {0: "batch"}},
    opset_version=13,
)

Without model.eval(), dropout and batch norm export in training mode and the results are wrong. dynamic_axes makes the batch size flexible. I keep height and width fixed, because fixed shapes allow more optimizations. Opset 13 works with current ONNX Runtime releases.

Check it

import onnx

m = onnx.load("mobilenet_v2.onnx")
onnx.checker.check_model(m)
print([i.name for i in m.graph.input], [o.name for o in m.graph.output])

The more important test is comparing outputs with PyTorch on the same input:

import numpy as np
import onnxruntime as ort

x = torch.randn(1, 3, 224, 224)
with torch.no_grad():
    ref = model(x).numpy()

sess = ort.InferenceSession("mobilenet_v2.onnx", providers=["CPUExecutionProvider"])
out = sess.run(None, {"input": x.numpy()})[0]
print(np.abs(ref - out).max())  # should be small, around 1e-5

Run it in a service

On the target machine you only need onnxruntime, numpy, and OpenCV or Pillow to read images.

import cv2
import numpy as np
import onnxruntime as ort

MEAN = np.array([0.485, 0.456, 0.406], dtype=np.float32)
STD = np.array([0.229, 0.224, 0.225], dtype=np.float32)

opts = ort.SessionOptions()
opts.intra_op_num_threads = 4
opts.graph_optimization_level = ort.GraphOptimizationLevel.ORT_ENABLE_ALL
sess = ort.InferenceSession("mobilenet_v2.onnx", opts, providers=["CPUExecutionProvider"])
input_name = sess.get_inputs()[0].name

def preprocess(path):
    img = cv2.imread(path)                       # BGR, HWC, uint8
    img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
    img = cv2.resize(img, (224, 224), interpolation=cv2.INTER_LINEAR)
    img = img.astype(np.float32) / 255.0
    img = (img - MEAN) / STD
    img = np.transpose(img, (2, 0, 1))           # HWC -> CHW
    return img[np.newaxis, ...]                  # add batch dim

def predict(path):
    x = preprocess(path)
    logits = sess.run(None, {input_name: x})[0][0]
    probs = np.exp(logits - logits.max())
    probs /= probs.sum()
    top = probs.argsort()[::-1][:5]
    return [(int(i), float(probs[i])) for i in top]

Create the session once at startup. Creating it is slow, running it is fast.

Preprocessing

When the ONNX model “gives bad results”, it is almost never ONNX. In my case it was preprocessing every time:

Mistake Effect
BGR instead of RGB (OpenCV reads BGR) Lower accuracy, sometimes subtle
Missing / 255.0 or missing mean/std Very wrong outputs
HWC instead of CHW Error or garbage
float64 input Error: the model expects float32
Different resize method or crop than training Small accuracy loss

I now keep the preprocessing code next to the model file, and test it against the training code with the same image.

Threads

intra_op_num_threads is the number of threads used inside one operator. Set it to the number of physical cores you want to give the model.

The trap is a web server with several worker processes. Each one creates its own thread pool. Four workers with four threads each on a four-core machine means 16 busy threads fighting for 4 cores, and latency gets worse. I use either one process with N threads or N processes with 1 thread, and measure both with real traffic.

Quantization

For models with many linear layers (transformers, MLPs), dynamic int8 quantization often helps on CPU:

from onnxruntime.quantization import quantize_dynamic, QuantType

quantize_dynamic("model.onnx", "model.int8.onnx", weight_type=QuantType.QUInt8)

For convolution-heavy vision models it helps less. Static quantization with a calibration dataset is the better tool there, but I have not done it yet. Either way, check accuracy on a real validation set afterwards.

Raspberry Pi

Use a 64-bit OS, and check on PyPI that a wheel exists for aarch64 and your Python version before you plan anything. Building ONNX Runtime from source on a Pi is slow. Start with MobileNet-sized models and measure with your real image size. A Pi 4 under constant load throttles without a heatsink or fan; vcgencmd measure_temp and vcgencmd get_throttled show it.

To measure:

import time
x = np.random.rand(1, 3, 224, 224).astype(np.float32)
for _ in range(10):
    sess.run(None, {input_name: x})   # warm up
n = 100
t = time.perf_counter()
for _ in range(n):
    sess.run(None, {input_name: x})
print((time.perf_counter() - t) / n * 1000, "ms per image")

The first runs are always slower, so warm up before you time anything.