Sub topic 12
How TensorRT optimizes a network into an engine
This chapter explains what TensorRT does between your ONNX file and a running GPU program. It covers the builder, the engine, and the runtime, and the errors people hit when they treat an engine like a model file.
Prerequisites assumed: you can export a PyTorch model to ONNX and run it in an ONNX Runtime InferenceSession. You know what a CUDA execution provider is. You have an NVIDIA GPU for the hands-on parts.
What TensorRT is
TensorRT is NVIDIA's inference optimizer and runtime. It takes a trained network and produces a GPU program tuned for one specific GPU. It does no training and has no autograd. It only makes a fixed network run fast.
ONNX Runtime executes your graph operator by operator, with kernels from a provider. TensorRT instead rewrites the whole graph, picks the fastest kernel for each piece on your hardware, and saves the result. That saved result is an engine.
The three pieces: builder, engine, runtime
TensorRT separates work into a slow offline step and a fast online step.
| Piece | Role | When it runs |
|---|---|---|
| Builder | Parses the network, optimizes it, benchmarks kernels, and produces an engine | Offline, can take seconds to minutes |
| Engine | The optimized, serialized network for one GPU and one TensorRT version | Saved to disk, loaded at startup |
| Runtime | Deserializes an engine and creates execution contexts that run inference | Online, on every request |
The builder takes a network definition and a builder configuration. The configuration holds your choices: allowed precisions, a memory limit for scratch space, and optimization profiles for dynamic shapes. The output is a byte string you can write to a file. The runtime loads that file without needing the original ONNX.
An execution context holds the per-inference state, such as intermediate buffers. One engine can have several contexts, so several threads or streams can run the same engine concurrently.
What the builder does to the graph
The builder applies several optimizations. Knowing them explains both the speed gains and the surprises.
Layer and tensor fusion
Running many small GPU kernels is slow, because each one reads its input from GPU memory and writes its output back. Fusion merges adjacent operations into one kernel so intermediate results stay in fast on-chip memory.
A common vision pattern is convolution, then batch normalization, then ReLU. TensorRT folds the batch normalization constants into the convolution weights, then fuses the activation into the same kernel. Three layers become one. A ResNet-50 has dozens of these blocks, so the savings add up.
Fusion also removes operations that have no effect at inference time. Dropout is the usual example. Concatenations can sometimes be eliminated by having producer layers write straight into the right slice of a shared buffer.
Kernel auto-tuning
For each layer, several kernel implementations exist. They differ in tiling, memory layout, and whether they use Tensor Cores. The builder times the candidates on your actual GPU and keeps the fastest. This is why build time is long. It is also why an engine is tied to the GPU model it was built on.
Precision selection
By default, TensorRT builds in FP32. If you enable FP16 or INT8, the builder may choose lower-precision kernels for any layer where they are faster. It can mix precisions within one network. The next chapters cover accuracy checks for these modes.
Memory planning
The builder analyzes tensor lifetimes. Two intermediate tensors that are never alive at the same time can share the same memory. This lowers the memory footprint of the engine at runtime.
What the engine is and is not
An engine is not a portable model format. Treat it as a compiled binary.
- It is specific to the GPU architecture it was built for, such as Ampere versus Ada.
- It is specific to the TensorRT version. A newer version usually refuses to load an older engine.
- It is built for a range of input shapes, defined by optimization profiles.
- It cannot be converted back to ONNX or PyTorch.
Keep the ONNX file as your source of truth. Treat engines as build artifacts you can regenerate.
Seeing the builder work
You can use the Python API directly. This example builds an FP16 engine from the ONNX file produced earlier and saves it. It uses a fixed batch size of 1 to stay simple. The chapter on dynamic shapes covers profiles.
import tensorrt as trt
logger = trt.Logger(trt.Logger.INFO)
builder = trt.Builder(logger)
network = builder.create_network()
parser = trt.OnnxParser(network, logger)
with open("resnet50.onnx", "rb") as f:
if not parser.parse(f.read()):
for i in range(parser.num_errors):
print(parser.get_error(i))
raise SystemExit("ONNX parse failed")
config = builder.create_builder_config()
config.set_memory_pool_limit(trt.MemoryPoolType.WORKSPACE, 1 << 30)
config.set_flag(trt.BuilderFlag.FP16)
profile = builder.create_optimization_profile()
profile.set_shape("input", (1, 3, 224, 224), (1, 3, 224, 224), (1, 3, 224, 224))
config.add_optimization_profile(profile)
serialized = builder.build_serialized_network(network, config)
if serialized is None:
raise SystemExit("Engine build failed")
with open("resnet50.plan", "wb") as f:
f.write(serialized)
print("engine bytes:", len(serialized))The ONNX export used a dynamic batch axis, so the profile is required. A network with a dynamic dimension and no profile fails to build. The three tuples are the minimum, optimal, and maximum shapes.
The INFO-level logger prints which layers were fused and which tactics were chosen. Read that output once. It shows you how much of your graph actually changed.
Loading the engine in a separate process uses the runtime:
import tensorrt as trt
logger = trt.Logger(trt.Logger.WARNING)
runtime = trt.Runtime(logger)
with open("resnet50.plan", "rb") as f:
engine = runtime.deserialize_cuda_engine(f.read())
context = engine.create_execution_context()
print("I/O tensors:", [engine.get_tensor_name(i) for i in range(engine.num_io_tensors)])Deserializing takes far less time than building. This split is the reason engine caching matters in production.
Unsupported operators and partial graphs
TensorRT supports a large but finite set of operators. If the parser meets an operator it cannot handle, the build fails when you use TensorRT directly. You then have three options: change the model, replace the operator with supported ones, or write a TensorRT plugin.
Inside ONNX Runtime, the TensorRT execution provider handles this differently. It claims only the subgraphs TensorRT supports, and the remaining nodes fall back to the CUDA or CPU provider. This is convenient. It also means a model can run with several small TensorRT engines joined by CPU or CUDA nodes. Each boundary costs a memory copy and a synchronization. A model that "uses TensorRT" may therefore be slower than expected. Always check how many partitions you got.
Common errors
- Building on the wrong machine. An engine built on a development workstation GPU fails or misbehaves on a different GPU model in production. Build on the target hardware, or in a pipeline that matches it.
- Missing optimization profile. The build fails with dynamic dimensions. Always set minimum, optimal, and maximum shapes.
- Running outside the profile. A batch of 64 against a profile with maximum 32 raises an error at run time.
- Too small a workspace. A low memory limit makes the builder skip fast kernels. The engine builds but runs slower.
- Benchmarking the build. The first run after a fresh build includes loading and initialization. Use warmup runs, as in the benchmarking chapter.
- Version mismatch. Updating TensorRT or the driver invalidates saved engines.
Choosing between direct TensorRT and the ONNX Runtime provider
Use the ONNX Runtime TensorRT provider when you want one API, automatic fallback for unsupported operators, and easy comparison with the CUDA provider. Build engines directly when you need full control over profiles and precision, want to ship a single engine file with a small runtime, or need to profile with trtexec. Later chapters cover both.
Exercise
A teammate builds an engine on an RTX workstation, copies the .plan file to a cloud server with a different GPU model, and gets a load failure. Why does this happen, and what should they ship and build instead?
Show answer
The builder auto-tunes kernels for the specific GPU architecture and TensorRT version, so an engine is a compiled binary that is not portable across GPU models or versions. They should ship the ONNX file (the source of truth) and build the engine on the target hardware, or in a build step that matches the target GPU and TensorRT version.
Exercise
Name three optimizations the TensorRT builder applies and say what each one reduces.
Show answer
Layer fusion merges operations such as convolution, batch normalization, and ReLU into one kernel, reducing kernel launches and memory traffic. Kernel auto-tuning times several implementations per layer and picks the fastest, reducing per-layer compute time. Memory planning lets tensors with non-overlapping lifetimes share buffers, reducing the memory footprint. Precision selection (FP16 or INT8) is also an accepted answer, reducing compute and bandwidth cost.