Sub topic 14
Engine build time and engine caching
This chapter assumes you can export a model to ONNX, create an ONNX Runtime InferenceSession, and choose execution providers. It also assumes you have read the previous chapter on enabling the TensorRT execution provider. The GPU examples need an NVIDIA GPU, CUDA drivers, and an ONNX Runtime build that includes TensorRT support.
Why the first session is slow
TensorRT does not run an ONNX graph directly. It first compiles the graph into an engine, which is a serialized plan tuned for one GPU, one TensorRT version, and one set of input shapes and precisions. The step that produces the engine is called the build.
During a build, TensorRT does the following:
- It fuses layers, for example convolution, bias, and activation.
- It benchmarks several candidate kernels (tactics) for each layer on your actual GPU.
- It picks the fastest tactic and lays out memory.
This search is the reason the engine is fast. It is also the reason that creating the first session takes a long time. A ResNet-50 build can take tens of seconds. Larger detection or segmentation models can take several minutes.
If you do not cache the engine, ONNX Runtime repeats the build every time a process creates a session. For a service that restarts, autoscales, or runs short batch jobs, the build time becomes startup time.
Where the build happens in ONNX Runtime
With the TensorRT execution provider, the build is not always at session creation. ONNX Runtime partitions the graph and gives TensorRT the subgraphs it can handle. By default, the engine for each subgraph is built when the session is created, or on the first run if the input shapes are not yet known.
The practical rules are these:
- Static input shapes: the build usually happens when you call
InferenceSession(...). - Dynamic shapes: the build can happen on the first
runthat needs it, and again when a new shape falls outside what the existing engine supports. - Unsupported operators: ONNX Runtime splits the graph into several TensorRT subgraphs and CUDA or CPU parts. Each TensorRT subgraph gets its own engine, so more splits mean more engines and more build time.
The diagram shows the decision at session creation.
Turning on engine caching
Engine caching is controlled by provider options. The two options you need are trt_engine_cache_enable and trt_engine_cache_path.
import time
import onnxruntime as ort
providers = [
(
"TensorrtExecutionProvider",
{
"trt_fp16_enable": True,
"trt_engine_cache_enable": True,
"trt_engine_cache_path": "./trt_cache",
},
),
"CUDAExecutionProvider",
"CPUExecutionProvider",
]
start = time.perf_counter()
sess = ort.InferenceSession("resnet50.onnx", providers=providers)
print(f"session creation: {time.perf_counter() - start:.1f} s")
print(sess.get_providers())Run this script twice. The first run builds the engine and writes files into ./trt_cache. The second run finds the files and loads them, so session creation should drop from tens of seconds to a second or two. The exact numbers depend on your model and GPU.
Look in the cache directory after the first run. You should see files with the extension .engine. ONNX Runtime also writes .profile files that record the shape ranges used for the build. The file names include a hash of the model and the subgraph, along with GPU architecture information, so one directory can hold engines for several models.
What the cache key covers
A cached engine is only reused when it is valid for the current setup. ONNX Runtime and TensorRT check several things:
- The model: a changed ONNX file produces a different hash.
- The GPU architecture: an engine built on one compute capability will not load on another.
- The TensorRT version: engines are not compatible across TensorRT versions.
- The build options: precision flags and shape ranges that change the engine.
If a check fails, the provider rebuilds. This is safe, but it can surprise you. For example, you update a driver stack that brings a new TensorRT version, and the next startup takes minutes again.
Some details are easy to get wrong:
- A change in the optimization profile (the min, opt, and max shapes) needs a new engine. ONNX Runtime stores the ranges it used in the
.profilefile and rebuilds when a new input falls outside them. - Switching
trt_fp16_enablebetween runs should be treated as a different configuration. Use a separate cache directory for each precision to avoid confusion when you compare results. - Engines are tuned by timing kernels on a specific GPU. Two GPUs of the same architecture work, but a build on a busy GPU can pick slightly slower tactics. Build while the GPU is otherwise idle.
Measuring build time and warm-up separately
Report three numbers for a TensorRT deployment: cold start (no cache), warm start (cache present), and steady-state latency. The following script measures the first two. Run it twice with the same cache directory to see the difference.
import os
import time
import numpy as np
import onnxruntime as ort
CACHE = "./trt_cache"
cold = not os.path.isdir(CACHE) or not any(
name.endswith(".engine") for name in os.listdir(CACHE)
)
providers = [
(
"TensorrtExecutionProvider",
{
"trt_fp16_enable": True,
"trt_engine_cache_enable": True,
"trt_engine_cache_path": CACHE,
},
),
"CUDAExecutionProvider",
"CPUExecutionProvider",
]
t0 = time.perf_counter()
sess = ort.InferenceSession("resnet50.onnx", providers=providers)
t_session = time.perf_counter() - t0
x = np.random.rand(1, 3, 224, 224).astype(np.float32)
t0 = time.perf_counter()
sess.run(None, {"input": x})
t_first = time.perf_counter() - t0
t0 = time.perf_counter()
for _ in range(50):
sess.run(None, {"input": x})
t_steady = (time.perf_counter() - t0) / 50
print("cache state:", "cold" if cold else "warm")
print(f"session creation: {t_session:.2f} s")
print(f"first run: {t_first * 1000:.1f} ms")
print(f"steady run: {t_steady * 1000:.2f} ms")On a cold start, session creation or first run carries the build time, depending on whether shapes were known up front. On a warm start, both should be small, and first run is still a little higher than steady run because of memory allocation and GPU context setup. That residual cost is why the benchmarking chapter uses warmup iterations.
Shipping the cache versus building at startup
You have three practical choices for getting a warm cache into production.
| Strategy | How it works | Strength | Weakness |
|---|---|---|---|
| Build at first startup | The service builds and writes the cache on its first run | Simple, always matches the host GPU | The first instance is slow, and every new node repeats it |
| Pre-warm in the image | A build step runs the model once and bakes `trt_cache` into the image | Fast startup | Only valid if production GPU and TensorRT version match the build machine |
| Shared volume | Nodes mount a shared cache directory | One build serves many nodes of the same type | Concurrent writers need care, and mixed GPU types share one directory |
For a fleet with a single GPU type, pre-warming is usually best. For a mixed fleet, build at startup, or pre-warm one cache directory per GPU type and select it with an environment variable.
Reducing build time
Caching hides the build, but it does not make it shorter. If builds are too slow, you have these options:
- Reduce the number of engines. Check
get_providers()and the ONNX Runtime log for how many subgraphs go to TensorRT. Replacing or simplifying an unsupported operator can merge several small engines into one. - Narrow the shape range. A wide min-to-max range makes the builder consider more cases. Cover only the batch sizes you serve.
- Limit the builder effort. The provider has an option for the builder optimization level, which trades some runtime speed for a shorter build. Check the documentation for your ONNX Runtime version, because option names change between releases.
- Use FP16 only if you need it, and test INT8 builds separately. INT8 adds calibration work.
- Build once in CI, not on every node.
Common errors
- Cache directory never fills. The most common cause is that the provider did not load. Print
sess.get_providers()and confirmTensorrtExecutionProvidercomes first. If it is missing, your ONNX Runtime build lacks TensorRT support or a library cannot be found. - Every start is slow even with caching on. The cache path is not persistent, the path differs between runs (a relative path with a different working directory), or the process cannot write to it.
- A new batch size triggers a long pause in production. The shape fell outside the built range, so the provider rebuilt. Set the profile range to cover all expected shapes, and send those shapes during pre-warming.
- Results change slightly after a rebuild. Tactic selection can differ between builds, especially in FP16. Run a parity check against the original model after each new build.
Exercise
Your service restarts at night and the first request after each restart takes about 40 seconds. You already set trt_engine_cache_enable to True and trt_engine_cache_path to ./trt_cache. The service runs in a container, and the working directory is inside the container's writable layer. What is the likely cause, and what two changes would fix it?
Show answer
The cache is written to a path that is lost when the container is replaced, so every restart rebuilds the engine. Fix it by using an absolute cache path on a persistent volume (or a pre-warmed cache baked into the image for the same GPU type and TensorRT version), and by running a warm-up request with the expected shapes at startup so any remaining build or allocation cost happens before real traffic arrives.
Exercise
You change the optimization profile so the maximum batch size goes from 8 to 32 and keep the same cache directory. What should you expect on the next startup, and why?
Show answer
Expect a rebuild. The cached engine was built for a batch range that tops out at 8, so it is not valid for the new range. The provider builds a new engine and writes it to the cache. Using a separate cache directory per configuration makes this easier to track.