Sub topic 8
Execution providers and provider fallback
An execution provider (EP) is the part of ONNX Runtime that runs operators on a particular kind of hardware or with a particular backend. This chapter covers how ONNX Runtime assigns graph nodes to providers, what fallback does, and how to check where your model actually runs. A model can run on the CPU while your code appears to request the GPU, and the only symptom is bad latency.
It assumes you have exported resnet50.onnx and can create an InferenceSession, as in the earlier chapters. GPU examples need an NVIDIA GPU, a CUDA-enabled onnxruntime-gpu package, and matching CUDA and cuDNN libraries.
What an execution provider is
ONNX Runtime keeps the model as a graph of operators such as Conv, Relu, and Gemm. Each provider supplies kernels, which are implementations of some of those operators. Common providers for vision work:
| Provider | Runs on | Typical role |
|---|---|---|
| `CPUExecutionProvider` | CPU | Always present. Supports every operator. |
| `CUDAExecutionProvider` | NVIDIA GPU | Per-operator CUDA and cuDNN kernels. |
| `TensorrtExecutionProvider` | NVIDIA GPU | Hands whole subgraphs to TensorRT. |
Providers differ in granularity. CPU and CUDA run one node at a time. TensorRT takes a connected group of nodes, builds an optimized engine for it, and runs the group as one unit. The TensorRT chapters cover that in detail.
How the provider list is used
You pass providers in priority order:
import onnxruntime as ort
print(ort.get_available_providers())
sess = ort.InferenceSession(
"resnet50.onnx",
providers=["CUDAExecutionProvider", "CPUExecutionProvider"],
)
print(sess.get_providers())ort.get_available_providers() lists the providers compiled into your installed package. sess.get_providers() lists the providers the session actually registered. The two lists can differ, and the second one is the one that matters.
During session creation ONNX Runtime partitions the graph:
- It walks the graph and offers nodes to the first provider in your list. That provider claims every node it can run.
- Unclaimed nodes go to the next provider, and so on.
- The CPU provider is always the last resort, so every node ends up with an owner.
This is provider fallback. It makes models run when a GPU provider lacks one operator, and it also hides problems.
Two kinds of fallback
Fallback happens at two levels, and they fail differently.
Provider-level fallback. You request CUDAExecutionProvider but it cannot load. Typical causes are a CPU-only onnxruntime package, a missing libcudnn, or a CUDA version that does not match your build. In most versions session creation does not fail. ONNX Runtime prints a warning or error to the log and registers only the CPU provider. Your script then runs, slowly, on the CPU.
Node-level fallback. The provider loads, but it does not implement some operator or data type in your model. Those nodes run on the CPU, and ONNX Runtime inserts memory copy nodes between GPU and CPU regions. Each copy crosses PCIe, so a few scattered CPU nodes in the middle of a network can cost more than the GPU saves.
The default is permissive. ONNX Runtime favors producing an answer over telling you the answer came from the wrong hardware.
Failing loudly instead of silently
Never assume the GPU is in use. Check the session right after creating it:
import onnxruntime as ort
def make_session(path, providers, required_first):
sess = ort.InferenceSession(path, providers=providers)
active = sess.get_providers()
if active[0] != required_first:
raise RuntimeError(
f"Expected {required_first} first, got {active}. "
"Check CUDA/cuDNN installation and onnxruntime package."
)
return sess
sess = make_session(
"resnet50.onnx",
["CUDAExecutionProvider", "CPUExecutionProvider"],
"CUDAExecutionProvider",
)
print(sess.get_providers())In a service, put this check in startup code so a broken driver or image fails the deployment and does not slowly degrade production traffic. You may still want CPU fallback in some places, such as a developer laptop. In that case make it an explicit configuration choice and not an accident of the environment.
Passing options to a provider
Instead of a bare name, give a tuple of the name and an options dictionary:
import onnxruntime as ort
providers = [
(
"CUDAExecutionProvider",
{
"device_id": 0,
"arena_extend_strategy": "kNextPowerOfTwo",
"cudnn_conv_algo_search": "EXHAUSTIVE",
},
),
"CPUExecutionProvider",
]
sess = ort.InferenceSession("resnet50.onnx", providers=providers)
print(sess.get_providers())Options are specific to each provider. device_id picks the GPU. cudnn_conv_algo_search controls how cuDNN picks convolution algorithms, and EXHAUSTIVE benchmarks candidates at the cost of a slower first run. Treat option names as version-dependent and check the documentation for your installed release.
Seeing where each node ran
get_providers() only says which providers are registered. To see how many nodes each provider ran, use the profiler:
import json
from collections import Counter
import numpy as np
import onnxruntime as ort
opts = ort.SessionOptions()
opts.enable_profiling = True
sess = ort.InferenceSession(
"resnet50.onnx",
sess_options=opts,
providers=["CUDAExecutionProvider", "CPUExecutionProvider"],
)
x = np.random.rand(1, 3, 224, 224).astype(np.float32)
for _ in range(5):
sess.run(None, {"input": x})
profile_path = sess.end_profiling()
with open(profile_path) as f:
events = json.load(f)
counts = Counter(
e["args"]["provider"]
for e in events
if e.get("cat") == "Node" and "provider" in e.get("args", {})
)
print(counts)For a convolutional network on a working CUDA setup, almost all counted nodes should belong to CUDAExecutionProvider. A noticeable count under CPUExecutionProvider means some operators fell back. Look at those operator names in the profile (args["op_name"]) to learn which ones.
You can also set opts.log_severity_level = 0 before creating the session. The verbose log includes node placement and warnings about operators assigned to the CPU, though the exact wording changes between releases.
Why order matters
Order is a priority list, not a set. Consider ["TensorrtExecutionProvider", "CUDAExecutionProvider", "CPUExecutionProvider"]:
- TensorRT claims the subgraphs it supports.
- CUDA runs the operators TensorRT left behind.
- The CPU runs whatever is left.
Reversing the list puts CUDA first. CUDA then claims almost everything, and TensorRT never sees a node. Pairing a specialized provider with a general one is the normal pattern, with the specialized one first.
Common errors
- Session runs but is slow. The CPU provider is probably active. Check
get_providers(). - Import or load errors mentioning
libcudnnorlibcublas. The CUDA toolkit or cuDNN on the machine does not match what youronnxruntime-gpubuild expects. Use the version table in the ONNX Runtime documentation. - Several GPUs, wrong one used. Set
device_idin the provider options. - Results differ slightly between providers. Different kernels accumulate floating-point sums in different orders. Compare with a tolerance, as in the parity check chapter, and not with exact equality.
Exercise
You create a session with providers=["CUDAExecutionProvider", "CPUExecutionProvider"] on a machine where only the CPU-only onnxruntime package is installed. The script finishes without an exception but is ten times slower than expected. What happened, and what one-line check at startup would catch it?
Show answer
The CUDA provider is not available in that package, so ONNX Runtime fell back to the CPU provider and only logged a warning. Check that sess.getproviders()[0] equals "CUDAExecutionProvider" (or that "CUDAExecutionProvider" is in ort.getavailable_providers()) right after creating the session, and raise an error if it does not.
Exercise
Your session reports ["CUDAExecutionProvider", "CPUExecutionProvider"] and the profile shows 3 of 150 nodes on the CPU provider, yet latency is worse than expected. Why can so few CPU nodes hurt, and what should you inspect?
Show answer
Each switch between a GPU region and a CPU node needs memory copies across PCIe and a synchronization, so a few CPU nodes in the middle of the graph add transfer overhead that can outweigh the GPU gains. Inspect the op_name of those CPU nodes in the profile, then either replace or move the unsupported operator (for example into host-side post-processing) or change the export so the GPU provider supports it.