Sub topic 18
Deployment: Version Pinning, Engine Portability, and Fallbacks
This chapter assumes you can export a model to ONNX, create an InferenceSession, and enable the TensorRT execution provider with an engine cache, as covered in earlier chapters. It covers what can go wrong when the same service moves from your workstation to production machines.
Why deployment is a separate problem
A TensorRT engine is not a portable model file. It is a compiled artifact, tuned for one TensorRT version, one GPU architecture, and one set of shape and precision settings. ONNX Runtime also chooses providers at session creation. If a provider cannot load, it can quietly drop to a slower one. Most deployment failures come from one of these three causes:
- Library versions differ between build and run environments.
- A cached engine is reused on hardware it was not built for.
- The service runs on the CPU and nobody notices.
Pin the whole stack
The Python package version is not enough. The GPU path depends on a chain of components, and ONNX Runtime GPU builds are compiled against specific CUDA, cuDNN, and TensorRT major versions.
| Component | Why it matters | Where to pin it |
|---|---|---|
| NVIDIA driver | Sets the highest CUDA version the machine supports | Host image or node pool |
| CUDA and cuDNN | The ONNX Runtime CUDA provider links against them | Container base image |
| TensorRT | Engines are tied to its version | Container base image |
| `onnxruntime-gpu` | Decides which CUDA and TensorRT versions it expects | Lock file |
| ONNX opset | Controls which operators the exporter emits | Export script (`opset_version=17`) |
| Model file | Engines are built from a specific graph | Content hash or registry tag |
Pin exact versions in a lock file, and build one container image that holds the CUDA, cuDNN, TensorRT, and ONNX Runtime layers. Check the ONNX Runtime CUDA and TensorRT requirements page for the combination you choose. Do not install onnxruntime and onnxruntime-gpu in the same environment. They share a module name and the wrong one can win.
Log the stack at service start. Then every latency report or accuracy complaint can be traced to an exact environment.
import platform
import onnxruntime as ort
def describe_environment() -> dict:
return {
"python": platform.python_version(),
"onnxruntime": ort.__version__,
"device": ort.get_device(),
"available_providers": ort.get_available_providers(),
}
print(describe_environment())Engine portability
An engine built for one setup should be treated as invalid on another. These factors decide whether a cached engine can be reused:
- TensorRT version. An engine from one version does not load in another. ONNX Runtime rebuilds when its cache does not match, which costs minutes at startup.
- GPU architecture. Engines are tuned to a compute capability, such as an A100 versus a T4. Kernel choices that are fast on one GPU may be unavailable or slow on another.
- Build settings. Precision flags, optimization profiles, and workspace limits are baked in. Changing
trt_fp16_enableor the batch range means a different engine. - The model. A new ONNX file means a new engine, even if the filename is unchanged.
Practical rules:
- Keep one cache directory per GPU type and per image version, for example
./trt_cache/<image-tag>/<gpu-name>. - Do not bake an engine cache into an image and run that image on a different GPU model. Build the cache on the target hardware, either in a warmup job before the node takes traffic or on first start.
- Treat the cache as disposable. The ONNX file is the source of truth, and a missing or stale cache should only cost startup time.
- Mount the cache on persistent storage if pods restart often, so a rescheduled pod does not pay the build cost again.
TensorRT also offers hardware-compatibility build options for newer GPU generations, which let one engine run across several architectures. They trade some speed for portability. Check that your TensorRT version supports them before relying on them.
Fallbacks: make them visible
A provider list is a preference order, not a guarantee. ONNX Runtime can skip a provider that fails to load and may only log a warning. Two fallbacks exist, and they behave differently:
- Whole-session fallback. The preferred provider fails to load, so every node runs on a later provider.
- Partial-graph fallback. TensorRT takes the subgraphs it supports and leaves the rest to CUDA or the CPU. This is normal and expected, but many small subgraphs add copies between devices and slow the model down.
Check the result at startup instead of assuming it. The function below tries each tier in order and accepts a session only if the provider you wanted is first in get_providers().
import onnxruntime as ort
def make_session(path: str, cache_dir: str = "./trt_cache"):
tiers = [
("tensorrt", [
("TensorrtExecutionProvider", {
"trt_fp16_enable": True,
"trt_engine_cache_enable": True,
"trt_engine_cache_path": cache_dir,
}),
"CUDAExecutionProvider",
"CPUExecutionProvider",
]),
("cuda", ["CUDAExecutionProvider", "CPUExecutionProvider"]),
("cpu", ["CPUExecutionProvider"]),
]
available = set(ort.get_available_providers())
for name, providers in tiers:
first = providers[0][0] if isinstance(providers[0], tuple) else providers[0]
if first not in available:
continue
try:
sess = ort.InferenceSession(path, providers=providers)
except Exception as exc:
print(f"tier {name} failed: {exc}")
continue
if sess.get_providers()[0] != first:
print(f"tier {name} loaded but {first} is not active")
continue
return name, sess
raise RuntimeError("no usable execution provider")
tier, sess = make_session("resnet50.onnx")
print("serving on tier:", tier, sess.get_providers())Decide in advance whether a CPU fallback is acceptable. For a service sized for GPU latency, a CPU fallback often means missed deadlines and a backlog. Failing the readiness check, so the orchestrator routes traffic elsewhere, is usually safer. To stop individual nodes from silently landing on the CPU, set the session option session.disable_cpu_ep_fallback to "1" with sess_options.add_session_config_entry. Session creation then fails if any node cannot be placed on a non-CPU provider.
Export the active tier as a metric or log field. A dashboard that shows which tier each replica runs on will reveal a bad image rollout within minutes.
Verify after every change
Pinning and cache rules reduce the chance of drift. They do not remove it. Run a smoke test at startup using a small set of stored inputs and their reference outputs from the original PyTorch model. Compare with the same tolerance as your parity check, and also compare top-1 predictions. Run it again after any change to the TensorRT version, the precision flags, or the ONNX file. FP16 engines in particular can differ between TensorRT releases.
A short checklist for each release:
- Rebuild or revalidate the engine on every target GPU type.
- Check parity against the reference outputs.
- Benchmark with warmup and report p50, p95, and p99 latency against the previous release.
- Confirm the active provider tier in the logs.
- Keep the previous image and its known-good cache so you can roll back.
Common errors
- Startup takes minutes after a deploy. The cache did not match, so the engine was rebuilt. Check the TensorRT version, the GPU type, and whether the cache path is writable and persistent.
- Latency doubles but nothing crashes. A fallback to CUDA or CPU happened. Look at
get_providers()and the startup warnings. - Works on the dev GPU, fails on production. The driver is older than the CUDA version in the image, or the cached engine came from a different architecture.
- Import errors or wrong provider list. Both
onnxruntimeandonnxruntime-gpuare installed. Uninstall both and reinstall only the GPU package.
Exercise
A team bakes a TensorRT engine cache into a container image built on a T4 workstation. After deployment to A100 nodes, startup is slow and p99 latency is worse than in testing. Give two likely causes and one fix.
Show answer
The cached engines were built for the T4's architecture and do not match the A100, so ONNX Runtime either rebuilds them at startup or runs with a poor configuration, and some nodes may have fallen back from TensorRT to CUDA. Check the active providers with get_providers() to see which happened. The fix is to stop shipping the cache in the image. Build it on each target GPU type, using a warmup job or first start, and store it per GPU type and image version on persistent storage. Add a startup check that fails readiness if TensorRT is not the active provider.