Sub topic 14
Engine Build Time and Engine Caching
Assume you know basic Python, ONNX Runtime, and GPU inference. This chapter focuses on the TensorRT execution provider (EP), which lets ONNX Runtime use TensorRT to optimize and run part of an ONNX graph.
TensorRT does not usually execute an ONNX graph directly. It first builds an engine. Engine building chooses kernels, applies graph optimizations, and tunes implementations for a particular GPU, TensorRT version, model, shape range, and precision. This process can take seconds or minutes. Inference starts only after the engine is ready.
Why engine caching matters
A server that creates a new InferenceSession after every restart may repeatedly pay the engine-build cost. TensorRT can save the serialized engine to a cache directory. Later sessions can load the compatible engine instead of building it again.
The cache is an optimization, not a source of truth. TensorRT may ignore a cached engine when the model, provider settings, GPU, TensorRT libraries, or shape profile no longer match.
import onnxruntime as ort
providers = [
(
"TensorrtExecutionProvider",
{
"trt_fp16_enable": True,
"trt_engine_cache_enable": True,
"trt_engine_cache_path": "./trt_cache",
},
),
"CUDAExecutionProvider",
"CPUExecutionProvider",
]
session = ort.InferenceSession(
"resnet50.onnx",
providers=providers,
)
print(session.get_providers())Create the cache directory with suitable permissions before deployment. The first session may still be slow because it builds and writes the engine. A later session on the same compatible machine should load it more quickly.
Engine cache versus timing cache
These caches solve different problems:
| Cache | Stores | Main benefit |
|---|---|---|
| Engine cache | A built TensorRT engine | Avoids rebuilding the model |
| Timing cache | Kernel timing information used during building | Speeds future engine builds |
A timing cache can help when you build several engines with related configurations. It does not replace the finished engine cache. Treat both as generated artifacts that can be deleted and recreated.
A safe deployment flow
Warm the service before accepting traffic. Log whether initialization loaded or built an engine, then measure startup time separately from inference latency. Include the ONNX model hash, GPU type, TensorRT version, precision, and shape profile in your deployment record.
Exercise
Why might TensorRT rebuild an engine even when the cache directory is present?
Show answer
The cached engine may be incompatible with the model, GPU, TensorRT or CUDA version, provider options, precision, or supported input shapes.