Sub topic 6
Checking That Outputs Match the Original Model
This chapter assumes basic Python, NumPy, PyTorch, and image-model concepts. It also assumes that you exported the same PyTorch model to resnet50.onnx. Numerical parity means that two implementations produce outputs close enough for the intended use.
Why parity matters
An optimized model can run faster while producing different results because of:
- Different preprocessing, such as channel order or normalization.
- A changed input shape or data type.
- An unsupported operator replaced by another implementation.
- Floating-point rounding.
- FP16 or INT8 reduced precision.
- The original model still being in training mode.
Compare the complete pipeline, not only the model graph. Use the same input tensor, preprocessing values, output interpretation, and batch size.
| Check | What it can reveal |
|---|---|
| Output shape | Incorrect model interface or dynamic shape |
| Maximum absolute difference | Largest numerical change |
| Relative difference | Change compared with output magnitude |
| Top-1 class | Whether the decision changed |
Prepare a deterministic comparison
Call eval() on the PyTorch model. This disables training-time behavior such as dropout. Use a fixed random seed while testing, although deterministic input is not required for every production workload.
The example below compares PyTorch with ONNX Runtime on CPU. Change the provider only after the CPU comparison passes.
import numpy as np
import torch
import torchvision
import onnxruntime as ort
torch.manual_seed(7)
np.random.seed(7)
model = torchvision.models.resnet50(
weights=torchvision.models.ResNet50_Weights.DEFAULT
).eval()
session = ort.InferenceSession(
"resnet50.onnx",
providers=["CPUExecutionProvider"],
)
x = np.random.rand(2, 3, 224, 224).astype(np.float32)
with torch.no_grad():
reference = model(torch.from_numpy(x)).numpy()
optimized = session.run(["logits"], {"input": x})[0]
if reference.shape != optimized.shape:
raise AssertionError(
f"shape mismatch: PyTorch {reference.shape}, "
f"ONNX Runtime {optimized.shape}"
)
np.testing.assert_allclose(
reference,
optimized,
rtol=1e-3,
atol=1e-4,
)
reference_classes = reference.argmax(axis=1)
optimized_classes = optimized.argmax(axis=1)
print("maximum absolute difference:",
np.max(np.abs(reference - optimized)))
print("top-1 matches:",
np.mean(reference_classes == optimized_classes))atol is the absolute tolerance. It limits the allowed difference near zero. rtol is the relative tolerance. It scales the allowed difference for larger values. These values are starting points, not universal guarantees.
Test the real operating conditions
Repeat the comparison with representative images, batch sizes, and input resolutions. For classification, compare logits and final classes. For detection or segmentation, also compare boxes, scores, masks, and postprocessing results.
When testing TensorRT, compare the TensorRT provider with the CPU or CUDA provider, then compare both with PyTorch. FP16 usually needs a looser tolerance than FP32. INT8 requires task-level accuracy tests on a validation set, not just one random batch.
Exercise
Why should you compare the same preprocessed input in both runtimes?
Show answer
Different preprocessing can create output differences that look like model or runtime errors.