Sub topic 15
Verifying the optimised pipeline matches the reference
This chapter assumes you have built a reference pipeline and applied some optimisations from earlier chapters. These include JPEG draft decoding, keeping data as uint8, worker processes, and GPU normalisation. You should be comfortable with NumPy arrays, PyTorch tensors, and the Image.draft and DataLoader APIs. Here you will check that the faster pipeline still feeds the model what it expects.
Why optimisation can change the input
A faster pipeline that quietly changes its output is a bug. The model was trained or validated on inputs from one pipeline. If the serving or training pipeline differs in resize method, channel order, or value range, accuracy drops, and nothing crashes to tell you. This is a form of train/serve skew.
Some optimisations cannot change values. Moving work to another process or thread is one. Others change them by design. Draft decoding downscales inside the JPEG decoder, which is not the same arithmetic as decoding at full size and then resizing. Your job is to separate the two kinds and to bound the second kind.
Exact changes and approximate changes
| Optimisation | Expected effect on values | How to check |
|---|---|---|
| More workers, prefetching, pinned memory | None (order may differ if shuffled) | Exact equality per sample |
| Normalising on the GPU instead of the CPU | Float rounding only | `torch.allclose` with a small tolerance |
| Keeping uint8 until the last step | None, if the reference rounds the same way | Exact equality on uint8 tensors |
| JPEG draft decoding | Small pixel differences | Pixel error statistics and a model-level check |
| Different interpolation or antialiasing | Visible differences | Treat as a different pipeline and re-evaluate |
| Cached or re-encoded data (lossy) | Compression noise | Pixel statistics and a model-level check |
Exact changes get exact or near-exact tests. Approximate changes get a tolerance that you choose on purpose and justify with a model-level measurement.
Step 1: write the reference as simply as possible
The reference should be slow, obvious, and correct. It uses full-size decode, one resize call, and CPU normalisation in float32. Do not optimise it. It is your definition of correct.
import numpy as np
import torch
from PIL import Image
MEAN = torch.tensor([0.485, 0.456, 0.406]).view(1, 3, 1, 1)
STD = torch.tensor([0.229, 0.224, 0.225]).view(1, 3, 1, 1)
def reference(path, size=(224, 224)):
with Image.open(path) as im:
im = im.convert("RGB").resize(size, Image.Resampling.BILINEAR)
arr = np.asarray(im, dtype=np.float32) / 255.0
x = torch.from_numpy(arr).permute(2, 0, 1).unsqueeze(0)
return (x - MEAN) / STD
def optimised(path, size=(224, 224), device="cpu"):
with Image.open(path) as im:
im.draft("RGB", (size[0] * 2, size[1] * 2))
im = im.convert("RGB").resize(size, Image.Resampling.BILINEAR)
arr = np.array(im, dtype=np.uint8)
u8 = torch.from_numpy(arr).permute(2, 0, 1).unsqueeze(0).to(device)
x = u8.float() / 255.0
return (x - MEAN.to(device)) / STD.to(device)Both functions return a 1 x 3 x 224 x 224 float tensor. Keep their signatures identical so one test harness can call either.
Step 2: check one stage at a time
If you compare only the final tensors and they differ, you do not know which change caused it. Compare after each stage, and change one thing at a time.
The normalisation stage is the easiest to test exactly. Feed the same uint8 tensor through the CPU and device paths and compare:
import torch
MEAN = torch.tensor([0.485, 0.456, 0.406]).view(1, 3, 1, 1)
STD = torch.tensor([0.229, 0.224, 0.225]).view(1, 3, 1, 1)
def normalise_cpu(u8):
return (u8.float() / 255.0 - MEAN) / STD
def normalise_device(u8, device):
mean = MEAN.to(device) * 255
std = STD.to(device) * 255
return (u8.to(device).float() - mean) / std
if __name__ == "__main__":
device = "cuda" if torch.cuda.is_available() else "cpu"
torch.manual_seed(0)
u8 = torch.randint(0, 256, (8, 3, 224, 224), dtype=torch.uint8)
a = normalise_cpu(u8)
b = normalise_device(u8, device).cpu()
print("max abs diff:", (a - b).abs().max().item())
assert torch.allclose(a, b, atol=1e-4)The two paths use different operation orders, so the results can differ in the last float bits. They should never differ by more than a tiny tolerance. If they do, you have a real bug, such as swapped mean and std or a missing * 255.
Step 3: measure approximate differences in pixel units
For draft decoding, compare the uint8 tensors right after the resize. Float differences after normalisation are hard to read, because the scale depends on the standard deviation. Convert the difference back to pixel levels (0 to 255) so the numbers mean something.
import os
import tempfile
import numpy as np
import torch
from PIL import Image, ImageDraw
# reference() and optimised() are defined in Step 1.
STD = torch.tensor([0.229, 0.224, 0.225]).view(1, 3, 1, 1)
def pixel_stats(a, b):
"""a, b: normalised float tensors from the two pipelines."""
levels = (a - b).abs() * STD * 255.0 # back to 0..255 pixel units
flat = levels.flatten()
return {
"mean": flat.mean().item(),
"p99": torch.quantile(flat[:100000], 0.99).item(),
"max": flat.max().item(),
}
def make_test_jpeg(path):
h, w = 1536, 2048
yy, xx = np.mgrid[0:h, 0:w]
base = np.stack([xx * 255 // w, yy * 255 // h, (xx + yy) * 255 // (w + h)], axis=-1)
im = Image.fromarray(base.astype(np.uint8))
d = ImageDraw.Draw(im)
d.ellipse((600, 400, 1400, 1100), outline=(255, 255, 255), width=12)
im.save(path, quality=90)
if __name__ == "__main__":
with tempfile.TemporaryDirectory() as tmp:
path = os.path.join(tmp, "test.jpg")
make_test_jpeg(path)
print(pixel_stats(reference(path), optimised(path)))The p99 line takes the 99th percentile over the first 100,000 values, which keeps torch.quantile within its input size limit. Report the mean, a high percentile, and the maximum. A tiny mean with a large maximum usually means a localised difference, such as edges where the two resize paths disagree. A large mean means a systematic difference, such as the wrong interpolation filter or a colour-order swap.
Run the comparison over a few hundred real images from your own dataset, not one synthetic file. Include the awkward ones: very large, very small, grayscale, CMYK, progressive JPEG, PNG with transparency, and images with EXIF rotation.
Step 4: check what the model sees
Small pixel differences matter only if they change predictions. Run both pipelines through the same model in evaluation mode and compare outputs, not just inputs:
- Top-1 agreement: the fraction of images where both pipelines predict the same class.
- Logit similarity: the cosine similarity or mean absolute difference between output vectors.
- Task metric: the accuracy, mAP, or loss on a validation set, computed with each pipeline.
Pick the tolerance before you look at the result. For example, require top-1 agreement above 99.5% and a validation accuracy change within the noise you see between random seeds. If draft decoding exceeds your tolerance, raise the margin (request 4 times the target size instead of 2 times), or drop draft mode for that model.
Call model.eval() and use torch.no_grad() for this comparison. Otherwise dropout and batch-norm statistics will create differences that have nothing to do with the pipeline.
Common errors
- Comparing different samples. With
shuffle=Trueand several workers, the two loaders return images in different orders. Compare by file path, or disable shuffling for the test. - Hidden randomness. Random crops or flips make two runs differ legitimately. Disable augmentation for parity tests, or seed the random generator identically and test augmentation separately.
- Channel order and layout. HWC versus CHW, and RGB versus BGR, produce errors far larger than any rounding. A mean pixel error in the tens points here.
- Value range. Dividing by 255 twice, or not at all, shows up as an input range far from the reference. Print
min,max,mean, andstdper channel for both outputs. - Reading uint8 as signed. Converting to
int8or subtracting a float mean from a uint8 tensor in place can wrap values around. - Wrong dtype tolerance. Using
atol=1e-8on float32 data fails for harmless rounding. Usingatol=0.1hides real bugs. Use 1e-4 to 1e-5 for float32 normalisation. - Testing on one image. A synthetic image or a single photo can pass while edge-case formats fail.
- Skipping the final system. A correct function can still be misused by the
DataLoader. Run the comparison through the real loader as well, with the real workers, collate function, and device transfer.
Keep the check as a regression test
Parity is not a one-time task. Library upgrades, such as a new Pillow or a different libjpeg build, can change decoder output. Store a small fixed set of test images in the repository, record the expected statistics, and run the comparison in continuous integration. Fail the build when mean error, high-percentile error, or top-1 agreement leaves its range.
Exercise
Your optimised pipeline normalises on the GPU. The final tensors differ from the reference by a maximum of 3e-6, but the mean pixel error measured after the resize is 0.4 levels. Which difference needs investigation, and why?
Show answer
Neither is an error by itself. A float difference of 3e-6 is rounding from a different operation order, and a tolerance such as 1e-4 covers it. A mean difference of 0.4 pixel levels after the resize is the kind of small error draft decoding introduces. Confirm it matters (or not) by checking top-1 agreement and the validation metric against a tolerance chosen in advance.
Exercise
A parity test shows a mean pixel error of about 40 levels between the two pipelines, even with draft mode switched off. Name two likely causes and one check for each.
Show answer
Likely causes are a channel-order swap (RGB versus BGR) and a value-range mistake (for example, missing division by 255 or normalising twice). To check channel order, compare the per-channel means of both outputs, or swap the channels in one tensor and see if the error drops. To check the range, print min, max, and mean per channel for both outputs and look for a factor of 255 or a shifted centre.