Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions ASSET_LICENSES.md
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@ inclusion and redistribution in this repository under the Apache License 2.0:

- `families/layoutlmv3/tests/data/test_img.jpeg`
- `families/dinov3/tests/data/test_img.jpeg`
- `families/dpt/tests/data/test_img.jpeg`
- `families/gemma3n/tests/data/test_img.jpeg`
- `families/internvl/tests/data/test_img.jpeg`
- `families/lance/tests/data/test_img.jpeg`
Expand Down
129 changes: 129 additions & 0 deletions families/dpt/NOTICE
Original file line number Diff line number Diff line change
@@ -0,0 +1,129 @@
The 8-bit bilinear image resize in runtime/image_ops.cpp (resize_bilinear_rgb8
and its helpers) is adapted from Pillow 13.0.0, src/libImaging/Resample.c:
https://github.com/python-pillow/Pillow/blob/13.0.0/src/libImaging/Resample.c
Pillow is licensed as follows:

The Python Imaging Library (PIL) is

Copyright © 1997-2011 by Secret Labs AB
Copyright © 1995-2011 by Fredrik Lundh and contributors

Pillow is the friendly PIL fork. It is

Copyright © 2010 by Jeffrey 'Alex' Clark and contributors

Like PIL, Pillow is licensed under the open source MIT-CMU License:

By obtaining, using, and/or copying this software and/or its associated
documentation, you agree that you have read, understood, and will comply
with the following terms and conditions:

Permission to use, copy, modify and distribute this software and its
documentation for any purpose and without fee is hereby granted,
provided that the above copyright notice appears in all copies, and that
both that copyright notice and this permission notice appear in supporting
documentation, and that the name of Secret Labs AB or the author not be
used in advertising or publicity pertaining to distribution of the software
without specific, written prior permission.

SECRET LABS AB AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS
SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS.
IN NO EVENT SHALL SECRET LABS AB OR THE AUTHOR BE LIABLE FOR ANY SPECIAL,
INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE
OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
PERFORMANCE OF THIS SOFTWARE.

----------------------------------------------------------------------------

The bicubic depth-map resize in runtime/image_ops.cpp (resize_bicubic and its
helpers) is adapted from PyTorch v2.12.0, aten/src/ATen/native/UpSample.h and
aten/src/ATen/native/cpu/UpSampleKernel.cpp:
https://github.com/pytorch/pytorch/blob/v2.12.0/aten/src/ATen/native/UpSample.h
https://github.com/pytorch/pytorch/blob/v2.12.0/aten/src/ATen/native/cpu/UpSampleKernel.cpp
PyTorch is licensed as follows:

From PyTorch:

Copyright (c) 2016- Facebook, Inc (Adam Paszke)
Copyright (c) 2014- Facebook, Inc (Soumith Chintala)
Copyright (c) 2011-2014 Idiap Research Institute (Ronan Collobert)
Copyright (c) 2012-2014 Deepmind Technologies (Koray Kavukcuoglu)
Copyright (c) 2011-2012 NEC Laboratories America (Koray Kavukcuoglu)
Copyright (c) 2011-2013 NYU (Clement Farabet)
Copyright (c) 2006-2010 NEC Laboratories America (Ronan Collobert, Leon Bottou, Iain Melvin, Jason Weston)
Copyright (c) 2006 Idiap Research Institute (Samy Bengio)
Copyright (c) 2001-2004 Idiap Research Institute (Ronan Collobert, Samy Bengio, Johnny Mariethoz)

From Caffe2:

Copyright (c) 2016-present, Facebook Inc. All rights reserved.

All contributions by Facebook:
Copyright (c) 2016 Facebook Inc.

All contributions by Google:
Copyright (c) 2015 Google Inc.
All rights reserved.

All contributions by Yangqing Jia:
Copyright (c) 2015 Yangqing Jia
All rights reserved.

All contributions by Kakao Brain:
Copyright 2019-2020 Kakao Brain

All contributions by Cruise LLC:
Copyright (c) 2022 Cruise LLC.
All rights reserved.

All contributions by Tri Dao:
Copyright (c) 2024 Tri Dao.
All rights reserved.

All contributions by Arm:
Copyright (c) 2021, 2023-2025 Arm Limited and/or its affiliates

All contributions from Caffe:
Copyright(c) 2013, 2014, 2015, the respective contributors
All rights reserved.

All other contributions:
Copyright(c) 2015, 2016 the respective contributors
All rights reserved.

