Object Detection Model Export - LTDETRv2

Open In Colab

This notebook demonstrates how to export an object detection model to ONNX and TensorRT.

The notebook covers the following steps:

  1. Install LightlyTrain

  2. Export a trained LTDETR model to ONNX

  3. Export a trained LTDETR model to TensorRT

  4. Run inference with the TensorRT engine

The image size and normalization used for preprocessing are baked into the exported files: the image size as the static images input shape, and the normalization statistics and class names as ONNX metadata. This means the ONNX and TensorRT inference cells read everything they need directly from the exported files and do not require LightlyTrain to be installed.

Important: When running on Google Colab make sure to select a GPU runtime. You can do this by going to Runtime > Change runtime type and selecting a GPU hardware accelerator.

!pip install "lightly-train[onnx,onnxruntime,onnxslim]"

Export to ONNX

Load the model weights

Then load the model with LightlyTrain’s load_model function. This will automatically download the model weights and load the model.

import lightly_train

model = lightly_train.load_model("ltdetrv2-s-coco")

Download an example image

Download an example image for inference with the following command:

!wget -O image.jpg http://images.cocodataset.org/val2017/000000039769.jpg

Load the example image

Load the image once. The raw tensor is used both for the reference PyTorch prediction and for visualization. Preprocessing is deferred until after export, where the required image size and normalization are read back from the exported ONNX file.

from PIL import Image
from torchvision.transforms.functional import pil_to_tensor

# Load image with PIL.
image_pil = Image.open("image.jpg").convert("RGB")

# Convert PIL image to tensor for plotting and the reference prediction.
image_tensor = pil_to_tensor(image_pil)

# Original image size, used to rescale boxes back after inference.
w, h = image_pil.size

Get the model predictions for reference

We define a helper function to visualize the predictions. The function will be used to compare the predictions from PyTorch, ONNX and TensorRT models.

import matplotlib.pyplot as plt
from torchvision.utils import draw_bounding_boxes


def visualize_detections(image, boxes, labels, classes):
    image_with_boxes = draw_bounding_boxes(
        image,
        boxes=boxes,
        labels=[classes[label.item()] for label in labels],
    )
    plt.imshow(image_with_boxes.permute(1, 2, 0))
    plt.axis("off")
    plt.show()
# Get predictions from the PyTorch model.
labels_torch, boxes_torch, _ = model.predict(image_tensor, threshold=0.6).values()

# Visualize predictions from the PyTorch model.
visualize_detections(
    image_tensor, boxes=boxes_torch, labels=labels_torch, classes=model.classes
)

Export the model to ONNX

# Export the PyTorch model to ONNX.
model.export_onnx(
    out="model.onnx",
    # precision="fp16", # Export model with FP16 weights for smaller size and faster inference.
)

See export_onnx for all available options when exporting to ONNX.

Read the baked-in preprocessing from the exported file

The steps below read the image size, normalization statistics, and class names directly from the exported ONNX file. This is all that is needed to preprocess an image and interpret the outputs, so the remaining inference cells do not depend on LightlyTrain.

import json

import onnx
import torch
import torchvision.transforms.v2 as T
from torchvision.ops import box_convert

# Read the baked-in metadata from the ONNX file (no LightlyTrain required).
onnx_model = onnx.load("model.onnx")
metadata = {entry.key: entry.value for entry in onnx_model.metadata_props}

# Class names, as a {class_id: name} mapping.
classes = {int(k): v for k, v in json.loads(metadata["classes"]).items()}

# Normalization statistics, if any were baked in.
image_normalize = (
    json.loads(metadata["image_normalize"]) if "image_normalize" in metadata else None
)

# Image size is baked into the static height/width of the "images" input.
images_input = onnx_model.graph.input[0].type.tensor_type.shape.dim
image_size = (images_input[2].dim_value, images_input[3].dim_value)  # (H, W)

# Build the preprocessing transform from the file-derived values.
transforms = T.Compose(
    [
        T.Resize(image_size),
        T.ToTensor(),
        T.Normalize(**image_normalize) if image_normalize else T.Identity(),
    ]
)

# Apply transforms for ONNX and TensorRT inference.
image_tensor_transformed = transforms(image_pil)[None]


def postprocess_detections(logits, boxes, threshold=0.6):
    """Decode the raw graph outputs into labels, boxes, and scores.

    The exported graph returns raw class ``logits`` of shape ``(1, num_queries,
    num_classes)`` and normalized ``cxcywh`` boxes of shape ``(1, num_queries, 4)``.
    Applying a sigmoid, keeping detections above the score threshold, and rescaling
    the boxes to the original image reproduces what ``model.predict`` returns.
    """
    scores = logits[0].sigmoid()
    num_classes = scores.shape[-1]
    boxes_xyxy = box_convert(boxes[0], in_fmt="cxcywh", out_fmt="xyxy")

    scores_flat = scores.flatten()
    # Match model.predict: select the best num_queries class/query pairs first,
    # then apply the score threshold.
    scores, flat_index = scores_flat.topk(logits.shape[1])
    keep = scores > threshold
    scores = scores[keep]
    flat_index = flat_index[keep]
    query_index = flat_index // num_classes
    class_index = flat_index % num_classes

    # Boxes are normalized to [0, 1]; scale them to the original image size.
    boxes = boxes_xyxy[query_index] * torch.tensor([w, h, w, h], dtype=boxes_xyxy.dtype)

    # Map internal class indices back to the dataset class ids from the metadata.
    class_ids = list(classes.keys())
    labels = torch.tensor([class_ids[int(i)] for i in class_index])
    return labels, boxes, scores

