Depth Estimation Model Export (ONNX and TensorRT)

Open In Colab

This notebook demonstrates how to export a depth estimation model to ONNX and TensorRT.

The notebook covers the following steps:

  1. Install LightlyTrain

  2. Export a Depth Anything model to ONNX

  3. Export a Depth Anything model to TensorRT

  4. 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 type and selecting a GPU hardware accelerator.

Installation

!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 numpy as np
import onnxruntime as ort
import torch

import lightly_train

model = lightly_train.load_model("dinov2/dav2-relative-small")

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

from PIL import Image

# Precision used for the exported ONNX and TensorRT models.
precision = "fp32"

# The Depth Anything models process images at a fixed square resolution.
height = width = model.image_size

# Load the image and resize it to the model's processing resolution.
img = Image.open("image.jpg").convert("RGB")
img = img.resize((width, height), resample=Image.BILINEAR)

# The depth model handles its own pre-processing (resize and normalization), so we
# build the input batch with the model's preprocessing helpers instead of torchvision
# transforms.
x, meta = model.preprocess_image(img)
batch = model.preprocess_batch([x])

# Build the ONNX input feed with the dtype matching the export precision.
if precision == "fp16":
    inputs = {"images": batch.cpu().numpy().astype(np.float16)}
else:
    inputs = {"images": batch.cpu().numpy()}

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


def visualize_depth(image, depth):
    fig, axes = plt.subplots(1, 2, figsize=(14, 6))
    axes[0].imshow(image)
    axes[0].set_title("Input")
    axes[0].axis("off")
    axes[1].imshow(depth.cpu(), cmap="Spectral_r")
    axes[1].set_title("Relative depth")
    axes[1].axis("off")
    plt.show()
# Get predictions from the PyTorch model.
depth_torch = model.predict(img)

# Visualize predictions from the PyTorch model.
visualize_depth(img, depth=depth_torch)

Export the model to ONNX

model.export_onnx(
    out=f"dav2-relative-small-{precision}-{width}x{height}.onnx",
    height=height,
    width=width,
    precision=precision,
)

See export_onnx for all available options when exporting to ONNX.

Run inference with the ONNX model

session = ort.InferenceSession(
    f"dav2-relative-small-{precision}-{width}x{height}.onnx",
    providers=["CUDAExecutionProvider"],
)

outs = session.run(None, inputs)
names = [o.name for o in session.get_outputs()]
raw = {n: torch.from_numpy(v) for n, v in zip(names, outs)}
depth_onnx = raw["depth"][0][0]

visualize_depth(img, depth=depth_onnx)

Note: The exported graph returns the raw depth map at the model’s processing resolution. Postprocessing that model.predict applies in PyTorch (resizing back to the original image size and, for metric models, the metric scaling) is not part of the ONNX or TensorRT graph and must be applied by the caller. Here the input image is already resized to the model’s processing resolution, so no resize-back is needed.

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.
#
# This example builds a fixed-shape engine (single image, no dynamic batch
# dimension) so the simple runner below can allocate its buffers directly from
# the engine's static tensor shapes. To build a dynamic-batch engine instead,
# drop the `dynamic_batch_size`/`batch_size` overrides and set the input shape
# on the execution context before allocating buffers.
model.export_tensorrt(
    out=f"dav2-relative-small-{precision}-{width}x{height}.trt",
    onnx_args={
        "height": height,
        "width": width,
        "dynamic_batch_size": False,
        "batch_size": 1,
    },
    precision=precision,
)

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(
    f"dav2-relative-small-{precision}-{width}x{height}.trt",
)

in_name = trt_model.in_names[0]

if precision == "fp16":
    inputs = {in_name: batch.to(torch.float16)}
else:
    inputs = {in_name: batch}
raw = trt_model(inputs)

depth_trt = raw["depth"][0][0]

visualize_depth(img, depth=depth_trt)