Sub topic 2
Benchmarking Inference, Provider Selection, and I/O Binding
This chapter assumes you have exported a model to resnet50.onnx and can run Python with onnxruntime-gpu and NumPy installed. The GPU sections also assume an NVIDIA driver and CUDA runtime that match your ONNX Runtime build.
Benchmarking with warmup and percentile latencies
Latency is the time for one inference call. A single timing is noisy, so the first calls include one-time setup such as memory allocation and kernel selection. Run warmup iterations first, then time many runs and report percentiles. The p50 value is the median, and p95 and p99 show the slow tail that users notice.
import time
import numpy as np
import onnxruntime as ort
def bench(sess, x, warmup=20, iters=200):
feed = {"input": x}
for _ in range(warmup):
sess.run(None, feed)
times = []
for _ in range(iters):
start = time.perf_counter()
sess.run(None, feed)
times.append((time.perf_counter() - start) * 1000.0)
return np.percentile(times, [50, 95, 99])
sess = ort.InferenceSession(
"resnet50.onnx",
providers=["CUDAExecutionProvider", "CPUExecutionProvider"],
)
x = np.random.rand(1, 3, 224, 224).astype(np.float32)
print("p50/p95/p99 ms:", bench(sess, x))Execution providers and provider fallback
An execution provider is a backend that runs graph nodes, such as CPU, CUDA, or TensorRT. You pass providers in priority order. ONNX Runtime assigns each node to the first provider that supports it, so the list above runs on CUDA and falls back to CPU for unsupported nodes. Always call sess.get_providers() to confirm which providers loaded. A silent fallback to CPU can make a benchmark look far slower than the GPU can run.
Graph optimization levels and operator fusion
ONNX Runtime rewrites the graph before running it. At ORT_ENABLE_ALL, it fuses operators such as convolution followed by batch normalization and activation into fewer kernels. Fewer kernels mean fewer memory round trips.
so = ort.SessionOptions()
so.graph_optimization_level = ort.GraphOptimizationLevel.ORT_ENABLE_ALL
sess = ort.InferenceSession(
"resnet50.onnx",
sess_options=so,
providers=["CUDAExecutionProvider", "CPUExecutionProvider"],
)Running on the GPU with the CUDA execution provider
The CUDA provider runs supported operators on the GPU. Compare the p50 value before and after you switch providers, using the same bench function.
Avoiding copies with I/O binding
By default, each run call copies the input from host memory to the GPU and the output back. I/O binding keeps tensors on the GPU between calls.
x_gpu = ort.OrtValue.ortvalue_from_numpy(x, "cuda", 0)
io = sess.io_binding()
io.bind_ortvalue_input("input", x_gpu)
io.bind_output("logits", "cuda", 0)
sess.run_with_iobinding(io)
logits = io.copy_outputs_to_cpu()[0]Exercise
Why report p95 and p99 alongside p50?
Show answer
The median can look fast while a few slow calls still stall users. The tail percentiles expose those slow calls.