Sub topic 17
Building and profiling engines with trtexec
This chapter assumes you can export a PyTorch model to ONNX, run it with ONNX Runtime, and read latency percentiles. It also assumes you know what an optimization profile is from the chapter on dynamic shapes, and that you have an NVIDIA GPU with TensorRT installed. trtexec ships with the TensorRT package (and in NVIDIA's TensorRT containers). It is a command-line tool, so you do not write any C++ or Python to use it.
What trtexec is for
trtexec does three jobs in one binary:
- It builds a TensorRT engine from an ONNX file and saves it to disk.
- It loads a saved engine and runs it with random or supplied inputs.
- It reports timing, per-layer profiles, and build settings.
Use it to answer questions before you commit to a deployment path. Does TensorRT support every operator in your model? How fast is the engine with no Python or ONNX Runtime overhead? What does FP16 buy you on this GPU? The number it gives you is a ceiling: the best your model can do with TensorRT on that hardware.
Where it fits in the workflow
Building an engine
The basic command from the plan builds an FP16 engine with an optimization profile covering batch sizes 1 to 32:
trtexec --onnx=resnet50.onnx --saveEngine=resnet50.plan --fp16 \
--minShapes=input:1x3x224x224 \
--optShapes=input:8x3x224x224 \
--maxShapes=input:32x3x224x224Each flag matters:
| Flag | Meaning |
|---|---|
| `--onnx` | The model to parse. The input name (`input`) must match the name used at export. |
| `--saveEngine` | Where to write the serialized engine. The `.plan` extension is a convention. |
| `--fp16` | Allow FP16 kernels. TensorRT still picks FP32 for layers where it is faster or where FP16 is not supported. |
| `--minShapes`, `--optShapes`, `--maxShapes` | The optimization profile. The engine accepts any shape between min and max. |
The optShapes value is the shape TensorRT tunes kernels for. Batch sizes near it run fastest. Batch sizes far from it still work but may use kernels that are less well suited. If your service mostly sees batches of 8, set 8 here, not the maximum.
If your ONNX model has a fixed batch size, you do not pass the shape flags at all. Passing them to a model with no dynamic axis causes a build error or is ignored, depending on the version. This is why the export step used dynamic_axes.
Reading the build log
The build can take from seconds to many minutes. The log is worth reading, because it tells you things the engine file does not:
- Parser errors name operators TensorRT cannot import. Fix these in the export (a different
opset_version, or a rewrite of the offending operation) or plan to let ONNX Runtime run that part with its fallback providers. - Warnings about weights outside the FP16 range or about casting INT64 to INT32 are usually harmless, but note them.
- The final summary lists the engine size and the build time.
Profiling a built engine
Once you have an engine, load it and run it. You can also let trtexec build and run in one call by omitting --saveEngine, but saving first lets you profile repeatedly without rebuilding.
trtexec --loadEngine=resnet50.plan \
--shapes=input:8x3x224x224 \
--warmUp=500 --iterations=200 --duration=3 \
--avgRuns=10 --percentile=50,95,99The flags set the benchmark protocol you already know from the benchmarking chapter:
--warmUpis the time in milliseconds to run before measuring.--iterationsis the minimum number of timed runs, and--durationis the minimum number of seconds.trtexecruns until both are met.--shapespicks the concrete input shape for this run. It must lie inside the profile.--percentilereports the latency percentiles you ask for.
Interpreting the output
The summary prints several figures. The ones to read first:
| Figure | What it tells you |
|---|---|
| Throughput (qps) | Inference calls per second at this batch size. Multiply by the batch size for images per second. |
| Latency (min, max, mean, median, percentiles) | End-to-end time per call, including host and device transfers unless you disable them. |
| Enqueue time | Time the CPU spends launching work. If this is close to latency, the CPU is the bottleneck. |
| H2D and D2H latency | Time copying inputs to the GPU and outputs back. |
| GPU Compute Time | Time the GPU spends on the network itself. |
Compare GPU compute time with total latency. If they are close, the GPU is the limit and you should look at precision or the model. If latency is much larger, transfers or launch overhead dominate. In that case, the ONNX Runtime I/O binding technique or a larger batch will help more than a faster kernel.
By default trtexec overlaps transfers with compute across iterations, so throughput can look better than 1 / latency. Add --noDataTransfers to isolate pure GPU compute, and --useSpinWait to reduce timing noise from the CPU waking up late. Neither changes what you deploy. They change what you measure.
Per-layer profiling
To find which layers cost the most, ask for a profile:
trtexec --loadEngine=resnet50.plan \
--shapes=input:8x3x224x224 \
--dumpProfile --separateProfileRun \
--exportProfile=profile.json \
--exportTimes=times.json--dumpProfile prints per-layer times. --separateProfileRun does the profiling in its own pass so that the profiling hooks do not disturb the main latency numbers. The JSON files can be loaded with a script for sorting and plotting.
Layer names will show fusion. A line such as a convolution fused with a batch normalization and a ReLU is a single kernel, which is the operator fusion you saw in the graph optimization chapter, done by TensorRT. If you want more detail on why a layer was chosen, rebuild with --profilingVerbosity=detailed and export the layer information with --exportLayerInfo.
Precision flags and their checks
The precision flags change what the engine computes, so every engine you build with a new flag needs a parity check.
--fp16allows half-precision kernels. For most vision backbones the accuracy change is small.--int8allows 8-bit integer kernels. Without calibration data,trtexecuses placeholder scales, which gives you valid timing but meaningless accuracy. Use it to estimate speed only, and supply a calibration cache (--calib=cache_file) or a quantized ONNX model with Q/DQ nodes for real results.--bestlets TensorRT choose among FP32, FP16, and INT8 per layer.
Checking the engine against the original model
trtexec can save the engine's outputs so you can compare them with PyTorch:
trtexec --loadEngine=resnet50.plan \
--shapes=input:1x3x224x224 \
--loadInputs=input:input.bin \
--exportOutput=output.json--loadInputs feeds a binary file instead of random data. Write that file from NumPy with x.tofile("input.bin"), using the same float32 array you passed to PyTorch. Then load output.json and compare with numpy.testing.assert_allclose, using looser tolerances for FP16 (for example rtol=1e-2, atol=1e-3) than you used for FP32. Check that the top-1 class matches on a set of real images, not just one tensor.
Common errors
- Input name mismatch. The name in
--minShapesmust equal the ONNX input name. Inspect it withonnx.loador Netron. - Shape outside the profile. Running with
--shapesbeyondmaxShapesfails. Rebuild with a wider profile. - Optimizing for the wrong batch. Setting
optShapesto 1 and then serving batches of 32 gives slower kernels than necessary. - Comparing unlike numbers.
trtexecmean latency with overlapped transfers is not comparable to a Python loop that runs synchronously. Match the protocol first. - Reusing a stale engine. After a driver, CUDA, or TensorRT upgrade, rebuild. A load failure or a version-mismatch message is the usual sign.
When to use trtexec rather than the TensorRT provider
Use trtexec to establish a baseline and to debug. If trtexec is fast and parses everything, the ONNX Runtime TensorRT provider will usually be close, and you keep one runtime for pre- and postprocessing. If trtexec shows that TensorRT cannot parse key operators, or you need minimal overhead and control of memory in a C++ service, build engines yourself and load them with the TensorRT runtime.
Exercise
You built an engine with --minShapes=input:1x3x224x224 --optShapes=input:8x3x224x224 --maxShapes=input:32x3x224x224 --fp16. Your service mostly receives batches of 4, with occasional batches of 64. Name two problems and say what you would do for each.
Show answer
Batches of 64 exceed maxShapes and will fail, so rebuild the engine with a larger max (for example 64), or split large requests into batches of 32 or fewer. Since most traffic is batch 4, optShapes=8 is not the best tuning point, so set optShapes to 4 (or build separate profiles) and re-benchmark. Also run a parity check on the FP16 engine against PyTorch, because the precision flag changed the computation.
Exercise
A trtexec run reports a median latency of 6 ms but a GPU Compute Time of 1.5 ms. What does this suggest, and which options would you try first?
Show answer
Most of the time is spent outside the network: host-to-device and device-to-host copies, or launch overhead. Try a larger batch to amortize the overhead, use pinned memory and I/O binding (or keep tensors on the GPU) in the application, and check Enqueue time to see whether the CPU is the bottleneck. A faster precision mode would help little here.