Sub topic 13
Enabling the TensorRT execution provider
This chapter shows how to turn on the TensorRT execution provider (EP) in ONNX Runtime, what it changes, and the errors you are most likely to hit. It assumes you can export a model to ONNX and run it in an InferenceSession. It also assumes you know what an execution provider is and that you have an NVIDIA GPU with working CUDA drivers.
What the TensorRT EP does
TensorRT is NVIDIA's inference optimizer. It takes a network, fuses layers, picks fast GPU kernels, and produces an engine, a binary specialized for one GPU and one set of settings.
The TensorRT EP lets ONNX Runtime hand parts of an ONNX graph to TensorRT. You keep the ONNX Runtime API and get TensorRT's optimizations.
The EP does not usually take the whole graph. It claims the subgraphs whose operators TensorRT supports and compiles each one into an engine. Everything else goes to the next provider in your list. This is why the provider list matters.
Prerequisites for the GPU build
Check these before you write any code, because most failures at this step are installation problems.
- You need the
onnxruntime-gpupackage. The plainonnxruntimepackage has no CUDA or TensorRT support. - The TensorRT libraries must be installed and findable on the library path. Each ONNX Runtime release is built against specific CUDA and TensorRT versions, so check the compatibility table in the ONNX Runtime documentation.
- The NVIDIA driver must support the CUDA version your build uses.
You can check which providers your installation offers:
import onnxruntime as ort
print(ort.__version__)
print(ort.get_available_providers())If TensorrtExecutionProvider is missing from the list, the package or the library path is wrong. Fix that first.
Creating a session with the TensorRT EP
The earlier export step produced resnet50.onnx with a dynamic batch axis. Create a session that tries TensorRT first, then CUDA, then CPU:
import onnxruntime as ort
providers = [
(
"TensorrtExecutionProvider",
{
"trt_fp16_enable": True,
"trt_engine_cache_enable": True,
"trt_engine_cache_path": "./trt_cache",
},
),
"CUDAExecutionProvider",
"CPUExecutionProvider",
]
sess_trt = ort.InferenceSession("resnet50.onnx", providers=providers)
print(sess_trt.get_providers())Each entry is either a provider name or a tuple of a name and an options dictionary. The order is the priority order. ONNX Runtime assigns each node to the first provider that can run it.
The options used here:
| Option | Effect |
|---|---|
| `trt_fp16_enable` | Lets TensorRT use half-precision kernels where they are faster. |
| `trt_engine_cache_enable` | Saves built engines to disk so later sessions skip the build. |
| `trt_engine_cache_path` | Directory for the cached engines. |
FP16 and caching each get their own chapter. For now, treat both as the settings you would normally want in production.
Verifying that TensorRT is really in use
get_providers() reports which providers the session registered. It does not tell you that TensorRT took any nodes. If TensorRT fails to load, ONNX Runtime can fall back to the remaining providers, and the session still works. You then benchmark a CUDA or CPU run and believe it was TensorRT.
Use these checks:
- Print
sess_trt.get_providers()and confirmTensorrtExecutionProvideris first. - Look at the logs from session creation. TensorRT builds log messages, and the first build takes noticeably longer.
- Confirm that the cache directory contains files after the first run.
- Compare latency with the plain CUDA session. A large improvement on a convolutional model suggests TensorRT is working.
To get more detail, raise the log verbosity before you create the session:
import onnxruntime as ort
ort.set_default_logger_severity(1) # 0 verbose, 1 info, 2 warning, 3 errorAt info level, the log lists how many nodes each provider received. If you see many small subgraphs, the graph is badly partitioned, and the next section explains why that hurts.
Partitioning and why it affects speed
Each TensorRT subgraph runs as its own engine. Between a TensorRT subgraph and a CUDA or CPU node, tensors cross a boundary. If that boundary is on the CPU, data is copied between device and host.
A graph with one large supported region is fast. A graph with many alternating supported and unsupported nodes pays for each switch and loses fusion across the boundaries. For standard classification networks such as ResNet-50, nearly everything is supported. Detection and segmentation models with custom post-processing operators are more likely to split.
If partitioning looks poor, you have three options:
- Move the unsupported operators out of the ONNX model and into your own pre or postprocessing code.
- Re-export with different settings or a newer opset so the operators map to supported ones.
- Build the engine directly with TensorRT, which a later chapter covers.
The first run is slow
The first inference after creating a TensorRT session can take many seconds or minutes, depending on the model and GPU. ONNX Runtime builds engines lazily, and the builder times many candidate kernels. This is normal.
Do not include this time in a latency benchmark. Run warmup iterations first, as in the benchmarking chapter. In a service, run a warmup request before the instance accepts traffic.
Common errors
- The provider is silently not used. A missing library, such as a TensorRT or cuDNN shared object, makes ONNX Runtime log a load error and continue without TensorRT. Read the log lines at session creation.
- Version mismatch. An
onnxruntime-gpubuild made for one CUDA or TensorRT major version fails with another. Install the combination the documentation lists. - Different results than PyTorch. FP16 changes numerics slightly. Check parity again after enabling it, using the comparison from the earlier chapter, and loosen the tolerance only as far as the accuracy check justifies.
- A new build for every shape. If the model has dynamic dimensions and no profile settings, TensorRT can rebuild an engine when it sees a new input shape. The dynamic shapes chapter covers profiles.
- An unwritable cache directory. If the process cannot write to
trt_engine_cache_path, caching fails and every start rebuilds.
A minimal end-to-end check
This script creates the TensorRT session, warms it up, and runs a batch. It assumes resnet50.onnx exists with an input named input.
import numpy as np
import onnxruntime as ort
providers = [
(
"TensorrtExecutionProvider",
{
"trt_fp16_enable": True,
"trt_engine_cache_enable": True,
"trt_engine_cache_path": "./trt_cache",
},
),
"CUDAExecutionProvider",
"CPUExecutionProvider",
]
sess = ort.InferenceSession("resnet50.onnx", providers=providers)
print("registered:", sess.get_providers())
x = np.random.rand(1, 3, 224, 224).astype(np.float32)
for _ in range(3):
out = sess.run(None, {"input": x})[0]
print("output shape:", out.shape)Run it twice. The second run should start much faster because it loads the cached engine.
Exercise
Your session prints ['TensorrtExecutionProvider', 'CUDAExecutionProvider', 'CPUExecutionProvider'], yet latency matches the plain CUDA session and the cache directory stays empty. What does that suggest, and what do you check next?
Show answer
The listing only shows registered providers, so TensorRT may not have taken any nodes, or it failed to load. Check the session creation logs at info level for library load errors and for the node count per provider. Also confirm the cache path is writable and that your onnxruntime-gpu build matches your installed CUDA and TensorRT versions.
Exercise
Why can a graph with many alternating TensorRT-supported and unsupported nodes run slower than the same graph on the CUDA provider alone?
Show answer
Each supported region becomes a separate engine, so every switch between providers adds overhead and may copy tensors between host and device. Fusion also cannot cross the boundaries. Many small engines can cost more than they save.