Object Detection Model Export - LTDETRv2¶
This notebook demonstrates how to export an object detection model to ONNX and TensorRT.
The notebook covers the following steps:
Install LightlyTrain
Export a trained LTDETR model to ONNX
Export a trained LTDETR model to TensorRT
Run inference with the TensorRT engine
Important: When running on Google Colab make sure to select a GPU runtime. You can do this by going to
Runtime>Change runtime typeand 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
Preprocessing¶
import torchvision.transforms.v2 as T
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.
image_tensor = pil_to_tensor(image_pil)
# Define pre-processing transforms.
w, h = image_pil.size
transforms = T.Compose(
[
T.Resize((model.image_size)),
T.ToTensor(),
T.Normalize(**model.image_normalize) if model.image_normalize else T.Identity(),
]
)
# Apply transforms for ONNX and TensorRT inference.
image_tensor_transformed = transforms(image_pil)[None]
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.
Run inference with the ONNX model¶
import onnxruntime as ort
import torch
# 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]
labels_onnx, boxes_onnx, scores_onnx = sess.run(
output_names=None,
input_feed={
"images": image_tensor_transformed.numpy().astype(input_dtype_numpy),
},
)
# The ONNX model does not filter by score, so we do it here.
keep = scores_onnx > 0.6
labels_onnx = labels_onnx[keep]
boxes_onnx = boxes_onnx[keep]
scores_onnx = scores_onnx[keep]
# The ONNX model does not resize boxes to original image size, so we do it here.
scale_x = w / model.image_size[1]
scale_y = h / model.image_size[0]
boxes_onnx[:, 0] *= scale_x # x1
boxes_onnx[:, 2] *= scale_x # x2
boxes_onnx[:, 1] *= scale_y # y1
boxes_onnx[:, 3] *= scale_y # y2
# Visualize predictions from the ONNX model.
visualize_detections(
image_tensor,
boxes=torch.from_numpy(boxes_onnx).squeeze(0),
labels=torch.from_numpy(labels_onnx).squeeze(0),
classes=model.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
]
self.buffers = {}
self.bindings = []
for name in io_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()
self.buffers[name] = buffer
self.bindings.append(buffer.data_ptr())
@torch.no_grad()
def __call__(self, inputs: dict[str, torch.Tensor]) -> dict[str, torch.Tensor]:
for name in self.in_names:
self.buffers[name].copy_(inputs[name].to(self.device))
if not self.context.execute_v2(self.bindings):
raise RuntimeError("TensorRT execution failed")
return {name: self.buffers[name] for name in self.out_names}
# Instantiate the TensorRT model.
trt_model = TRT("model.trt")
# Run inference with the TensorRT model.
outputs_trt = trt_model({"images": image_tensor_transformed})
labels_trt = outputs_trt["labels"]
boxes_trt = outputs_trt["boxes"]
scores_trt = outputs_trt["scores"]
# The TensorRT model does not filter by score, so we do it here.
keep = scores_trt > 0.6
labels_trt = labels_trt[keep]
boxes_trt = boxes_trt[keep]
scores_trt = scores_trt[keep]
# The TensorRT model does not resize boxes to original image size, so we do it here.
scale_x = w / model.image_size[1]
scale_y = h / model.image_size[0]
boxes_trt[:, 0] *= scale_x # x1
boxes_trt[:, 2] *= scale_x # x2
boxes_trt[:, 1] *= scale_y # y1
boxes_trt[:, 3] *= scale_y # y2
# Visualize predictions from the TensorRT model.
visualize_detections(
image_tensor,
boxes=boxes_trt.squeeze(0),
labels=labels_trt.squeeze(0),
classes=model.classes,
)