Caffe2 uses a copyright model similar to Caffe: each contributor holds
copyright over their contributions to Caffe2. The project versioning records
all such contribution and copyright details. If a contributor wants to further
mark their specific copyright on a particular contribution, they should
indicate their copyright solely in the commit message of the change when it is
committed.

All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:

1. Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.

2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.

3. Neither the names of Facebook, Deepmind Technologies, NYU, NEC Laboratories America
and IDIAP Research Institute nor the names of its contributors may be
used to endorse or promote products derived from this software without
specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
99 changes: 99 additions & 0 deletions families/dpt/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,99 @@
# DPT-Hybrid (MiDaS)

This family builds the Transformers DPT-Hybrid depth model
(`DPTForDepthEstimation` with `is_hybrid: true`, as in
[`Intel/dpt-hybrid-midas`](https://huggingface.co/Intel/dpt-hybrid-midas)) as one
TensorRT engine for the `monocular_depth` task. A BiT ResNet stem and three
bottleneck stages feed a ViT-B/16 encoder; the DPT neck fuses BiT stages 1-2
with two ViT layers, and the head predicts relative inverse depth (MiDaS units,
larger is nearer) for every pixel of the input image.

```sh
trtmc build Intel/dpt-hybrid-midas -o dpt-hybrid-midas.bundle
trtmc depth dpt-hybrid-midas.bundle --image photo.jpg
```

The default precision is fp32, the checkpoint's own; `--precision fp16` builds
an fp16 engine. Batch is 1. The checkpoint ships only `pytorch_model.bin`, so the
build needs torch 2.10 or later (earlier versions can run code from a crafted file
even with `weights_only=True`); it is read with `weights_only=True`.

## Image pipeline

The family reproduces the checkpoint's `DPTImageProcessor` and
`post_process_depth_estimation` in C++:

- The input (RGB float32 in `[0, 1]`) is taken back to its 8-bit samples and
resized to 384x384 with Pillow 13's bilinear filter (fixed-point, two passes,
the vertical pass first when the height shrinks more than twice as much as the
width), then rescaled by 1/255 and normalized with mean and std 0.5. On the
test image, in landscape and portrait orientation, the engine input is
bit-identical to the processor's `pixel_values`.
- The 384x384 depth map is resized back to the input size bicubically
(`align_corners=False`, A = -0.75), as `post_process_depth_estimation` does.

Both are adapted from Pillow and PyTorch; see `NOTICE`.

## Accuracy

`tests/test_e2e.py` compares the CLI's depth map with the official pipeline in
float32 on the CPU (`DPTImageProcessor`, `DPTForDepthEstimation`,
`post_process_depth_estimation`) on the repository's test photograph in
landscape and in portrait orientation. Errors are relative to the largest
reference depth. 1x NVIDIA B300, CUDA 13, TensorRT 11.4, six builds of the fp32
engine and four of the fp16 one:

| Engine | Largest error | Mean error | Correlation | Engine call, batch 1 |
|---|---|---|---|---|
| fp32 | 2.8e-6 - 7.8e-6 | 2.0e-7 - 2.1e-7 | > 0.999999999999 | 8.7 ms |
| fp16 | 6.2e-3 - 3.0e-2 | 2.5e-4 - 5.7e-4 | >= 0.9999977 | 1.7 ms |

The fp32 builds are identical; the fp16 builds pick different kernels, and their
largest error on the landscape input moves between 1.3e-2 and 3.0e-2. For scale, the official model's
own float32 run on the GPU differs from its CPU run by up to 5.5e-6, and its
float16 run by up to 6.2e-3 (mean 2.8e-4 - 5.3e-4, compared on the 384x384
maps). On those maps the fp16 engine matches the official float16 run up to the
99th percentile (1.7e-3 against 1.5e-3); its largest errors, on about 0.1 % of
the pixels, are two to five times larger. They build up across the ViT encoder
and the neck: running one stage or the head in fp32 removes at most half of
them, so the engine stays fp16 throughout.

The bounds were also checked against known-wrong outputs: twelve plausible
porting mistakes injected into the float32 reference (resize filter,
normalization, rescale factor, channel order, BiT stem padding and
weight-standardization epsilon, ViT taps, GELU form, LayerNorm epsilon, fusion
and output interpolation), each on both inputs. The fp32 bounds (largest error
1e-4, mean 1e-5, correlation 0.999999) reject all 24 outputs, none of which
errs by less than 6.3e-4 (largest) or 4.9e-5 (mean). The fp16 bounds (0.05,
0.002, 0.99999) leave the fp16 engine at least 1.7 times its measured errors
and reject 16; the four mistakes they pass (rescale 1/256,
weight-standardization epsilon, tanh GELU, LayerNorm epsilon) err less than
fp16 rounding does, and the fp32 case, which runs in premerge, rejects them.

## Not supported

- DPT checkpoints other than DPT-Hybrid: the ViT-only `dpt-large`, and BEiT,
DINOv2 or Swin backbones. The build refuses them by name.
- `DPTForSemanticSegmentation`, `add_projection`, batch norm in the fusion units,
other image-processor settings (aspect-ratio-preserving resize, other
resampling filters, padding).
- Other input resolutions: images of any size are resized to the checkpoint's
384x384, and the position embeddings are not interpolated.
- Batch sizes above 1, quantization, tensor parallelism.

## Tests

```sh
cmake --build build --target test_dpt_image_ops test_dpt_pipeline
ctest --test-dir build --output-on-failure -R '^dpt_'
PYTHONPATH=core/builder:apps/benchmark:. python3 -m pytest families/dpt/tests --e2e-model dpt -q
```

`test_dpt_image_ops` checks the resize against Pillow byte for byte, the whole
preprocessing against `DPTImageProcessor` bit for bit, and the bicubic resize
against torch, with goldens from `tests/cpp/generate_image_ops_goldens.py`.
`test_dpt_pipeline` checks, with a stand-in engine, that the runtime refuses a
malformed `runtime.json`, an engine whose inputs or outputs differ from it, and
a non-finite depth map. `tests/test_support.py` covers identity, the default
task, the resolved geometry, every refused configuration value and the E2E case
selection.
4 changes: 4 additions & 0 deletions families/dpt/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: Apache-2.0

"""DPT-Hybrid (MiDaS) monocular depth estimation."""
74 changes: 74 additions & 0 deletions families/dpt/checkpoint.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: Apache-2.0

"""Read the tensors of a DPT checkpoint."""

from __future__ import annotations

from pathlib import Path

import numpy as np

CHECKPOINT = "pytorch_model.bin"
# Before 2.10.0, torch.load(weights_only=True) can run code from a crafted file
# (CVE-2026-24747, GHSA-63cw-57p8-fm3p).
MIN_TORCH = "2.10.0"


def tensor_arrays(state, source: str) -> dict[str, np.ndarray]:
"""Float32 copies of a state dict's tensors.

Every entry must be a named floating-point tensor whose values stay finite in
float32: integer, boolean or complex tensors are not weights of this graph, and a
NaN or infinity (also one that the conversion from float64 creates) would reach
the engine.
"""
import torch

if not isinstance(state, dict):
raise ValueError(f"{source} does not hold a state dict")
arrays = {}
for name, value in state.items():
if not isinstance(name, str) or not isinstance(value, torch.Tensor):
raise ValueError(f"{source} holds an entry that is not a named tensor: {name!r}")
if not value.is_floating_point():
raise ValueError(f"{source}: tensor {name} is {value.dtype}, not floating point")
array = value.detach().to(torch.float32).numpy()
if not np.isfinite(array).all():
raise ValueError(f"{source}: tensor {name} holds a value that is not finite in float32")
arrays[name] = array
return arrays


def as_engine_weights(values, dtype) -> np.ndarray:
"""``values`` as the engine stores them; a value that does not fit that dtype is refused.

A finite float32 weight can still overflow fp16 (100000 becomes infinity).
"""
with np.errstate(over="ignore", invalid="ignore"):
array = np.ascontiguousarray(values, dtype=dtype)
if not np.isfinite(array).all():
raise ValueError(f"a DPT weight is not finite in {np.dtype(dtype).name}; build fp32")
return array


def load_tensors(model_dir: str | Path) -> dict[str, np.ndarray]:
"""The checkpoint's state dict as float32 arrays.

The published repository ships only a PyTorch pickle. ``weights_only=True``
restricts unpickling to tensors and plain containers.
"""
try:
import torch
except ImportError as error:
raise RuntimeError("dpt requires torch in the build environment") from error
from packaging.version import Version

installed = str(torch.__version__).split("+")[0]
if Version(installed) < Version(MIN_TORCH):
raise RuntimeError(f"dpt reads checkpoints with torch {MIN_TORCH} or later; found {installed}")
path = Path(model_dir) / CHECKPOINT
if not path.is_file():
raise FileNotFoundError(f"dpt requires the checkpoint file {path}")
state = torch.load(str(path), map_location="cpu", weights_only=True)
return tensor_arrays(state, str(path))
Loading
Loading