Run inference with the ONNX model

The exported graph returns raw class logits and normalized boxes (top-k selection, thresholding, and box rescaling are intentionally kept outside the graph), so we decode them with the postprocess_detections helper defined above.

import onnxruntime as ort

# Create an ONNX Runtime session.
sess = ort.InferenceSession("model.onnx")

# Get expected input dtype.
input_dtype = sess.get_inputs()[0].type
input_dtype_numpy = {
    "tensor(float)": "float32",
    "tensor(float16)": "float16",
}[input_dtype]

# The graph outputs raw logits and normalized cxcywh boxes.
logits_onnx, boxes_onnx = sess.run(
    output_names=None,
    input_feed={
        "images": image_tensor_transformed.numpy().astype(input_dtype_numpy),
    },
)

# Decode to labels, boxes, and scores (see postprocess_detections above).
labels_onnx, boxes_onnx, scores_onnx = postprocess_detections(
    torch.from_numpy(logits_onnx).float(), torch.from_numpy(boxes_onnx).float()
)

# Visualize predictions from the ONNX model.
visualize_detections(
    image_tensor, boxes=boxes_onnx, labels=labels_onnx, classes=classes
)

Export to TensorRT

Requirements

TensorRT is not part of LightlyTrain’s dependencies and must be installed separately. Installation depends on your OS, Python version, GPU, and NVIDIA driver/CUDA setup. See the TensorRT documentation for more details.

On CUDA 12.x systems, install the TensorRT version tested with this tutorial. Pinning the version prevents pip from installing TensorRT 11, which is not yet supported by LightlyTrain:

!pip install "tensorrt-cu12==10.13.3.9"
# Get the TensorRT engine.
model.export_tensorrt(
    out="model.trt",
    # precision="fp16", # Export model with FP16 weights for smaller size and faster inference.
)

See export_tensorrt for all available options when exporting to TensorRT.

Run inference with the TensorRT engine

import numpy as np
import tensorrt as trt
import torch


class TRT:
    def __init__(self, engine_path: str, device: str = "cuda:0", verbose: bool = False):
        self.device = torch.device(device)
        logger = trt.Logger(trt.Logger.VERBOSE if verbose else trt.Logger.INFO)
        trt.init_libnvinfer_plugins(logger, "")
        runtime = trt.Runtime(logger)

        with open(engine_path, "rb") as f:
            self.engine = runtime.deserialize_cuda_engine(f.read())
        self.context = self.engine.create_execution_context()

        io_names = [
            self.engine.get_tensor_name(i) for i in range(self.engine.num_io_tensors)
        ]
        self.in_names = [
            n
            for n in io_names
            if self.engine.get_tensor_mode(n) == trt.TensorIOMode.INPUT
        ]
        self.out_names = [
            n
            for n in io_names
            if self.engine.get_tensor_mode(n) == trt.TensorIOMode.OUTPUT
        ]

    @torch.no_grad()
    def __call__(self, inputs: dict[str, torch.Tensor]) -> dict[str, torch.Tensor]:
        buffers = {}
        # Bind the inputs and set their shapes before querying output shapes.
        for name in self.in_names:
            np_dtype = trt.nptype(self.engine.get_tensor_dtype(name))
            torch_dtype = torch.from_numpy(np.empty((), dtype=np_dtype)).dtype
            tensor = inputs[name].to(device=self.device, dtype=torch_dtype).contiguous()
            self.context.set_input_shape(name, tuple(tensor.shape))
            buffers[name] = tensor
            self.context.set_tensor_address(name, tensor.data_ptr())
        # Output shapes are only known once the input shapes are set.
        for name in self.out_names:
            shape = tuple(self.context.get_tensor_shape(name))
            np_dtype = trt.nptype(self.engine.get_tensor_dtype(name))
            torch_dtype = torch.from_numpy(np.empty((), dtype=np_dtype)).dtype
            buffer = torch.empty(
                shape, device=self.device, dtype=torch_dtype
            ).contiguous()
            buffers[name] = buffer
            self.context.set_tensor_address(name, buffer.data_ptr())
        success = self.context.execute_async_v3(torch.cuda.current_stream().cuda_stream)
        if not success:
            raise RuntimeError("TensorRT execution failed")
        torch.cuda.synchronize()
        return {name: buffers[name] for name in self.out_names}
# Instantiate the TensorRT model.
trt_model = TRT("model.trt")

# Run inference with the TensorRT model. The graph outputs raw logits and boxes.
outputs_trt = trt_model({"images": image_tensor_transformed})

# Decode to labels, boxes, and scores (see postprocess_detections above).
labels_trt, boxes_trt, scores_trt = postprocess_detections(
    outputs_trt["logits"].float().cpu(), outputs_trt["boxes"].float().cpu()
)

# Visualize predictions from the TensorRT model.
visualize_detections(image_tensor, boxes=boxes_trt, labels=labels_trt, classes=classes)