Sub topic 10
Checking Accuracy After Quantization and Conversion
This chapter assumes you can run a PyTorch or TensorFlow model, you know what float32 and int8 mean, and you have already exported a model as in the previous chapters. Here you will learn how to confirm that the optimized model still does its job, and how to find the cause when it does not.
Why accuracy can change
Quantization, conversion, and preprocessing changes each alter the numbers the model produces. A model that was fine in float32 can lose accuracy for three separate reasons:
- Quantization error. Rounding weights and activations to 256 levels removes detail. Layers with wide or outlier-heavy value ranges lose the most.
- Conversion differences. The exporter may fuse layers, change operator versions, or replace an operator with an approximation. For example, a different
resizeinterpolation mode silently changes every input. - Pipeline mismatch. The on-device code may normalize or resize images differently from training. This is not a model bug, but it looks identical in the metrics.
You should check each of these at a different level of detail. A quick check tells you whether something is broken. A full check tells you how much quality you paid for the speed.
Build a reference first
Always compare against a float32 baseline that you evaluated yourself, on the same data and with the same code. Never compare against a number from a paper or a model card, because their preprocessing and evaluation split may differ from yours.
You need three things:
- A fixed evaluation set. Use held-out images that were not used for calibration. A few hundred is enough for a smoke test. For a final decision on a classifier with many classes, use thousands.
- A task metric. Top-1 or top-5 accuracy for classification. Mean average precision (mAP) for detection. Mean intersection over union (mIoU) for segmentation.
- A fixed preprocessing function shared by every model variant you evaluate.
The calibration images and the evaluation images must be disjoint. If they overlap, the quantized model looks better than it will on real data.
Two levels of checking
Level 1: output agreement
This check does not need labels. Run the same inputs through the original and the converted model and compare the outputs. It is fast and catches broken conversions immediately.
For classification, useful measures are:
- Top-1 agreement: the fraction of images where both models pick the same class.
- Maximum absolute difference in the output scores, which is most meaningful for float outputs.
- Cosine similarity of the output vectors, which ignores overall scale.
The following script compares a float32 ONNX model with its exported counterpart. It runs on random input, so it only tests that the export is numerically sound. Replace the input with real preprocessed images for a meaningful quantization check.
import numpy as np
import onnxruntime as ort
import torch
import torchvision
model = torchvision.models.mobilenet_v3_small(weights="DEFAULT").eval()
dummy = torch.randn(1, 3, 224, 224)
torch.onnx.export(
model, dummy, "mobilenet_v3_small.onnx",
input_names=["input"], output_names=["logits"], opset_version=17,
)
session = ort.InferenceSession(
"mobilenet_v3_small.onnx", providers=["CPUExecutionProvider"]
)
rng = np.random.default_rng(0)
agree, worst = 0, 0.0
n = 20
for _ in range(n):
x = rng.standard_normal((1, 3, 224, 224)).astype(np.float32)
with torch.no_grad():
ref = model(torch.from_numpy(x)).numpy()
got = session.run(["logits"], {"input": x})[0]
agree += int(ref.argmax() == got.argmax())
worst = max(worst, float(np.abs(ref - got).max()))
print(f"top-1 agreement: {agree}/{n}, max abs diff: {worst:.2e}")For a plain float32 export, expect a maximum difference around 1e-5 or smaller. A value near 1e-2 or more points to a real problem such as the model still being in training mode, a wrong opset, or a different preprocessing step baked into the graph.
Level 2: task metric on labeled data
Agreement alone is not enough. Two models can agree on most images and still differ on the hard ones that matter. Run the full evaluation set through each variant and compare the task metric.
A general-purpose evaluation loop for the quantized TensorFlow Lite model from the earlier chapter looks like this. It reads the input type from the model, so it works for both float and integer inputs.
import numpy as np
import tensorflow as tf
def evaluate_tflite(model_path, images, labels):
"""images: float32 array (N, 224, 224, 3) in the range the model expects
before quantization. labels: int array (N,)."""
interp = tf.lite.Interpreter(model_path=model_path)
interp.allocate_tensors()
inp = interp.get_input_details()[0]
out = interp.get_output_details()[0]
scale, zero_point = inp["quantization"]
correct = 0
for image, label in zip(images, labels):
x = image[np.newaxis, ...]
if inp["dtype"] != np.float32:
info = np.iinfo(inp["dtype"])
x = np.clip(np.round(x / scale + zero_point), info.min, info.max)
interp.set_tensor(inp["index"], x.astype(inp["dtype"]))
interp.invoke()
scores = interp.get_tensor(out["index"])
correct += int(scores.argmax() == label)
return correct / len(labels)The quantization field holds the scale and zero point that map real values to integers. If you feed a uint8 model raw float values without this step, the cast wraps around and the accuracy collapses to near chance. That is one of the most common false alarms.
How much loss is acceptable
There is no universal threshold. Decide it from the product requirement before you measure, not after. Typical starting points:
| Task | Metric | Commonly acceptable drop after int8 post-training quantization |
|---|---|---|
| Image classification | Top-1 accuracy | Under 1 percentage point |
| Object detection | mAP | 1 to 2 points, sometimes more for small objects |
| Segmentation | mIoU | 1 to 2 points |
| Keypoint or depth regression | Task error | Check visually and per range |
These are rules of thumb, not guarantees. Compact architectures with depthwise convolutions are known to quantize worse than large ResNet-style models. Detection and regression models are more sensitive because small numeric errors move boxes and values directly.
Also look beyond the average. Slice the evaluation set by lighting, image size, class, or object size, and compare per slice. A drop of 0.5 points overall can hide a 10 point drop on night images.
The validation workflow
The steps below form a loop. You stop when the metric meets your requirement.
Note the step "run same check on device." A desktop result does not always carry over. A hardware delegate such as a GPU or NPU may use different arithmetic, such as float16 or its own integer kernels, than the CPU interpreter you tested with.
Diagnosing a loss
When the metric is below target, narrow down the cause in this order, because the cheapest checks come first.
- Check the pipeline. Compare resize method, color order (RGB vs BGR), value range, and normalization between training and your test code. If the float32 model also scores poorly in your evaluation code, the problem is not quantization.
- Check the float conversion alone. Convert without quantization and evaluate. If accuracy already drops, the converter or an operator is responsible.
- Check the calibration data. Use real images, preprocessed exactly as at inference, and cover the variety you expect. Random data produces wrong activation ranges. A hundred representative images is a common starting point, and more rarely hurts.
- Find the sensitive layers. Compare intermediate outputs of the float and quantized models layer by layer and look for the first layer where the error jumps. Tools such as the TensorFlow Lite quantization debugger and the ONNX Runtime quantization debugging utilities exist for this purpose.
- Change the method. Options include per-channel weight quantization, keeping a few sensitive layers in float, trying a different calibration method such as percentile or entropy, or using quantization-aware training (QAT), which simulates rounding during fine-tuning so the weights adapt to it.
Edge cases to watch
- Output tensors that are also quantized. A
uint8output must be dequantized with its own scale and zero point before you apply a confidence threshold. Thresholds tuned on float outputs will behave differently on quantized scores. - Detection postprocessing. Non-maximum suppression and box decoding are often outside the converted graph. A quantized box regressor with coarse resolution can shift boxes by a pixel or two, which lowers mAP at high IoU thresholds even when top-line detection counts look the same.
- Non-determinism across backends. The same quantized model on a CPU, a GPU delegate, and an NPU can give slightly different scores. Allow small tolerances and compare metrics, not exact values.
- Small evaluation sets. With 200 images, one image changes accuracy by 0.5 points. Differences smaller than the noise of your test set are not evidence of anything.
- Calibration drift. If your input distribution changes after release, for example a new camera, the ranges chosen at calibration no longer fit. Re-run the check when the data source changes.
Make the check repeatable
Treat accuracy validation like a test in your build. Store the evaluation set version, preprocessing code, model file hash, and the resulting metrics together. Fail the pipeline when the metric drops below your threshold or when top-1 agreement with the float model falls below a limit you chose. This catches regressions when someone changes the converter version, the opset, or the calibration set.
Exercise
You quantize a MobileNetV2 to int8 and top-1 accuracy falls from 71% to 4% on your test set. Output agreement with the float model is also near zero. List the first two things you check and explain why you check them before changing the quantization method.
Show answer
First, check the preprocessing and input handling: whether the uint8 input is quantized with the model's scale and zero point, and whether resize, color order, and normalization match training. Second, convert the model to TensorFlow Lite without quantization and evaluate it. A collapse to near chance is almost never normal quantization error, which usually costs a point or two. It points to a pipeline or conversion fault such as wrapped integer casts or a mismatched normalization. These checks are cheap and rule out causes unrelated to quantization, so changing calibration or method first would waste effort and could mask the real bug.
Exercise
Your quantized detector loses only 0.4 mAP overall, but a customer reports it misses small objects in dim light. What do you do, and why is the overall number not enough?
Show answer
Slice the evaluation set by object size and lighting, and compute mAP for each slice for both the float and quantized models. The overall average is dominated by the large, well-lit majority, so a large loss on a small subset can be hidden. If the slice shows a large drop, inspect the calibration data for missing dim-light images, add them, recalibrate, and consider keeping the sensitive layers in float or using quantization-aware training.