Sub topic 10
Running on the GPU with the CUDA execution provider
This chapter assumes basic Python and NumPy, familiarity with PyTorch or another deep learning framework, and an NVIDIA GPU with working CUDA drivers. You also need an ONNX model, such as resnet50.onnx.
What the CUDA execution provider does
An ONNX Runtime execution provider is a backend that runs model operations on a particular device. The CUDAExecutionProvider runs supported operations on an NVIDIA GPU. ONNX Runtime divides the model graph among available providers. Operations that CUDA supports run on the GPU. Other operations can fall back to the CPU.
Provider order matters. Put CUDA first and CPU second:
CUDAExecutionProvider → CPUExecutionProviderONNX Runtime tries the first provider before using later providers. This fallback makes a model easier to run, but it can reduce performance if data moves repeatedly between the CPU and GPU.
Create a CUDA-backed session
Install the GPU build of ONNX Runtime, not both the CPU and GPU packages in the same environment:
pip install onnxruntime-gpu numpyThe package version must be compatible with the installed CUDA and cuDNN libraries. Then create a session with CUDA first and CPU as a fallback:
import numpy as np
import onnxruntime as ort
session = ort.InferenceSession(
"resnet50.onnx",
providers=[
("CUDAExecutionProvider", {"device_id": 0}),
"CPUExecutionProvider",
],
)
print("providers:", session.get_providers())
input_name = session.get_inputs()[0].name
input_shape = session.get_inputs()[0].shape
print("input:", input_name, input_shape)
x = np.random.rand(1, 3, 224, 224).astype(np.float32)
logits = session.run(None, {input_name: x})[0]
print("output shape:", logits.shape)
print("predicted class:", int(logits[0].argmax()))device_id: 0 selects the first visible GPU. Use another index when the process should use a different GPU.
get_providers() reports the provider order available to the session. It does not prove that every operation ran on CUDA. A missing CUDA provider usually indicates an installation or driver mismatch. Check the ONNX Runtime, CUDA, and cuDNN compatibility matrix before changing application code.
Avoid accidental slowdowns
A small batch or a very small model may run faster on the CPU because GPU launches and host-device transfers have fixed costs. For larger workloads, keep tensors on the GPU when possible. ONNX Runtime I/O binding can reduce copies between NumPy memory and GPU memory. Always compare the CUDA session with a CPU baseline using the same inputs and preprocessing.
Exercise
Which provider should appear first when you want ONNX Runtime to prefer an NVIDIA GPU, and why should you include a CPU provider after it?
Show answer
Put CUDAExecutionProvider first so supported operations prefer the GPU. Include CPUExecutionProvider as a fallback for unsupported operations or environments where CUDA is unavailable.