
Recall first from Mesa drivers and CUDA graphics interop
- On Raspberry Pi 4 and 5, V3D renders and VC4 handles display.
- CUDA can write a registered OpenGL pixel buffer while it is mapped.
- An OpenGL upload from a pixel buffer avoids a CPU pixel round trip and updates separate texture storage.
Export the trained model to ONNX
2 min readYou have rendered on the GPU. Now it runs neural networks, and this lesson answers how a trained model becomes a TensorRT engine through ONNX and trtexec.
A camera classifier can give wrong predictions even when the engine loads and every inference call succeeds. For example, a trained ResNet expects pixels to be resized and normalised in a particular way. If the application feeds raw pixels as floating-point numbers, the engine can still receive a tensor with the expected dimensions and type. That is why deployment starts by recording the model's input contract, including preprocessing, before measuring speed.
During training, a framework evaluates the model, computes a loss against the training objective and uses gradients to update its weights. During inference, it evaluates the model with those weights fixed. For image classification, the result is a vector of class scores. A model in PyTorch evaluation mode also uses inference behaviour for layers such as batch normalisation and dropout. Calling eval() selects that behaviour. Disabling gradient tracking is a separate operation.
Open Neural Network Exchange is an interchange format for representing a model as a graph with operators, tensor inputs and outputs, and initialisers such as trained weights. The export records the computation and its tensor interface. An ONNX opset identifies a version of the operator definitions used in the graph. The exporter and TensorRT parser must agree on operators and semantics. A valid ONNX model can still contain an operator or an operator configuration the parser cannot import.
Use pretrained torchvision ResNet-18 for a small, fixed-shape example. Run the following on Ubuntu with PyTorch, torchvision and ONNX installed. The first use of the pretrained weights may download them if they are absent from the local cache. The example explicitly uses the PyTorch exporter mode that supports the dynamic_axes option used later.
python3 - <<'PY'
import onnx
import torch
from torchvision.models import ResNet18_Weights, resnet18
weights = ResNet18_Weights.DEFAULT
model = resnet18(weights=weights).eval()
sample = torch.zeros(1, 3, 224, 224, dtype=torch.float32)
torch.onnx.export(
model, (sample,), "resnet18.onnx",
input_names=["images"], output_names=["logits"],
opset_version=17, dynamo=False,
)
graph = onnx.load("resnet18.onnx")
onnx.checker.check_model(graph)
for tensor in (*graph.graph.input, *graph.graph.output):
print(tensor.name, tensor.type.tensor_type)
PY
The input images has dimensions 1×3×224×224 in batch, channel, height, width order. The zero tensor supplies the exporter with an example of the input interface. For real images, prepare RGB data using weights.transforms(), then add a batch dimension to the resulting tensor. Keep the same preprocessing for the framework reference and engine runs. The logits output contains scores before softmax. Comparing those scores or the classes they rank requires the same image and class mapping on both sides.
For a TensorFlow model, first export a SavedModel with its inference signature, then use a compatible tf2onnx installation to convert it with python3 -m tf2onnx.convert --saved-model saved_model --opset 17 --output model.onnx. Check the exported names, dimensions and types before using the file. A TensorFlow model may expose channels last, so read its actual signature before constructing input tensors or specifying shapes. In either framework, ONNX structural validation and comparison against the original model answer separate questions about the export.
Build and run a TensorRT engine
3 min readUse the machine where the engine will run for the first build. A Raspberry Pi or BeagleBone alone cannot run this CUDA-based lab. Use an Ubuntu 24.04 system with a supported NVIDIA GPU and TensorRT installed. A WSL2 environment or VM qualifies if it exposes the supported GPU and has a working NVIDIA software stack. Check trtexec --help on that system. The precision-flag commands below target TensorRT 10.x installations that list these flags. TensorRT 11 removes --fp16, --int8 and --best in favour of strongly typed networks. With a strongly typed workflow, precision comes from the model's types and explicit quantisation operations.
trtexec is an NVIDIA command-line program that can build, serialise, load and benchmark engines. With --onnx, it parses the ONNX graph into a TensorRT network. The builder optimises the network for the specified constraints and produces a serialised engine, also called a plan. --saveEngine writes that plan to disk. --loadEngine opens the plan for a later run. Treat a default plan as specific to its build platform, GPU and TensorRT environment. Save the ONNX file and build command so you can rebuild for another target.
trtexec --onnx=resnet18.onnx --fp16 \
--saveEngine=resnet18-fp16.engine
trtexec --loadEngine=resnet18-fp16.engine
On this build path, --fp16 permits half-precision implementations where the builder can use them. The builder can select other permitted precisions for individual layers. The filename records the requested build configuration. The ONNX input remains a float32 tensor in this example. Internal compute precision and the application's input buffer type are separate properties. For a build that prioritises performance across the precisions offered by this CLI, --best enables the available precision choices. It does not set or enforce an accuracy target.
For the INT8 smoke test, use the same float ONNX file with the legacy --int8 path. This option permits INT8 tactics. Pair it with --fp16 here to allow FP16 implementations where appropriate. The build can produce a mixed-precision engine.
trtexec --onnx=resnet18.onnx --int8 --fp16 \
--saveEngine=resnet18-int8-smoke.engine
trtexec --loadEngine=resnet18-int8-smoke.engine
{{< callout type="warning" >}}
With a floating-point ONNX graph and the legacy --int8 path, trtexec has no real calibration data to work from when no calibration cache is provided, so the INT8 scales it uses are placeholders. Use this plan for an execution smoke test only. For an accuracy evaluation, use an explicitly quantised ONNX model with quantise and dequantise operations and representative scales, or use a matching calibration cache with a TensorRT version that supports the legacy path. The later lesson on INT8 quantisation and the DLA covers how those scales are obtained.
{{< /callout >}}
Check the build and reload commands separately. Linux starts the program with the supplied arguments, and the shell obtains the child's termination status. An engine file left over from an earlier run can still exist after a new build fails. Save to fresh lab filenames or check that the build succeeded before reloading. See the Linux manual pages for execve(2) and wait(2).
The reload command runs inference with generated input by default. A successful run establishes that the plan deserialises and executes on this setup. To check predictions, use real preprocessed images and compare outputs with the original model. With this fixed-shape example, save one contiguous float32 images tensor as raw bytes using the NumPy array's tofile("image.bin") method. Feed that file with --loadInputs=images:image.bin and inspect the resulting scores with --dumpOutput. Use the same sample and shape when comparing engines. Record the build settings with any timing you report so another reader can reproduce the run.
Choose shape bounds and builder settings
3 min readExport a dynamic batch dimension when the application needs to accept different batch sizes with one engine. In the PyTorch example, change the output filename to resnet18-dynamic.onnx and add dynamic_axes={"images": {0: "batch"}, "logits": {0: "batch"}} to the export call. Load the new filename in the checker as well. The channel count, height and width stay fixed in this export. Specifying a wider batch range at build time requires that the ONNX batch axis already be dynamic.
An optimisation profile gives the builder minimum, preferred and maximum dimensions for each dynamic input. Use --minShapes and --maxShapes to set the allowed bounds, and --optShapes to tell the builder the shape to optimise around. For example, an application that usually classifies one image at a time but sometimes receives a batch of four could use the following profile. The text before each colon is the input name from ONNX.
trtexec --onnx=resnet18-dynamic.onnx --fp16 \
--minShapes=images:1x3x224x224 \
--optShapes=images:1x3x224x224 \
--maxShapes=images:4x3x224x224 \
--saveEngine=resnet18-dynamic.engine
trtexec --loadEngine=resnet18-dynamic.engine \
--shapes=images:4x3x224x224
--shapes selects concrete dimensions for a run. Here batches one through four fit the profile, and batch five exceeds it. An engine with multiple profiles can cover different operating ranges. In a deployed application, the execution context uses a profile that covers the requested dimensions. Set the profile limits from actual application requirements. Broad bounds may exclude implementations that require narrower bounds or dimensions fixed across the profile.
A tactic is a candidate implementation of a layer or fused group. The builder considers factors such as input dimensions, supported precision and temporary memory. For example, it may fuse a convolution, a bias addition and a ReLU into one implementation where the graph and selected tactic permit it. A naive graph executor could launch separate kernels and write intermediate tensors to device memory between them. Fusion can avoid those launches and intermediate writes, which is one reason an engine can run faster. The gain depends on the graph, the chosen tactics and the input shapes.
Workspace is temporary memory certain tactics need. Where the CLI exposes --memPoolSize, the workspace pool limit can be set with a value such as --memPoolSize=workspace:256. In this syntax the workspace value is in MiB. A tight cap can exclude faster tactics and can prevent a build when no eligible implementation fits. The cap applies to this memory pool, so budget separately for other allocations such as weights and input and output buffers. --builderOptimizationLevel controls how much optimisation effort the builder is allowed to spend. Higher levels can take longer to build and may produce a faster plan. When comparing levels, keep the model, profile and test shape fixed so the build setting is the variable you are testing.
The next lesson, Layers as GEMM and FP16 vs FP32, looks at the arithmetic inside common network layers and explains why the choice of compute precision can change GPU execution time.
Key takeaways
- Inference runs a trained model with fixed weights.
- ONNX describes the model graph, weights and tensor interface.
- TensorRT builds a serialised engine with implementations selected for the target.
- A successful engine run with generated input establishes execution, while accuracy requires representative samples and reference results.
Reflect
- Explain to a colleague, in two sentences: export a trained ResNet with named ONNX inputs and outputs.
- Which objective are you least sure about? Re-read that section, then do its exercise in the practice pack.
- What surprised you when you ran the commands yourself?
On a real board
Repeat the key commands on your Raspberry Pi or lab board over SSH or the serial console. Note anything that behaves differently from your PC, such as missing tools, a BusyBox shell or a read-only filesystem.
References and further reading
- DocumentationNVIDIA TensorRT documentation
- DocumentationTensorRT best practices (performance)
- DocumentationTensorRT: working with quantized types
- Man pageexecve(2): execute a program
- Man pagewait(2): wait for a child process to change state
Official documentation first. Links checked when the lesson was published.