Sub topic 8
Execution Providers and Provider Fallback
Assume you know basic Python, NumPy, and PyTorch, and that you have an ONNX model such as resnet50.onnx. This chapter focuses on how ONNX Runtime chooses the hardware and software implementation for each model operation.
What an execution provider does
An execution provider (EP) is ONNX Runtime's implementation for running operators on a device. An operator is a computation such as convolution, matrix multiplication, or activation.
Common providers include:
| Provider | Typical device | Main use |
|---|---|---|
| `CPUExecutionProvider` | CPU | Portable fallback |
| `CUDAExecutionProvider` | NVIDIA GPU | General GPU inference |
| `TensorrtExecutionProvider` | NVIDIA GPU | TensorRT-optimized inference |
A session can use more than one provider. ONNX Runtime gives the providers a priority order. It tries to assign each part of the model to the first provider that supports it. Unsupported parts can be assigned to a provider lower in the list.
Selecting providers
Pass providers when you create an InferenceSession. Put the fastest preferred provider first and keep the CPU provider last.
import onnxruntime as ort
print("Installed providers:", ort.get_available_providers())
providers = [
"CUDAExecutionProvider",
"CPUExecutionProvider",
]
session = ort.InferenceSession(
"resnet50.onnx",
providers=providers,
)
print("Providers used by the session:", session.get_providers())get_available_providers() reports providers installed in the current environment. get_providers() reports the providers configured for the session.
The CUDA provider requires a compatible ONNX Runtime GPU package, NVIDIA driver, CUDA runtime, and cuDNN installation. A machine may have an NVIDIA GPU while still being unable to initialize the CUDA provider because one of these versions is incompatible.
Fallback behavior and provider order
Provider fallback is useful when one provider does not implement every operator in a graph. For example, CUDA can execute most of a vision model while CPU handles an uncommon preprocessing or postprocessing operator.
Provider order changes performance:
import onnxruntime as ort
providers = [
"TensorrtExecutionProvider",
"CUDAExecutionProvider",
"CPUExecutionProvider",
]
session = ort.InferenceSession(
"resnet50.onnx",
providers=providers,
)Here, TensorRT receives first choice. CUDA handles graph sections TensorRT cannot take. CPU handles anything neither GPU provider supports.
Fallback does not guarantee good performance. Moving tensors between CPU and GPU for a small unsupported operation can cost more than the operation itself. Inspect the model and benchmark the complete request, including preprocessing and output handling.
Exercise
Exercise
In what order should you list TensorRT, CUDA, and CPU when you want TensorRT preferred, CUDA as the GPU fallback, and CPU as the final fallback?
Show answer
List them as TensorrtExecutionProvider, CUDAExecutionProvider, and CPUExecutionProvider, in that order.