Sub topic 4
Running the Model with ONNX Runtime
Assume you know basic Python and NumPy, have an exported resnet50.onnx file, and understand that image models usually expect tensors shaped as batch, channels, height, and width. ONNX Runtime is an inference engine. It loads an ONNX graph and executes its operators on a selected device.
Create an inference session
An InferenceSession owns the loaded model and its runtime configuration. Provider order determines the preferred execution backends. The CUDA provider uses an NVIDIA GPU. The CPU provider is a fallback.
import numpy as np
import onnxruntime as ort
session = ort.InferenceSession(
"resnet50.onnx",
providers=[
"CUDAExecutionProvider",
"CPUExecutionProvider",
],
)
print("Available providers:", ort.get_available_providers())
print("Session providers:", session.get_providers())
input_info = session.get_inputs()[0]
output_info = session.get_outputs()[0]
print("Input:", input_info.name, input_info.shape, input_info.type)
print("Output:", output_info.name, output_info.shape, output_info.type)
x = np.random.rand(1, 3, 224, 224).astype(np.float32)
logits = session.run(
[output_info.name],
{input_info.name: x},
)[0]
print("Logits shape:", logits.shape)The input dictionary maps the ONNX input name to a NumPy array. Use the names reported by get_inputs() rather than assuming that the name is input. The output is returned as a list because a model can have several outputs.
A ResNet classifier normally expects preprocessing that matches its training setup. For ImageNet models, that commonly means resizing the image, converting pixels to RGB, scaling values to [0, 1], and applying channel-wise mean and standard deviation. Incorrect preprocessing can produce poor predictions even when inference itself succeeds.
Understand provider fallback
ONNX Runtime divides the graph among execution providers when possible. It gives preferred providers the first chance to claim each operator. Unsupported operators can run on a lower-priority provider, such as the CPU.
Fallback improves compatibility, but it can reduce performance when tensors move repeatedly between devices. Check the runtime logs or benchmark results if a GPU session is unexpectedly slow.
Configure graph optimization
ONNX Runtime can simplify the graph before execution. Operator fusion combines compatible operations, such as convolution and activation, into fewer runtime steps.
options = ort.SessionOptions()
options.graph_optimization_level = (
ort.GraphOptimizationLevel.ORT_ENABLE_ALL
)
session = ort.InferenceSession(
"resnet50.onnx",
sess_options=options,
providers=["CUDAExecutionProvider", "CPUExecutionProvider"],
)Exercise
Why should the CPU provider appear after the CUDA provider in the provider list?
Show answer
ONNX Runtime tries providers in priority order. Putting CPU last lets CUDA handle supported operators while preserving CPU fallback for unsupported ones.