Sub topic 6
Checking that outputs match the original model
This chapter shows how to confirm that an exported or optimized model still gives the same answers as the PyTorch model it came from. It assumes you have finished the export and ONNX Runtime chapters. You have resnet50.onnx, you can create an InferenceSession, and you know the preprocessing the model expects. A GPU is useful but not required, because the same checks work on the CPU provider.
Why a fast model can be wrong
A model that runs quickly but returns different predictions is a regression. Export and optimization can change results in several ways:
- Floating-point reordering. Floating-point addition is not associative. Operator fusion, different convolution algorithms, and different reduction orders change the last few bits of every output.
- Reduced-precision math. On NVIDIA Ampere and newer GPUs, convolutions and matrix multiplies can use TF32, which keeps fewer mantissa bits than FP32. FP16 and INT8 lose more.
- Export mistakes. Calling
.eval()is easy to forget. Without it, batch norm uses batch statistics and dropout stays active, so the exported graph does not match the model you trained. - Pipeline mismatches. Different resize interpolation, channel order, or normalization constants change the input, so every output changes too.
The first two causes produce small, expected differences. The last two produce large ones. Your job is to tell them apart.
Compare raw logits first
Compare the model's raw output, the logits, before any softmax or argmax. Softmax squashes large differences when one class dominates. Argmax hides everything except the winner. Comparing logits keeps the most information.
NumPy's assert_allclose(actual, desired, rtol, atol) passes when |actual - desired| <= atol + rtol * |desired| holds for every element. The relative term handles large logits and the absolute term handles values near zero. For FP32 on the same device type, rtol=1e-3 and atol=1e-4 are reasonable starting points. Treat them as a starting point, not a standard. Loosen them only after you understand the measured difference.
A reusable parity check
The script below sends the same batches through both runtimes. It reports several metrics, and it asserts closeness only after printing them, so a failure comes with numbers.
import numpy as np
import onnxruntime as ort
import torch
import torchvision
model = torchvision.models.resnet50(
weights=torchvision.models.ResNet50_Weights.DEFAULT
).eval()
sess = ort.InferenceSession(
"resnet50.onnx",
providers=["CUDAExecutionProvider", "CPUExecutionProvider"],
)
print("providers:", sess.get_providers())
def parity_report(ref, out, k=5):
diff = np.abs(ref - out)
cos = (ref * out).sum(axis=1) / (
np.linalg.norm(ref, axis=1) * np.linalg.norm(out, axis=1)
)
top1 = ref.argmax(axis=1) == out.argmax(axis=1)
topk_ref = np.argsort(-ref, axis=1)[:, :k]
topk_out = np.argsort(-out, axis=1)[:, :k]
overlap = np.mean(
[len(set(a) & set(b)) / k for a, b in zip(topk_ref, topk_out)]
)
return {
"max_abs_diff": float(diff.max()),
"mean_abs_diff": float(diff.mean()),
"min_cosine": float(cos.min()),
"top1_agreement": float(top1.mean()),
f"top{k}_overlap": float(overlap),
}
rng = np.random.default_rng(0)
for batch in (1, 4, 8):
x = rng.standard_normal((batch, 3, 224, 224)).astype(np.float32)
with torch.no_grad():
ref = model(torch.from_numpy(x)).numpy()
out = sess.run(None, {"input": x})[0]
print(batch, parity_report(ref, out))
np.testing.assert_allclose(ref, out, rtol=1e-3, atol=1e-4)
print("all batch sizes within tolerance")The loop over batch sizes matters. The export used a dynamic batch axis, and a different batch size can select a different kernel. A model that matches at batch 1 can drift at batch 8.
If the CUDA provider is active and the assertion fails by a small amount, TF32 is a likely cause. Try the CPU provider on the same model. If the CPU result matches, the model and export are fine, and the GPU path is just less precise. In that case, decide whether the difference is acceptable. Do not hide it with a looser tolerance and move on.
Why random inputs are not enough
Random noise is a good smoke test, but it is a poor acceptance test. The network was trained on natural images, and noise produces flat, low-confidence logits. In that regime many classes have nearly equal scores, so tiny numeric differences flip the argmax even when the model is healthy.
For acceptance, use a few hundred real images from your own domain. Run them through your real preprocessing, which the preprocessing chapter covered. Feed identical preprocessed tensors to both runtimes. Do not preprocess separately for each side, or you test your resize code instead of the model.
Look at margins before you panic
When the top-1 class differs on some inputs, look at how close the reference model's top two scores were. If the gap is smaller than the numeric error, the flip is explained, because the model had no real preference.
def explain_mismatches(ref, out):
top2 = np.sort(ref, axis=1)[:, -2:]
gap = top2[:, 1] - top2[:, 0]
max_err = np.abs(ref - out).max(axis=1)
bad = ref.argmax(axis=1) != out.argmax(axis=1)
for i in np.flatnonzero(bad):
verdict = "explained by noise" if gap[i] <= 2 * max_err[i] else "INVESTIGATE"
print(f"sample {i}: gap={gap[i]:.5f} max_err={max_err[i]:.5f} -> {verdict}")
return bad.sum()A mismatch with a large gap is a real problem. Look for a preprocessing difference, a missing .eval(), or an unsupported operator that fell back to different behavior.
Models that do not output class logits
For detection and segmentation, raw tensor comparison is still useful for the backbone and heads. The final result depends on postprocessing, though, and that is where small differences get amplified:
- Detection. Compare the boxes after non-maximum suppression. Match detections by IoU (for example above 0.9) and compare their scores and classes. A box that sits just above or below the confidence threshold can appear or disappear, so compare counts with some tolerance.
- Segmentation. Compare per-pixel agreement of the argmax mask, or mean IoU between the two masks. Expect disagreement mainly along object edges.
- Embeddings. Use cosine similarity. For retrieval you care about ranking, so check that nearest-neighbor results agree.
What to record
Run the parity check again every time something in the stack changes. That includes a new provider, FP16, a new TensorRT version, and a new export. Save the reference outputs for a fixed set of inputs to disk, so you can compare against them without reloading PyTorch. Log the metrics with the provider list, the batch size, and the library versions. A regression is much easier to find when you can see which change introduced it.
| Check | What it catches | Typical threshold for FP32 |
|---|---|---|
| `assert_allclose` on logits | Export bugs, wrong preprocessing | `rtol=1e-3`, `atol=1e-4` |
| Minimum cosine similarity | Systematic output drift | Above 0.9999 |
| Top-1 agreement on real images | Decision changes | At or near 100% |
| Top-5 overlap | Ranking changes | At or near 100% |
| Mismatch margin analysis | Whether flips are noise | Every flip explained |
Exercise
Your ONNX model passes assert_allclose at batch size 1, but with the CUDA provider you see a top-1 mismatch on 2 of 500 real images, with a max absolute logit difference of 3e-3. For both images, the reference model's top-two gap is 1e-3. What should you conclude, and what would change your answer?
Show answer
The flips are explained by numeric noise. The top-two gap (1e-3) is smaller than twice the observed error (6e-3), so the model had no real preference between those classes, and tiny differences, possibly from TF32 on the GPU, decided the winner. Confirm by running the CPU provider, which should match more closely. The answer would change if either image had a large gap, if mismatches were more frequent, or if the mismatches appeared at larger batch sizes, because those point to a preprocessing or export problem rather than noise.