Sub topic 1
What "fast" means: latency versus throughput
Prerequisites
This chapter assumes basic Python and NumPy, some experience with a deep learning framework such as PyTorch, and a general idea of how an image classification model works. The code runs on a CPU, but the GPU sections need an NVIDIA GPU with CUDA drivers.
Latency and throughput
Latency is the time from sending one input to receiving its output, usually measured in milliseconds. Throughput is how many inputs the system finishes per second. A web service that answers single requests cares about latency. A batch job that labels a million photos cares about throughput. Batching raises throughput but often increases the latency of each request, so choose the metric your application needs before you optimize.
The ONNX format
ONNX (Open Neural Network Exchange) is a file format that stores a model as a graph of operators, such as convolution and ReLU, with the weights attached. Many frameworks and runtimes read it. You can train in PyTorch and run the same model in ONNX Runtime without rewriting it.
Exporting a PyTorch model to ONNX
import torch
import torchvision
model = torchvision.models.resnet50(weights=torchvision.models.ResNet50_Weights.DEFAULT).eval()
dummy = torch.randn(1, 3, 224, 224)
torch.onnx.export(
model, dummy, "resnet50.onnx",
input_names=["input"], output_names=["logits"],
dynamic_axes={"input": {0: "batch"}, "logits": {0: "batch"}},
opset_version=17,
).eval() turns off training-only behavior such as dropout. The dummy input traces the graph. dynamic_axes marks dimension 0 as variable, so one file accepts any batch size.
Running the model with ONNX Runtime
import numpy as np
import onnxruntime as ort
sess = ort.InferenceSession(
"resnet50.onnx",
providers=["CUDAExecutionProvider", "CPUExecutionProvider"],
)
print(sess.get_providers())
x = np.random.rand(1, 3, 224, 224).astype(np.float32)
logits = sess.run(None, {"input": x})[0]
print(logits.shape)An execution provider is a backend that runs the graph. ONNX Runtime tries providers in list order and assigns unsupported operators to the next one. The printed list shows which providers are active.
Preprocessing and postprocessing
The model expects float32 tensors in NCHW layout, normalized with ImageNet mean and standard deviation. Preprocessing must match training exactly, or accuracy drops without an error. Postprocessing converts logits to probabilities with softmax and selects the top class.
def preprocess(img_rgb):
"""img_rgb: 224x224x3 uint8 RGB image. Returns a 1x3x224x224 float32 tensor."""
x = img_rgb.astype(np.float32) / 255.0
x = (x - np.array([0.485, 0.456, 0.406], np.float32)) / np.array([0.229, 0.224, 0.225], np.float32)
return x.transpose(2, 0, 1)[None]
def top1(logits):
e = np.exp(logits - logits.max(axis=1, keepdims=True))
probs = e / e.sum(axis=1, keepdims=True)
return int(probs.argmax(axis=1)[0]), float(probs.max())Checking that outputs match the original model
An optimized model must still produce nearly the same numbers. Compare its output with PyTorch on the same input:
import torch
with torch.no_grad():
ref = model(torch.from_numpy(x)).numpy()
np.testing.assert_allclose(ref, logits, rtol=1e-3, atol=1e-4)
print("top-1 match:", int(ref.argmax()) == int(logits.argmax()))Exercise
A real-time camera app processes one frame at a time. Should it optimize latency or throughput, and why?
Show answer
Latency. Each frame must return quickly. Large batches would make every frame wait for the others to fill the batch.