Sub topic 10
Running on the GPU with the CUDA execution provider
This chapter assumes you have exported resnet50.onnx with a dynamic batch axis and can create an InferenceSession on the CPU. It also assumes basic NumPy, and an NVIDIA GPU with a working driver for the hands-on parts. By the end you will be able to select the CUDA execution provider, confirm that it is really in use, and avoid the most common errors.
What the CUDA execution provider does
An execution provider (EP) is a backend that ONNX Runtime uses to run parts of the graph. The CUDA execution provider runs supported operators on an NVIDIA GPU through CUDA libraries such as cuDNN and cuBLAS. Operators it does not support stay on the CPU provider.
The CUDA EP is the simplest GPU path. It needs no engine build step and handles dynamic shapes without extra configuration. It usually runs slower than TensorRT, which the next chapters cover, but it is a good baseline and a good fallback.
Installing the right package
ONNX Runtime ships the CPU and GPU builds as separate Python packages. They conflict if both are installed.
pip uninstall -y onnxruntime
pip install onnxruntime-gpuThe GPU package must match the CUDA and cuDNN versions on your machine. Check the compatibility table in the ONNX Runtime documentation for your release before installing. A mismatch is the most common reason the CUDA provider fails to load.
Selecting the provider
Pass an ordered list of providers when you create the session. ONNX Runtime assigns each part of the graph to the first provider that supports it.
import numpy as np
import onnxruntime as ort
print("available:", ort.get_available_providers())
sess = ort.InferenceSession(
"resnet50.onnx",
providers=["CUDAExecutionProvider", "CPUExecutionProvider"],
)
print("in use:", sess.get_providers())
x = np.random.rand(1, 3, 224, 224).astype(np.float32)
logits = sess.run(None, {"input": x})[0]
print(logits.shape)The two printed lists answer different questions:
get_available_providers()lists what the installed package was built with.sess.get_providers()lists what this session actually registered.
If CUDA fails to load, for example because a shared library is missing, ONNX Runtime can log a warning and silently continue with the CPU provider. The session works, but it is slow. Always print sess.get_providers() and check that CUDAExecutionProvider comes first.
Passing provider options
A provider can be given as a tuple of name and options dictionary.
import onnxruntime as ort
providers = [
(
"CUDAExecutionProvider",
{
"device_id": 0,
"arena_extend_strategy": "kNextPowerOfTwo",
"cudnn_conv_algo_search": "EXHAUSTIVE",
"do_copy_in_default_stream": True,
},
),
"CPUExecutionProvider",
]
sess = ort.InferenceSession("resnet50.onnx", providers=providers)
print(sess.get_providers())The options that matter most for vision models:
| Option | Purpose | Trade-off |
|---|---|---|
| `device_id` | Selects the GPU on a multi-GPU machine. | None. Set it explicitly in services. |
| `cudnn_conv_algo_search` | Chooses how cuDNN picks convolution algorithms: `EXHAUSTIVE`, `HEURISTIC` or `DEFAULT`. | `EXHAUSTIVE` benchmarks algorithms and can cost seconds on the first run for each new input shape. |
| `arena_extend_strategy` | Controls how the GPU memory pool grows. | `kNextPowerOfTwo` can reserve more memory than needed. `kSameAsRequested` is tighter but can fragment. |
| `gpu_mem_limit` | Caps the memory pool size in bytes. | A low cap can cause allocation failures at large batch sizes. |
Where time goes: copies and first runs
Two effects make naive GPU timing misleading.
- Host-to-device copies. With a NumPy input, each
runcall copies the input to GPU memory and copies the output back. For small models and small batches, copy time can be a large share of the total. - First-run cost. The first call initializes CUDA contexts, allocates memory, and (with
EXHAUSTIVEsearch) tests convolution algorithms. This can be hundreds of milliseconds or more.
That is why the benchmarking chapter insists on warmup runs. The next chapter shows how I/O binding removes the copies.
Checking how the graph was partitioned
ONNX Runtime splits the graph into subgraphs, one per provider. Each boundary between a CUDA subgraph and a CPU subgraph forces a memory copy. A model with many such boundaries can be slower on the GPU than on the CPU alone.
To see the assignment, enable verbose logging when you create the session.
import onnxruntime as ort
so = ort.SessionOptions()
so.log_severity_level = 0 # 0 = verbose
sess = ort.InferenceSession(
"resnet50.onnx",
sess_options=so,
providers=["CUDAExecutionProvider", "CPUExecutionProvider"],
)Look in the log for lines about nodes being assigned to execution providers. Standard ResNet-50 runs entirely on CUDA. Models with unusual operators, such as some detection postprocessing steps like non-maximum suppression with data-dependent output sizes, may place nodes on the CPU. If you see many CPU nodes in the middle of the graph, consider moving that logic out of the model or replacing the operator.
Common errors and fixes
| Symptom | Likely cause | Fix |
|---|---|---|
| `sess.get_providers()` lacks `CUDAExecutionProvider` | CPU package installed, or CUDA libraries not found | Reinstall only `onnxruntime-gpu` and check library paths. |
| Warning that CUDA failed to create a provider | Version mismatch between CUDA, cuDNN and ONNX Runtime | Match versions using the compatibility table. |
| GPU is no faster than the CPU | Batch size 1 with a tiny model, copy-dominated timing, or CPU fallback nodes | Increase the batch, bind I/O, and check partitioning. |
| Out-of-memory error | Memory arena grew too large, or the batch is too large | Set `gpu_mem_limit` and lower the batch size. |
| Very slow first request | cuDNN algorithm search and lazy initialization | Run warmup before accepting traffic. |
A startup check you can reuse
This helper creates a session and refuses to continue if the GPU is not in use.
import numpy as np
import onnxruntime as ort
def make_gpu_session(path, device_id=0):
providers = [
("CUDAExecutionProvider", {"device_id": device_id}),
"CPUExecutionProvider",
]
sess = ort.InferenceSession(path, providers=providers)
if sess.get_providers()[0] != "CUDAExecutionProvider":
raise RuntimeError(f"CUDA provider not active: {sess.get_providers()}")
return sess
sess = make_gpu_session("resnet50.onnx")
x = np.random.rand(4, 3, 224, 224).astype(np.float32)
for _ in range(3): # warmup
sess.run(None, {"input": x})
print(sess.run(None, {"input": x})[0].shape)Because the model was exported with a dynamic batch axis, the same session accepts batch sizes 1 and 4 without changes.
Exercise
You install onnxruntime-gpu, create a session with providers=["CUDAExecutionProvider", "CPUExecutionProvider"], and inference runs without errors but is as slow as before. What do you check first, and why can this happen without an exception?
Show answer
Print sess.get_providers(). If CUDAExecutionProvider is missing, the session fell back to the CPU provider, because a provider that fails to load (missing CUDA or cuDNN libraries, version mismatch, or a conflicting CPU-only onnxruntime package) logs a warning and does not raise an error when a later provider in the list can run the model. Fix the installation or library versions, and add a startup assertion that the first provider is the CUDA one.
Exercise
Why does cudnn_conv_algo_search="EXHAUSTIVE" make the first request slow, and why can it still be worth using?
Show answer
With EXHAUSTIVE, cuDNN benchmarks several convolution algorithms for each new input shape and keeps the fastest. That costs time on the first run for every new shape. Later runs with the same shape reuse the choice and can be faster, so it pays off for long-running services with stable shapes, provided you warm up before serving traffic.