← Blog
A stepped ivory measuring gauge with an orange slider.
Published on
2026-11-27

Quantize an ONNX model and check what changes on CPU

Our handwritten-digit classifier shrank from 1,790,385 to 455,990 bytes when we quantized its weights. It also got faster on the test CPU. The harder question was whether it still made the same decisions. On 450 held-out digits it did. On inputs deliberately constructed to put two classes nearly level, seven decisions changed.

Here’s how to run that comparison on an ONNX model and decide whether the smaller artifact is suitable for a CPU worker.

Keep a floating-point reference

Start with an FP32 model that already gives the expected outputs in ONNX Runtime. Keep its input preprocessing, output interpretation and test examples fixed. Otherwise, a change as small as dividing the pixels by 255 instead of 16 could look like a quantization error.

We used the scikit-learn digits dataset: 8-by-8 grayscale images with pixel values from 0 to 16. We kept 450 labeled digits for evaluation and used 1,347 to fit a classifier with two fixed, randomly initialized hidden layers and a fitted linear output. Each image supplied 64 normalized inputs. The largest of ten output scores selected the digit. Those raw scores are not calibrated probabilities.

Quantize the matrix multiplications and inspect the graph

We ran shape inference before conversion, then used ONNX Runtime 1.23.2 to quantize the three weight matrices. The dynamic method stores signed 8-bit weights and calculates activation quantization parameters at inference time. The example below starts with the prepared FP32 file. Dynamic quantization needs no separate calibration set. If you use static quantization, select representative calibration inputs and keep your evaluation set separate. The ONNX Runtime quantization guide describes the available methods and operator support.

from onnxruntime.quantization import QuantType, quantize_dynamic

quantize_dynamic(
    "digits-fp32.onnx", "digits-int8.onnx",
    op_types_to_quantize=["MatMul"],
    weight_type=QuantType.QInt8,
    per_channel=True,
)

Check that the intended operations changed. Our converted graph contained three MatMulInteger nodes and three DynamicQuantizeLinear nodes. It also contained casts, multiplications and ReLUs. The graph inspection identifies which operations were converted; the file sizes tell you how much space that saved.

from collections import Counter
import onnx

graph = onnx.load("digits-int8.onnx").graph
print(Counter(node.op_type for node in graph.node))

Compare the selected class and the scores behind it

With one image per call, FP32 and INT8 each classified 442 of 450 held-out digits correctly (98.2%). They selected the same class on every image, including the 36 for which FP32 had the smallest gap between its top two scores. Yet the largest absolute change in any output score was 0.0932. If your application uses a score threshold to send an item for review, check that decision separately. Agreement on the winning class does not test the threshold.

We also ran a deliberately difficult check. Starting with pairs of images assigned different FP32 classes, we blended the pixels and narrowed the interval until the FP32 decision was close to switching. INT8 picked a different class on seven of 24 such blends. These synthetic images have no ground-truth labels. That result measures sensitivity near a boundary; it is not an estimate of errors among real users.

Measure warmed latency at the batch size you serve

We used the CPU execution provider on a Windows machine with an AMD Ryzen 7 7840HS. Each session used one thread within an operation and sequential graph execution. Both sessions were kept open. For each batch size, we warmed each model with 50 calls and timed another 500 per model, alternating which model ran first. The timer covered the inference call with an already-prepared input array. It excluded loading the model and decoding the image.

import onnxruntime as ort

options = ort.SessionOptions()
options.intra_op_num_threads = 1
options.inter_op_num_threads = 1
options.execution_mode = ort.ExecutionMode.ORT_SEQUENTIAL
session = ort.InferenceSession(
    "digits-int8.onnx", sess_options=options,
    providers=["CPUExecutionProvider"],
)
  • One digit per call. Median latency fell from 0.0517 ms to 0.0345 ms. The 95th percentile fell from 0.0883 ms to 0.0644 ms.
  • 32 digits per call. Median batch latency fell from 0.3024 ms to 0.1303 ms. The 95th percentile fell from 0.4408 ms to 0.1885 ms. Each time is for the full batch.

At these durations, hardware, runtime version, thread settings and other work on the host can affect the result. If most requests contain one item, use that measurement for the serving decision. For an overnight batch job, time full batches at the actual worker count. The ONNX Runtime threading reference explains the controls used here.

Decide what would justify switching

Choose the acceptable prediction drift and latency budget before comparing artifacts. For this classifier, INT8 saved 74.5% on disk and met the narrow goal of preserving all held-out top-class decisions. An application that acts on small score differences still has a separate acceptance test. Keep the FP32 artifact available until the candidate passes both quality and performance checks.

To evaluate a CPU instance from Compute with Hivenet, rerun the comparison on the intended instance with representative inputs, normal concurrency and end-to-end request timing. The local measurements above give you a procedure to repeat. If the full request remains slow, the PyTorch Profiler guide can help locate time spent in a PyTorch preprocessing pipeline before the ONNX call.

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.