Sub topic 5
Preprocessing and postprocessing around the model
This chapter assumes you can export a PyTorch model to ONNX and run it in an ONNX Runtime InferenceSession. It also assumes you know NumPy array shapes and the basic idea of an image classifier. The model graph is only one part of a vision pipeline. Code before and after it often decides whether the outputs are correct, and it can account for much of the total latency.
Why the code around the model matters
A classifier such as ResNet-50 does not accept a JPEG file. It accepts a float32 tensor of shape (N, 3, 224, 224) whose values were scaled and normalized the way the model saw them during training. If you export only the network, the ONNX file contains none of the image decoding, resizing, or normalization. You must reproduce those steps exactly.
Two things follow from this:
- Correctness. A wrong channel order or a missing normalization step produces valid-looking logits that are quietly wrong. No error is raised.
- Speed. Decoding and resizing run on the CPU by default. After you speed up the model with CUDA or TensorRT, this work can dominate end-to-end time.
The preprocessing contract
The pretrained torchvision ResNet-50 expects this sequence:
- Decode the image to RGB, with 8-bit values from 0 to 255.
- Resize the shorter side to 256 pixels.
- Center-crop to 224 x 224.
- Convert to float32 and divide by 255, so values fall between 0 and 1.
- Subtract the per-channel mean
[0.485, 0.456, 0.406]and divide by the per-channel standard deviation[0.229, 0.224, 0.225]. - Reorder from height-width-channel (HWC) to channel-height-width (CHW), then add a batch dimension.
The mean and standard deviation values come from the ImageNet training set. If you use a different model, read its documentation or its training configuration. Never copy the values from another model.
import numpy as np
from PIL import Image
MEAN = np.array([0.485, 0.456, 0.406], dtype=np.float32).reshape(1, 1, 3)
STD = np.array([0.229, 0.224, 0.225], dtype=np.float32).reshape(1, 1, 3)
def preprocess(path, size=224, resize_to=256):
img = Image.open(path).convert("RGB")
# Resize so the shorter side equals resize_to, keeping the aspect ratio.
w, h = img.size
scale = resize_to / min(w, h)
img = img.resize((round(w * scale), round(h * scale)), Image.BILINEAR)
# Center crop to size x size.
w, h = img.size
left = (w - size) // 2
top = (h - size) // 2
img = img.crop((left, top, left + size, top + size))
arr = np.asarray(img, dtype=np.float32) / 255.0
arr = (arr - MEAN) / STD
arr = arr.transpose(2, 0, 1) # HWC -> CHW
return np.ascontiguousarray(arr[None]) # add batch dimension
if __name__ == "__main__":
demo = Image.fromarray(
np.random.randint(0, 256, (300, 400, 3), dtype=np.uint8)
)
demo.save("demo.jpg")
x = preprocess("demo.jpg")
print(x.shape, x.dtype)The final np.ascontiguousarray call matters. A transpose returns a view with unusual strides. ONNX Runtime accepts such arrays, but a contiguous copy is predictable and is what the GPU copy path expects.
Common preprocessing errors
These mistakes are frequent, and none of them raises an exception.
| Mistake | Symptom | How to catch it |
|---|---|---|
| Using BGR (OpenCV default) instead of RGB | Accuracy drops a few points, colors are swapped | Compare a decoded array against PIL's output |
| Skipping the division by 255 | Logits are huge and the top class is almost random | Print the min and max of the input tensor |
| Wrong resize method | Small accuracy loss that varies with image content | Use the same interpolation as training |
| Float64 input | ONNX Runtime raises a type error, or you pay for a cast | Check `x.dtype` is `float32` |
| Forgetting the batch dimension | Shape mismatch error | Print `x.shape` before calling `run` |
| Wrong layout (HWC instead of CHW) | Shape error, or silent garbage if the dimensions happen to match | Assert the shape against the session's input metadata |
Resize interpolation deserves attention. PIL, OpenCV, and torchvision implement "bilinear" differently, especially when shrinking an image, because PIL applies antialiasing and OpenCV does not by default. The differences are small per pixel, but they can shift logits enough to break a strict parity check. If your service uses a different library than your training code, test this explicitly.
You can read the expected input from the session instead of hard-coding it:
import onnxruntime as ort
sess = ort.InferenceSession("resnet50.onnx", providers=["CPUExecutionProvider"])
inp = sess.get_inputs()[0]
print(inp.name, inp.shape, inp.type)For a model exported with a dynamic batch axis, this prints a shape such as ['batch', 3, 224, 224] and the type tensor(float). The string 'batch' is the symbolic name of the dynamic axis. The other dimensions are fixed.
Postprocessing a classifier
The ONNX model returns raw logits. For classification you usually want the top-k classes and, if you report confidence, probabilities from a softmax.
Compute softmax in a numerically stable way. Subtract the row maximum before exponentiating, otherwise large logits overflow.
import numpy as np
def softmax(logits):
z = logits - logits.max(axis=-1, keepdims=True)
e = np.exp(z)
return e / e.sum(axis=-1, keepdims=True)
def top_k(logits, k=5):
probs = softmax(logits)
idx = np.argsort(-probs, axis=-1)[:, :k]
return [
[(int(i), float(probs[row, i])) for i in idx[row]]
for row in range(probs.shape[0])
]
logits = np.array([[2.0, 1.0, 0.1, 5.0, -1.0]], dtype=np.float32)
print(top_k(logits, k=3))If you only need the ranking, skip the softmax. It does not change the order of the classes. Class indices map to names through a label file, which for ImageNet is a list of 1,000 names in a fixed order. Keep that file versioned with the model, since a reordered list gives wrong names with correct indices.
Postprocessing for detection
Detection models return boxes, scores, and class IDs, often thousands of candidates per image. Postprocessing then does three jobs:
- Filter candidates below a confidence threshold.
- Run non-maximum suppression (NMS), which removes overlapping boxes for the same object, keeping the highest-scoring one.
- Rescale box coordinates from the model input size back to the original image size.
The third step is a common source of bugs. If you letterbox the image (resize with preserved aspect ratio and pad), you must undo both the scale and the padding offset. Store the scale and padding for each image when you preprocess it, and apply them in reverse when you postprocess.
You can include NMS inside the ONNX graph, because ONNX has a NonMaxSuppression operator. The trade-off is worth knowing. A graph with NMS is one self-contained file, but NMS has data-dependent output sizes, and some execution providers cannot run it. TensorRT may then hand that node to another provider, which adds a device copy. Keeping NMS in Python or in a separate step is often simpler to debug.
Where the time goes
Measure the stages separately before optimizing any of them.
import time
import numpy as np
def timed(fn, *args, repeats=50):
fn(*args) # warmup
start = time.perf_counter()
for _ in range(repeats):
fn(*args)
return (time.perf_counter() - start) / repeats * 1000.0
print("preprocess ms:", timed(preprocess, "demo.jpg"))Run the same helper on the session call and on the postprocessing. On a fast GPU, FP16 inference of ResNet-50 can take only a few milliseconds, while decoding a large JPEG and resizing it can take longer. Typical remedies are:
- Use a smaller decode size, or decode with a library that supports reduced-size JPEG decoding.
- Run preprocessing in worker processes so it overlaps with GPU work.
- Move normalization into the model. You can wrap the network so that it accepts uint8 input and normalizes inside the graph. This also shrinks the host-to-device copy by a factor of four, since uint8 uses one byte per value and float32 uses four.
- Use a GPU image library for decode and resize, if the pipeline is large enough to justify the dependency.
Moving normalization into the graph has a cost. The exported model no longer matches the training-time interface, so document the new input contract clearly and rerun your parity check.
Pipeline overview
The diagram shows where each step runs by default and which steps can move onto the GPU.
Checklist before benchmarking or comparing outputs
- The preprocessing code matches the training pipeline, including interpolation and normalization constants.
- The input is float32 (or uint8 if you moved normalization into the graph), contiguous, and in the layout the session reports.
- Postprocessing uses a stable softmax and a versioned label file.
- Detection postprocessing reverses every geometric change made during preprocessing.
- Stages are timed separately, so you know which one to optimize.
Exercise
A teammate switches a service from PIL to OpenCV for image loading, with no other changes. Accuracy on a validation set drops by about two points, and no errors appear. Name two likely causes and one way to confirm each.
Show answer
First, OpenCV loads images in BGR order while the model expects RGB. Confirm by comparing the first pixel's channels from both loaders, or convert with cv2.cvtColor(img, cv2.COLOR_BGR2RGB) and see whether accuracy recovers. Second, resize interpolation differs: PIL antialiases when shrinking and OpenCV's default bilinear does not. Confirm by feeding the same image through both pipelines and comparing the preprocessed tensors with np.abs(a - b).max(), or by using the same resize implementation as training.
Exercise
Why does the stable softmax subtract the row maximum, and does it change the predicted class?
Show answer
Subtracting the maximum keeps the largest exponent at zero, so np.exp cannot overflow for large logits. The shift cancels in the ratio, so the probabilities are unchanged and the predicted class is the same.