Sub topic 15
Verifying the Optimised Pipeline Matches the Reference
This chapter assumes you know basic Python, NumPy arrays, image tensors, and PyTorch Dataset and DataLoader. It also assumes you have a reference pipeline that is correct but slower, and an optimised pipeline that should produce equivalent model inputs.
Optimisation is incomplete until you check equivalence. A faster pipeline can silently change image values, channel order, dimensions, data types, or normalisation. These changes may reduce model accuracy even when the images look identical on screen.
Define what “matches” means
Exact equality is often too strict. Different decoders, interpolation implementations, or operation orders can produce small floating-point differences. Instead, define an acceptance rule for each output:
| Property | Typical check | Why it matters |
|---|---|---|
| Shape | Exact equality | The model expects a fixed layout |
| Data type | Exact equality or an allowed type | It affects memory and arithmetic |
| Range | Minimum and maximum bounds | It detects missing or repeated scaling |
| Pixel values | Maximum or mean absolute error | It detects preprocessing differences |
| Model output | Task-specific tolerance or metric | It confirms end-to-end behavior |
For example, compare images before model inference. If the optimised pipeline uses JPEG draft decoding, its pixels may not exactly match full-resolution decoding followed by resizing. Decide whether the difference is acceptable for your model rather than assuming it is harmless.
Compare tensors with useful diagnostics
A single Boolean result hides the reason for a mismatch. Report the largest difference, its location, and the fraction of elements outside the tolerance.
import numpy as np
def compare_arrays(reference, candidate, atol=1e-3, rtol=1e-4):
reference = np.asarray(reference)
candidate = np.asarray(candidate)
if reference.shape != candidate.shape:
return {
"ok": False,
"reason": f"shape mismatch: {reference.shape} != {candidate.shape}",
}
if reference.dtype != candidate.dtype:
print(f"warning: dtypes differ: {reference.dtype} != {candidate.dtype}")
ref = reference.astype(np.float32)
got = candidate.astype(np.float32)
difference = np.abs(ref - got)
allowed = atol + rtol * np.abs(ref)
failures = difference > allowed
index = np.unravel_index(np.argmax(difference), difference.shape)
return {
"ok": not failures.any(),
"max_abs_error": float(difference.max()),
"mean_abs_error": float(difference.mean()),
"failure_fraction": float(failures.mean()),
"worst_index": index,
"reference_value": float(ref[index]),
"candidate_value": float(got[index]),
}
reference = np.array([[[0.1, 0.2], [0.3, 0.4]]], dtype=np.float32)
candidate = reference + 1e-5
print(compare_arrays(reference, candidate))Use atol for a fixed absolute difference and rtol for an error proportional to the reference value. Choose tolerances from observed decoder and interpolation behavior, then record them in the test.
Check each stage, not only the final model
Compare the pipelines at several boundaries:
- After decoding, check channel order, dimensions, and color mode.
- After resizing, compare shape, range, and pixel error.
- After conversion to a tensor, check layout such as
C x H x W. - After normalisation, check representative values and summary statistics.
- After batching, check batch shape and sample ordering.
- Finally, compare model outputs or an evaluation metric.
A mismatch first appearing after one stage narrows the search. Common causes include RGB versus BGR ordering, applying division by 255 twice, converting uint8 to floating point too early, and resizing before versus after a crop.
Build a regression test set
Keep a small, fixed set of representative files under version control or in stable test storage. Run the reference and optimised pipelines on the same paths and compare every output. For stochastic augmentation, use the same random seed or disable randomness during the parity test.
Also compare performance separately. A pipeline can pass numerical checks but still be slower because worker startup, disk access, or host-to-device copies dominate.
Exercise
The optimised output has the expected shape, but its values are about 255 times larger than the reference. What should you inspect first?
Show answer
Inspect scaling and normalisation. One pipeline probably divides uint8 values by 255 while the other does not, or one pipeline applies that conversion twice.