{ "cells": [ { "cell_type": "markdown", "id": "0", "metadata": {}, "source": [ "# Panoptic Segmentation Model Export - EoMT\n", "\n", "[![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/lightly-ai/lightly-train/blob/main/examples/notebooks/eomt_panoptic_segmentation_export.ipynb)\n", "\n", "This notebook demonstrates how to export a panoptic segmentation model to ONNX and TensorRT.\n", "\n", "The notebook covers the following steps:\n", "1. Install LightlyTrain\n", "2. Export a trained EoMT model to ONNX\n", "3. Export a trained EoMT model to TensorRT\n", "4. Run inference with the TensorRT engine\n", "\n", "> **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." ] }, { "cell_type": "code", "execution_count": null, "id": "1", "metadata": {}, "outputs": [], "source": [ "!pip install \"lightly-train[onnx,onnxruntime,onnxslim]\"" ] }, { "cell_type": "markdown", "id": "2", "metadata": {}, "source": [ "## Export to ONNX\n", "\n", "### Load the model weights\n", "\n", "Then load the model with LightlyTrain's `load_model` function. This will automatically download the model weights and load the model." ] }, { "cell_type": "code", "execution_count": null, "id": "3", "metadata": {}, "outputs": [], "source": [ "import lightly_train\n", "\n", "model = lightly_train.load_model(\"dinov3/vits16-eomt-panoptic-coco\")" ] }, { "cell_type": "markdown", "id": "4", "metadata": {}, "source": [ "### Download an example image\n", "\n", "Download an example image for inference with the following command:" ] }, { "cell_type": "code", "execution_count": null, "id": "5", "metadata": {}, "outputs": [], "source": [ "!wget -O image.jpg http://images.cocodataset.org/val2017/000000105264.jpg" ] }, { "cell_type": "markdown", "id": "6", "metadata": {}, "source": [ "### Preprocessing" ] }, { "cell_type": "code", "execution_count": null, "id": "7", "metadata": {}, "outputs": [], "source": [ "import torch\n", "import torchvision.transforms.v2 as T\n", "from PIL import Image\n", "from torchvision.transforms.functional import pil_to_tensor\n", "\n", "# Load image with PIL.\n", "image_pil = Image.open(\"image.jpg\").convert(\"RGB\")\n", "\n", "# Convert PIL image to tensor for plotting.\n", "image_tensor = pil_to_tensor(image_pil)\n", "\n", "# Define pre-processing transforms.\n", "w, h = image_pil.size\n", "transforms = T.Compose(\n", " [\n", " T.Resize((model.image_size)),\n", " T.ToTensor(),\n", " T.Normalize(**model.image_normalize),\n", " ]\n", ")\n", "\n", "# Apply transforms for ONNX and TensorRT inference.\n", "image_tensor_transformed = transforms(image_pil)[None]" ] }, { "cell_type": "markdown", "id": "8", "metadata": {}, "source": [ "### Get the model predictions for reference\n", "\n", "We define a helper function to visualize the predictions.\n", "The function will be used to compare the predictions from PyTorch, ONNX and\n", "TensorRT models." ] }, { "cell_type": "code", "execution_count": null, "id": "9", "metadata": {}, "outputs": [], "source": [ "import matplotlib.pyplot as plt\n", "from torchvision.utils import draw_segmentation_masks\n", "\n", "\n", "def visualize_segmentations(image, masks, segment_ids):\n", " # masks is (H, W, 2)\n", " # segment_ids is (num_segments)\n", "\n", " # Convert masks to boolean masks for each segment\n", " # masks[..., 1] contains the segment id for each pixel.\n", " # We add a mask for unassigned pixels (segment id -1).\n", " masks_bool = torch.stack(\n", " [masks[..., 1] == -1]\n", " + [masks[..., 1] == segment_id for segment_id in segment_ids]\n", " )\n", "\n", " # Create colors for visualization\n", " colors = [(0, 0, 0)] + [\n", " [int(color * 255) for color in plt.cm.tab20c(i / len(segment_ids))[:3]]\n", " for i in range(len(segment_ids))\n", " ]\n", "\n", " image_with_masks = draw_segmentation_masks(\n", " image, masks_bool, colors=colors, alpha=1.0\n", " )\n", "\n", " fig, axs = plt.subplots(1, 2, figsize=(12, 8))\n", " axs[0].imshow(image.permute(1, 2, 0))\n", " axs[0].axis(\"off\")\n", " axs[1].imshow(image_with_masks.permute(1, 2, 0))\n", " axs[1].axis(\"off\")\n", " fig.show()" ] }, { "cell_type": "code", "execution_count": null, "id": "10", "metadata": {}, "outputs": [], "source": [ "# Get predictions from the PyTorch model.\n", "results = model.predict(image_tensor)\n", "\n", "# Visualize predictions from the PyTorch model.\n", "visualize_segmentations(\n", " image_tensor, masks=results[\"masks\"], segment_ids=results[\"segment_ids\"]\n", ")" ] }, { "cell_type": "markdown", "id": "11", "metadata": {}, "source": [ "### Export the model to ONNX" ] }, { "cell_type": "code", "execution_count": null, "id": "12", "metadata": {}, "outputs": [], "source": [ "# Export the PyTorch model to ONNX.\n", "model.export_onnx(\n", " out=\"model.onnx\",\n", " # precision=\"fp16\", # Export model with FP16 weights for smaller size and faster inference.\n", ")" ] }, { "cell_type": "markdown", "id": "13", "metadata": {}, "source": [ "See [`export_onnx`](https://docs.lightly.ai/train/stable/python_api/lightly_train.html#lightly_train._task_models.dinov3_eomt_panoptic_segmentation.task_model.DINOv3EoMTPanopticSegmentation.export_onnx) for all available options when exporting to ONNX.\n" ] }, { "cell_type": "markdown", "id": "14", "metadata": {}, "source": [ "### Run inference with the ONNX model" ] }, { "cell_type": "code", "execution_count": null, "id": "15", "metadata": {}, "outputs": [], "source": [ "import onnxruntime as ort\n", "import torch.nn.functional as F\n", "\n", "# Create an ONNX Runtime session.\n", "sess = ort.InferenceSession(\"model.onnx\")\n", "\n", "# Get expected input dtype.\n", "input_dtype = sess.get_inputs()[0].type\n", "input_dtype_numpy = {\n", " \"tensor(float)\": \"float32\",\n", " \"tensor(float16)\": \"float16\",\n", "}[input_dtype]\n", "\n", "# Run inference.\n", "outputs = sess.run(\n", " output_names=None,\n", " input_feed={\n", " \"images\": image_tensor_transformed.numpy().astype(input_dtype_numpy),\n", " },\n", ")\n", "\n", "masks_onnx = outputs[0]\n", "segment_ids_onnx = outputs[1]\n", "scores_onnx = outputs[2]\n", "\n", "# Resize ONNX predictions to original image size if necessary.\n", "masks_onnx = torch.from_numpy(masks_onnx)\n", "masks_onnx = masks_onnx.permute(0, 3, 1, 2).float() # (1, 2, H_model, W_model)\n", "# (1, 2, H_orig, W_orig)\n", "masks_onnx = F.interpolate(masks_onnx, size=(h, w), mode=\"nearest\")\n", "masks_onnx = masks_onnx.permute(0, 2, 3, 1).long() # (1, H_orig, W_orig, 2)\n", "\n", "# Visualize predictions from the ONNX model.\n", "visualize_segmentations(\n", " image_tensor, masks=masks_onnx[0], segment_ids=segment_ids_onnx[0]\n", ")" ] }, { "cell_type": "markdown", "id": "16", "metadata": {}, "source": [ "## Export to TensorRT" ] }, { "cell_type": "markdown", "id": "17", "metadata": {}, "source": [ "### Requirements\n", "\n", "TensorRT is not part of LightlyTrain’s dependencies and must be installed separately. Installation depends on your OS, Python\n", "version, GPU, and NVIDIA driver/CUDA setup. See the [TensorRT documentation](https://docs.nvidia.com/deeplearning/tensorrt/latest/installing-tensorrt/installing.html) for more details.\n", "\n", "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:" ] }, { "cell_type": "code", "execution_count": null, "id": "18", "metadata": {}, "outputs": [], "source": [ "!pip install \"tensorrt-cu12==10.13.3.9\"" ] }, { "cell_type": "code", "execution_count": null, "id": "19", "metadata": {}, "outputs": [], "source": [ "# Get the TensorRT engine.\n", "model.export_tensorrt(\n", " out=\"model.trt\",\n", " # precision=\"fp16\", # Export model with FP16 weights for smaller size and faster inference.\n", ")" ] }, { "cell_type": "markdown", "id": "20", "metadata": {}, "source": [ "See [`export_tensorrt`](https://docs.lightly.ai/train/stable/python_api/lightly_train.html#lightly_train._task_models.dinov3_eomt_panoptic_segmentation.task_model.DINOv3EoMTPanopticSegmentation.export_tensorrt) for all available options when exporting to TensorRT.\n" ] }, { "cell_type": "markdown", "id": "21", "metadata": {}, "source": [ "### Run inference with the TensorRT engine" ] }, { "cell_type": "code", "execution_count": null, "id": "22", "metadata": {}, "outputs": [], "source": [ "import numpy as np\n", "import tensorrt as trt\n", "import torch\n", "\n", "\n", "class TRT:\n", " def __init__(\n", " self,\n", " engine_path: str,\n", " num_queries: int,\n", " device: str = \"cuda:0\",\n", " verbose: bool = False,\n", " ):\n", " self.device = torch.device(device)\n", " logger = trt.Logger(trt.Logger.VERBOSE if verbose else trt.Logger.INFO)\n", " trt.init_libnvinfer_plugins(logger, \"\")\n", " runtime = trt.Runtime(logger)\n", "\n", " with open(engine_path, \"rb\") as f:\n", " self.engine = runtime.deserialize_cuda_engine(f.read())\n", " self.context = self.engine.create_execution_context()\n", "\n", " io_names = [\n", " self.engine.get_tensor_name(i) for i in range(self.engine.num_io_tensors)\n", " ]\n", " self.in_names = [\n", " n\n", " for n in io_names\n", " if self.engine.get_tensor_mode(n) == trt.TensorIOMode.INPUT\n", " ]\n", " self.out_names = [\n", " n\n", " for n in io_names\n", " if self.engine.get_tensor_mode(n) == trt.TensorIOMode.OUTPUT\n", " ]\n", "\n", " self.buffers = {}\n", " self.bindings = []\n", " for name in io_names:\n", " shape = tuple(self.context.get_tensor_shape(name))\n", " shape = [s if s != -1 else num_queries for s in shape]\n", " np_dtype = trt.nptype(self.engine.get_tensor_dtype(name))\n", " torch_dtype = torch.from_numpy(np.empty((), dtype=np_dtype)).dtype\n", " buffer = torch.empty(\n", " shape, device=self.device, dtype=torch_dtype\n", " ).contiguous()\n", " self.buffers[name] = buffer\n", " self.bindings.append(buffer.data_ptr())\n", "\n", " @torch.no_grad()\n", " def __call__(self, inputs: dict[str, torch.Tensor]) -> dict[str, torch.Tensor]:\n", " for name in self.in_names:\n", " self.buffers[name].copy_(inputs[name].to(self.device))\n", " if not self.context.execute_v2(self.bindings):\n", " raise RuntimeError(\"TensorRT execution failed\")\n", " return {name: self.buffers[name] for name in self.out_names}" ] }, { "cell_type": "code", "execution_count": null, "id": "23", "metadata": {}, "outputs": [], "source": [ "# Instantiate the TensorRT model.\n", "trt_model = TRT(\"model.trt\", num_queries=model.num_queries)\n", "\n", "# Run inference with the TensorRT model.\n", "outputs_trt = trt_model({\"images\": image_tensor_transformed})\n", "\n", "masks_trt = outputs_trt[\"masks\"][0]\n", "segment_ids_trt = outputs_trt[\"segment_ids\"][0]\n", "scores_trt = outputs_trt[\"scores\"][0]\n", "\n", "# Filter out segments with scores below threshold. This is required because TensorRT\n", "# returns scores and segment ids for all possible segments.\n", "keep = scores_trt > 0.8\n", "segment_ids_trt = segment_ids_trt[keep]\n", "scores_trt = scores_trt[keep]\n", "\n", "# Resize TensorRT predictions to original image size if necessary.\n", "masks_trt = masks_trt.permute(2, 0, 1).float()\n", "masks_trt = masks_trt.unsqueeze(0)\n", "masks_trt = F.interpolate(masks_trt, size=(h, w), mode=\"nearest\")\n", "masks_trt = masks_trt.squeeze(0).permute(1, 2, 0).long()\n", "\n", "# Visualize predictions from the TensorRT model.\n", "visualize_segmentations(\n", " image_tensor, masks=masks_trt.cpu(), segment_ids=segment_ids_trt.cpu()\n", ")" ] } ], "metadata": { "kernelspec": { "display_name": "python3", "language": "python", "name": "python3" } }, "nbformat": 4, "nbformat_minor": 5 }