From dccce3148d0f3a5765393efc91d6723066b01a62 Mon Sep 17 00:00:00 2001 From: Qikai Li Date: Tue, 24 Nov 2026 07:35:51 +0000 Subject: [PATCH 1/2] feat(dpt): add the monocular-depth family for DPT-Hybrid MiDaS Build DPT-Hybrid (MiDaS v3.0 hybrid) DPTForDepthEstimation checkpoints, such as Intel/dpt-hybrid-midas, as one TensorRT engine for the monocular_depth task: the BiT stem and bottleneck stages with their weight standardization folded into the constants, TF-style SAME padding and a zero-padded stem max pool, the ViT-B/16 encoder, the DPT neck with the "project" readout, and the depth head. fp32 is the default, fp16 an option. Other DPT variants, and configuration values of another JSON type, are refused at build time. The runtime reproduces DPTImageProcessor (Pillow 13 bilinear resize in fixed point, rescale, normalize) and post_process_depth_estimation (PyTorch bicubic resize) in C++; the adapted Pillow and PyTorch code is credited in the family NOTICE, which is installed with the library. At load it checks runtime.json and the engine's inputs and outputs, and it refuses a non-finite depth map. Tests cover identity, the resolved geometry, every refused configuration value and the E2E case selection; the image operations against Pillow, DPTImageProcessor and torch goldens; the runtime contract with a stand-in engine; and the CLI against the official float32 pipeline for fp32 and fp16 engines in landscape and portrait orientation, with bounds checked against injected porting mistakes. Signed-off-by: Qikai Li --- ASSET_LICENSES.md | 1 + families/dpt/NOTICE | 129 ++++ families/dpt/README.md | 98 +++ families/dpt/__init__.py | 4 + families/dpt/checkpoint.py | 66 ++ families/dpt/config.py | 560 ++++++++++++++ families/dpt/graph.py | 204 +++++ families/dpt/model.py | 436 +++++++++++ families/dpt/requirements.txt | 6 + families/dpt/runtime/CMakeLists.txt | 81 ++ families/dpt/runtime/image_ops.cpp | 328 ++++++++ families/dpt/runtime/image_ops.h | 52 ++ families/dpt/runtime/pipeline.cpp | 199 +++++ families/dpt/runtime/pipeline.h | 41 + families/dpt/runtime/plugin.cpp | 46 ++ families/dpt/support.py | 14 + families/dpt/tests/__init__.py | 4 + .../tests/cpp/generate_image_ops_goldens.py | 140 ++++ families/dpt/tests/cpp/image_ops_goldens.h | 153 ++++ families/dpt/tests/cpp/test_image_ops.cpp | 165 ++++ families/dpt/tests/cpp/test_pipeline.cpp | 278 +++++++ families/dpt/tests/data/test_img.jpeg | Bin 0 -> 55258 bytes .../manifests/dpt-hybrid-midas-fp16.json | 32 + .../dpt/tests/manifests/dpt-hybrid-midas.json | 32 + families/dpt/tests/test_e2e.py | 467 ++++++++++++ families/dpt/tests/test_support.py | 704 ++++++++++++++++++ 26 files changed, 4240 insertions(+) create mode 100644 families/dpt/NOTICE create mode 100644 families/dpt/README.md create mode 100644 families/dpt/__init__.py create mode 100644 families/dpt/checkpoint.py create mode 100644 families/dpt/config.py create mode 100644 families/dpt/graph.py create mode 100644 families/dpt/model.py create mode 100644 families/dpt/requirements.txt create mode 100644 families/dpt/runtime/CMakeLists.txt create mode 100644 families/dpt/runtime/image_ops.cpp create mode 100644 families/dpt/runtime/image_ops.h create mode 100644 families/dpt/runtime/pipeline.cpp create mode 100644 families/dpt/runtime/pipeline.h create mode 100644 families/dpt/runtime/plugin.cpp create mode 100644 families/dpt/support.py create mode 100644 families/dpt/tests/__init__.py create mode 100644 families/dpt/tests/cpp/generate_image_ops_goldens.py create mode 100644 families/dpt/tests/cpp/image_ops_goldens.h create mode 100644 families/dpt/tests/cpp/test_image_ops.cpp create mode 100644 families/dpt/tests/cpp/test_pipeline.cpp create mode 100644 families/dpt/tests/data/test_img.jpeg create mode 100644 families/dpt/tests/manifests/dpt-hybrid-midas-fp16.json create mode 100644 families/dpt/tests/manifests/dpt-hybrid-midas.json create mode 100644 families/dpt/tests/test_e2e.py create mode 100644 families/dpt/tests/test_support.py diff --git a/ASSET_LICENSES.md b/ASSET_LICENSES.md index a0d95df341..c30daa683f 100644 --- a/ASSET_LICENSES.md +++ b/ASSET_LICENSES.md @@ -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` diff --git a/families/dpt/NOTICE b/families/dpt/NOTICE new file mode 100644 index 0000000000..25ecc7a784 --- /dev/null +++ b/families/dpt/NOTICE @@ -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. diff --git a/families/dpt/README.md b/families/dpt/README.md new file mode 100644 index 0000000000..665d733268 --- /dev/null +++ b/families/dpt/README.md @@ -0,0 +1,98 @@ +# 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; 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. diff --git a/families/dpt/__init__.py b/families/dpt/__init__.py new file mode 100644 index 0000000000..b4fa3d0a01 --- /dev/null +++ b/families/dpt/__init__.py @@ -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.""" diff --git a/families/dpt/checkpoint.py b/families/dpt/checkpoint.py new file mode 100644 index 0000000000..41cb5c0cf7 --- /dev/null +++ b/families/dpt/checkpoint.py @@ -0,0 +1,66 @@ +# 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" + + +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 + 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)) diff --git a/families/dpt/config.py b/families/dpt/config.py new file mode 100644 index 0000000000..ff3a5f5c9d --- /dev/null +++ b/families/dpt/config.py @@ -0,0 +1,560 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +"""Read and check the DPT-Hybrid fields this family builds against. + +Absent fields take the defaults Transformers 5.2.0 fills in (``DPTConfig``, +``BitConfig`` and ``DPTImageProcessor``). A field that is present keeps its +JSON type: ``768.0`` is not an integer, ``"false"`` not a boolean, and an +explicit ``null`` is a value, accepted only where Transformers accepts it. +Every value that would change the graph or the image pipeline outside what this +family implements is refused rather than guessed. +""" + +from __future__ import annotations + +import json +import math +from collections.abc import Iterable, Iterator +from pathlib import Path + +import numpy as np + +ARCHITECTURE = "DPTForDepthEstimation" + +# DPTConfig defaults for the fields this family reads. +_DPT_DEFAULTS = { + "hidden_size": 768, + "num_hidden_layers": 12, + "num_attention_heads": 12, + "intermediate_size": 3072, + "hidden_act": "gelu", + "layer_norm_eps": 1e-12, + "image_size": 384, + "patch_size": 16, + "num_channels": 3, + "is_hybrid": False, + "qkv_bias": True, + "backbone_out_indices": [2, 5, 8, 11], + "readout_type": "project", + "reassemble_factors": [4, 2, 1, 0.5], + "neck_hidden_sizes": [96, 192, 384, 768], + "fusion_hidden_size": 256, + "head_in_index": -1, + "use_batch_norm_in_fusion_residual": False, + "use_bias_in_fusion_residual": None, + "add_projection": False, + "backbone_featmap_shape": [1, 1024, 24, 24], + "neck_ignore_stages": [0, 1], + "backbone": None, +} + +# BitConfig defaults, and the ones DPTConfig substitutes when a hybrid config +# carries no backbone_config at all (or null). +_BIT_DEFAULTS = { + "num_channels": 3, + "embedding_size": 64, + "hidden_sizes": [256, 512, 1024, 2048], + "depths": [3, 4, 6, 3], + "layer_type": "preactivation", + "hidden_act": "relu", + "global_padding": None, + "num_groups": 32, + "embedding_dynamic_padding": False, + "output_stride": 32, + "width_factor": 1, + "out_features": None, + "out_indices": None, +} +_BIT_HYBRID_DEFAULTS = { + "global_padding": "same", + "layer_type": "bottleneck", + "depths": [3, 4, 9], + "out_features": ["stage1", "stage2", "stage3"], + "embedding_dynamic_padding": True, +} + +# DPTImageProcessor defaults. resample 2 is PIL bilinear, 3 bicubic. +_PROCESSOR_DEFAULTS = { + "do_resize": True, + "size": {"height": 384, "width": 384}, + "resample": 3, + "keep_aspect_ratio": False, + "ensure_multiple_of": 1, + "do_rescale": True, + "rescale_factor": 1 / 255, + "do_normalize": True, + "image_mean": [0.5, 0.5, 0.5], + "image_std": [0.5, 0.5, 0.5], + "do_pad": False, + "size_divisor": None, +} +_PIL_BILINEAR = 2 + +# BitEmbeddings and every BiT bottleneck convolution standardize their weights +# with these epsilons; GroupNorm uses its own. +STEM_WEIGHT_EPS = 1e-8 +LAYER_WEIGHT_EPS = 1e-8 +GROUP_NORM_EPS = 1e-5 + +# Engine dimensions are int32. +_INT32_MAX = 2**31 - 1 +BIT_PREFIX = "dpt.embeddings.backbone.bit" +_FLOAT32_MAX = float(np.finfo(np.float32).max) +_FLOAT16_MAX = float(np.finfo(np.float16).max) + + +def _unique_keys(pairs: list[tuple[str, object]]) -> dict: + result = {} + for key, value in pairs: + if key in result: + raise ValueError(f"DPT JSON repeats the key {key!r}") + result[key] = value + return result + + +def _finite_float(text: str) -> float: + value = float(text) + if not math.isfinite(value): + raise ValueError(f"DPT JSON holds the non-finite number {text}") + return value + + +def _no_constant(name: str): + raise ValueError(f"DPT JSON holds the non-finite number {name}") + + +def _read_json(path: Path) -> dict: + if not path.is_file(): + raise FileNotFoundError(f"missing DPT file: {path}") + value = json.loads(path.read_text(encoding="utf-8"), object_pairs_hook=_unique_keys, + parse_float=_finite_float, parse_constant=_no_constant) + if not isinstance(value, dict): + raise ValueError(f"DPT file must hold a JSON object: {path}") + return value + + +def load(model_dir: str | Path) -> dict: + """Resolve the build configuration of the checkpoint under ``model_dir``.""" + root = Path(model_dir) + return resolve(_read_json(root / "config.json"), + _read_json(root / "preprocessor_config.json")) + + +def _values(raw: dict, defaults: dict) -> dict: + """Every field of ``defaults``: the raw value when the key is present, null included.""" + return {key: raw[key] if key in raw else default for key, default in defaults.items()} + + +def _integer(value, name: str, *, minimum: int | None = 1) -> int: + if isinstance(value, bool) or not isinstance(value, int): + raise ValueError(f"DPT {name} must be an integer; got {value!r}") + if (minimum is not None and value < minimum) or abs(value) > _INT32_MAX: + raise ValueError(f"DPT {name} is out of range: {value}") + return value + + +def _number(value, name: str) -> float: + if isinstance(value, bool) or not isinstance(value, (int, float)) or not math.isfinite(value): + raise ValueError(f"DPT {name} must be a finite number; got {value!r}") + return float(value) + + +def _flag(value, name: str) -> bool: + if not isinstance(value, bool): + raise ValueError(f"DPT {name} must be true or false; got {value!r}") + return value + + +def _text(value, name: str) -> str: + if not isinstance(value, str): + raise ValueError(f"DPT {name} must be a string; got {value!r}") + return value + + +def _integers(value, name: str, *, minimum: int | None = 1) -> list[int]: + if not isinstance(value, list): + raise ValueError(f"DPT {name} must be a list; got {value!r}") + return [_integer(item, name, minimum=minimum) for item in value] + + +def _numbers(value, name: str) -> list[float]: + if not isinstance(value, list): + raise ValueError(f"DPT {name} must be a list; got {value!r}") + return [_number(item, name) for item in value] + + +def _same_padding(size: int, kernel: int, stride: int) -> tuple[int, int]: + """Before/after padding of BiT's dynamic TF-style SAME padding.""" + total = max((math.ceil(size / stride) - 1) * stride + kernel - size, 0) + return total // 2, total - total // 2 + + +def _conv_padding(size: int, kernel: int, stride: int) -> tuple[int, int]: + """Padding of a BiT convolution: static when stride 1 and odd kernel, else dynamic.""" + if stride == 1 and (kernel - 1) % 2 == 0: + return (kernel - 1) // 2, (kernel - 1) // 2 + return _same_padding(size, kernel, stride) + + +def _make_div(value: float, divisor: int = 8) -> int: + new_value = max(divisor, int(value + divisor / 2) // divisor * divisor) + if new_value < 0.9 * value: + new_value += divisor + return new_value + + +def _bit_out_features(values: dict, stage_count: int) -> list[str]: + """The stages a BiT backbone returns, from out_features and out_indices as Transformers + 5.2.0 aligns them: either one alone decides, both must agree, neither means the last.""" + stage_names = ["stem"] + [f"stage{index}" for index in range(1, stage_count + 1)] + features, indices = values["out_features"], values["out_indices"] + if features is not None: + if not isinstance(features, list) or any(not isinstance(name, str) for name in features) \ + or features != [name for name in stage_names if name in features]: + raise ValueError( + f"DPT BiT out_features must name distinct stages of {stage_names} in order; got " + f"{features!r}") + if indices is not None: + indices = _integers(indices, "BiT out_indices", minimum=None) + if any(not -len(stage_names) <= index < len(stage_names) for index in indices): + raise ValueError(f"DPT BiT out_indices must index {stage_names}; got {indices}") + positive = [index % len(stage_names) for index in indices] + if positive != sorted(set(positive)): + raise ValueError(f"DPT BiT out_indices must be distinct and in order; got {indices}") + named = [stage_names[index] for index in positive] + if features is not None and features != named: + raise ValueError( + f"DPT BiT out_features {features} and out_indices {indices} name different stages") + features = named + return features if features is not None else [stage_names[-1]] + + +def _resolve_backbone(raw: dict, image_size: int) -> dict: + # DPTConfig builds the hybrid BiT defaults for an absent or null backbone_config. + backbone = raw.get("backbone_config") + if backbone is None: + values = dict(_BIT_DEFAULTS, **_BIT_HYBRID_DEFAULTS) + elif isinstance(backbone, dict): + model_type = backbone.get("model_type", "bit") + if model_type != "bit": + raise NotImplementedError( + f"dpt builds the BiT backbone of DPT-Hybrid only; got backbone model_type={model_type!r}") + values = _values(backbone, _BIT_DEFAULTS) + else: + raise ValueError("DPT backbone_config must be a JSON object") + + if _text(values["layer_type"], "BiT layer_type") != "bottleneck": + raise NotImplementedError( + f"dpt supports the BiT bottleneck layer only; got {values['layer_type']!r}") + padding = values["global_padding"] + if not isinstance(padding, str) or padding.upper() != "SAME": + raise NotImplementedError(f"dpt supports BiT global_padding='SAME' only; got {padding!r}") + if not _flag(values["embedding_dynamic_padding"], "BiT embedding_dynamic_padding"): + raise NotImplementedError("dpt supports BiT embedding_dynamic_padding=true only") + if _text(values["hidden_act"], "BiT hidden_act") != "relu": + raise NotImplementedError(f"dpt supports BiT hidden_act='relu' only; got {values['hidden_act']!r}") + if _integer(values["num_channels"], "BiT num_channels") != 3: + raise ValueError("DPT BiT backbone must take three input channels") + + depths = _integers(values["depths"], "BiT depths") + hidden_sizes = _integers(values["hidden_sizes"], "BiT hidden_sizes") + # BitConfig names a stage per depth; the encoder pairs them with hidden_sizes. + stage_count = len(depths) + if len(hidden_sizes) < stage_count: + raise ValueError(f"DPT BiT needs a hidden size per stage; got {hidden_sizes} for {depths}") + out_features = _bit_out_features(values, stage_count) + if out_features != [f"stage{index}" for index in range(1, stage_count + 1)] or stage_count != 3: + raise NotImplementedError( + "dpt needs a three-stage BiT backbone that returns every stage; got " + f"depths={depths} out_features={out_features!r}") + + width_factor = _number(values["width_factor"], "BiT width_factor") + if width_factor <= 0.0: + raise ValueError(f"DPT BiT width_factor must be positive; got {width_factor}") + output_stride = _integer(values["output_stride"], "BiT output_stride") + groups = _integer(values["num_groups"], "BiT num_groups") + embedding = _integer(values["embedding_size"], "BiT embedding_size") + + # The stem: 7x7 stride-2 convolution, then a 3x3 stride-2 max pool, both with + # SAME padding computed from the input size. + side = image_size + stem_pad = _same_padding(side, 7, 2) + side = (side + sum(stem_pad) - 7) // 2 + 1 + pool_pad = _same_padding(side, 3, 2) + side = (side + sum(pool_pad) - 3) // 2 + 1 + + stages = [] + channels = embedding + current_stride = 4 + dilation = 1 + for index in range(stage_count): + out_channels = _make_div(hidden_sizes[index] * width_factor) + stride = 1 if index == 0 else 2 + if current_stride >= output_stride: + dilation *= stride + stride = 1 + if dilation != 1: + raise NotImplementedError("dpt does not support dilated BiT stages") + mid_channels = _make_div(out_channels * 0.25) + for value in (mid_channels, out_channels): + if value % groups: + raise ValueError(f"BiT GroupNorm needs {groups} groups to divide {value} channels") + stages.append({ + "depth": depths[index], + "in_channels": channels, + "out_channels": out_channels, + "mid_channels": mid_channels, + "stride": stride, + "in_side": side, + "conv2_padding": _conv_padding(side, 3, stride), + "downsample_padding": _conv_padding(side, 1, stride), + }) + side = (side + sum(stages[-1]["conv2_padding"]) - 3) // stride + 1 + stages[-1]["out_side"] = side + channels = out_channels + current_stride *= stride + if embedding % groups: + raise ValueError(f"BiT GroupNorm needs {groups} groups to divide {embedding} channels") + + return { + "embedding_size": embedding, + "num_groups": groups, + "stem_padding": stem_pad, + "pool_padding": pool_pad, + "stages": stages, + } + + +def _normalized(rescale_factor: float, mean: list[float], std: list[float]) -> np.ndarray: + """Every 8-bit level of every channel, normalized as the runtime computes it: the + product in float64 stored as float32, then subtraction and division in float32.""" + mean32 = np.asarray(mean, dtype=np.float32)[:, None] + std32 = np.asarray(std, dtype=np.float32)[:, None] + levels = (np.arange(256, dtype=np.float64) * rescale_factor).astype(np.float32)[None, :] + with np.errstate(over="ignore", divide="ignore", invalid="ignore"): + return (levels - mean32) / std32 + + +def _check_normalization(rescale_factor: float, mean: list[float], std: list[float]) -> None: + """Every 8-bit sample must rescale and normalize to a finite float32.""" + if not 0.0 < rescale_factor <= _FLOAT32_MAX / 255.0: + raise ValueError( + f"DPT rescale_factor must be positive and keep 255 within float32; got {rescale_factor}") + if any(abs(value) > _FLOAT32_MAX for value in (*mean, *std)): + raise ValueError("DPT image_mean and image_std must fit float32") + if (np.asarray(std, dtype=np.float32) == 0.0).any(): + raise ValueError(f"DPT image_std must be non-zero in float32; got {std}") + if not np.isfinite(_normalized(rescale_factor, mean, std)).all(): + raise ValueError("DPT image_mean and image_std overflow float32 for an 8-bit sample") + + +def _resolve_processor(processor: dict, image_size: int) -> dict: + values = _values(processor, _PROCESSOR_DEFAULTS) + # DPTImageProcessor replaces a null size, image_mean or image_std with its default. + for key in ("size", "image_mean", "image_std"): + if values[key] is None: + values[key] = _PROCESSOR_DEFAULTS[key] + size = values["size"] + if not _flag(values["do_resize"], "do_resize") or not isinstance(size, dict) \ + or set(size) != {"height", "width"} \ + or _integer(size["height"], "size.height") != image_size \ + or _integer(size["width"], "size.width") != image_size: + raise NotImplementedError( + f"dpt needs the image processor to resize to the model's {image_size}x{image_size}") + if _flag(values["keep_aspect_ratio"], "keep_aspect_ratio") \ + or _integer(values["ensure_multiple_of"], "ensure_multiple_of") != 1: + raise NotImplementedError( + "dpt supports keep_aspect_ratio=false and ensure_multiple_of=1 only: the engine " + "takes one fixed input size") + if _integer(values["resample"], "resample", minimum=0) != _PIL_BILINEAR: + raise NotImplementedError( + f"dpt reproduces PIL bilinear resampling only; got resample={values['resample']}") + if _flag(values["do_pad"], "do_pad") or values["size_divisor"] is not None: + raise NotImplementedError("dpt does not support padded preprocessing") + if not _flag(values["do_rescale"], "do_rescale") \ + or not _flag(values["do_normalize"], "do_normalize"): + raise NotImplementedError("dpt needs do_rescale=true and do_normalize=true") + mean = _numbers(values["image_mean"], "image_mean") + std = _numbers(values["image_std"], "image_std") + if len(mean) != 3 or len(std) != 3 or any(value == 0.0 for value in std): + raise ValueError("DPT image_mean and image_std need three values, std non-zero") + rescale_factor = _number(values["rescale_factor"], "rescale_factor") + _check_normalization(rescale_factor, mean, std) + return { + "rescale_factor": rescale_factor, + "image_mean": mean, + "image_std": std, + } + + +def resolve(raw: dict, processor: dict) -> dict: + """The subset of the model and processor configs this family builds against.""" + if raw.get("model_type") != "dpt": + raise ValueError(f"dpt does not support model_type={raw.get('model_type')!r}") + # An absent or null list states nothing; the model class is DPTForDepthEstimation. + architectures = raw.get("architectures") + if architectures is not None and architectures != [ARCHITECTURE]: + raise NotImplementedError( + f"dpt builds {ARCHITECTURE} only; got architectures={architectures!r}") + values = _values(raw, _DPT_DEFAULTS) + if _flag(values["is_hybrid"], "is_hybrid") is not True: + raise NotImplementedError( + "dpt builds DPT-Hybrid checkpoints (is_hybrid=true, BiT backbone) only") + if values["backbone"] is not None: + raise NotImplementedError( + "dpt builds the BiT backbone described by backbone_config, not a named backbone") + if _text(values["readout_type"], "readout_type") != "project": + raise NotImplementedError("DPT-Hybrid requires readout_type='project'") + if _text(values["hidden_act"], "hidden_act") != "gelu": + raise NotImplementedError(f"dpt supports hidden_act='gelu' only; got {values['hidden_act']!r}") + if _flag(values["use_batch_norm_in_fusion_residual"], "use_batch_norm_in_fusion_residual"): + raise NotImplementedError("dpt does not support batch norm in the fusion residual units") + if _flag(values["add_projection"], "add_projection"): + raise NotImplementedError("dpt does not support the depth head's add_projection") + fusion_bias = values["use_bias_in_fusion_residual"] + if fusion_bias is not None: + _flag(fusion_bias, "use_bias_in_fusion_residual") + if _integer(values["num_channels"], "num_channels") != 3: + raise ValueError("DPT must take three input channels") + + hidden = _integer(values["hidden_size"], "hidden_size") + heads = _integer(values["num_attention_heads"], "num_attention_heads") + if hidden % heads: + raise ValueError("DPT hidden_size must divide by num_attention_heads") + image_size = _integer(values["image_size"], "image_size") + # The runtime refuses an engine input of more than INT32_MAX / 4 pixels. + if image_size * image_size > _INT32_MAX // 4: + raise ValueError(f"DPT image_size {image_size} exceeds the runtime's input limit") + patch = _integer(values["patch_size"], "patch_size") + if image_size % patch: + raise ValueError("DPT image_size must be a whole number of patches") + layers = _integer(values["num_hidden_layers"], "num_hidden_layers") + layer_norm_eps = _number(values["layer_norm_eps"], "layer_norm_eps") + # TensorRT stores the epsilon as float32: it must stay positive and finite there. + if not 0.0 < layer_norm_eps <= _FLOAT32_MAX or float(np.float32(layer_norm_eps)) == 0.0: + raise ValueError( + f"DPT layer_norm_eps must be a positive float32 value; got {layer_norm_eps}") + + if _integers(values["neck_ignore_stages"], "neck_ignore_stages", minimum=0) != [0, 1]: + raise NotImplementedError( + "DPT-Hybrid feeds BiT stages 1-2 straight into the neck: neck_ignore_stages " + f"must be [0, 1]; got {values['neck_ignore_stages']!r}") + out_indices = _integers(values["backbone_out_indices"], "backbone_out_indices", minimum=0) + neck_sizes = _integers(values["neck_hidden_sizes"], "neck_hidden_sizes") + factors = _numbers(values["reassemble_factors"], "reassemble_factors") + if len(out_indices) != 4 or len(neck_sizes) != 4 or len(factors) != 4: + raise ValueError("DPT needs four backbone_out_indices, neck_hidden_sizes and factors") + # The reference walks the encoder layers in order and keeps those named here, + # so the taps reach the neck in ascending layer order whatever the list order. + taps = sorted(out_indices[2:]) + if len(set(taps)) != len(taps): + raise ValueError(f"DPT backbone_out_indices {out_indices} name a ViT layer twice") + if any(index >= layers for index in taps): + raise ValueError(f"DPT backbone_out_indices {taps} name a layer past the encoder") + # A factor 1/n is a stride-n convolution over the patch grid: n from 2 to the grid side. + grid = image_size // patch + for factor in factors[2:]: + step = 1.0 / factor if 0.0 < factor < 1.0 else 0.0 + if factor != 1.0 and not (step.is_integer() and 2 <= step <= grid): + raise NotImplementedError( + f"dpt supports reassemble factors 1 and 1/n (n from 2 to {grid}) on the ViT " + f"taps; got {factor}") + if _integer(values["head_in_index"], "head_in_index", minimum=None) not in (-1, 3): + raise NotImplementedError("dpt reads the depth head from the last fusion layer only") + + backbone = _resolve_backbone(raw, image_size) + stage3 = backbone["stages"][-1] + if stage3["out_side"] != grid: + raise NotImplementedError( + f"DPT-Hybrid needs BiT's last stage at the patch grid ({grid}); it is " + f"{stage3['out_side']}") + featmap = _integers(values["backbone_featmap_shape"], "backbone_featmap_shape") + if len(featmap) != 4 or featmap[1] != stage3["out_channels"]: + raise ValueError( + f"DPT backbone_featmap_shape {featmap} disagrees with BiT's " + f"{stage3['out_channels']} output channels") + if neck_sizes[0] != backbone["stages"][0]["out_channels"] \ + or neck_sizes[1] != backbone["stages"][1]["out_channels"]: + raise ValueError("DPT neck_hidden_sizes[0:2] must match BiT stages 1 and 2") + + return { + "hidden_size": hidden, + "num_attention_heads": heads, + "head_dim": hidden // heads, + "num_hidden_layers": layers, + "intermediate_size": _integer(values["intermediate_size"], "intermediate_size"), + "layer_norm_eps": layer_norm_eps, + "qkv_bias": _flag(values["qkv_bias"], "qkv_bias"), + "image_size": image_size, + "patch_size": patch, + "patch_grid": grid, + "tap_layers": taps, + "reassemble_factors": factors, + "neck_hidden_sizes": neck_sizes, + "fusion_hidden_size": _integer(values["fusion_hidden_size"], "fusion_hidden_size"), + "fusion_bias": fusion_bias is not False, + "backbone": backbone, + "processor": _resolve_processor(processor, image_size), + } + + +def bit_layer_shapes(stage: dict, layer_index: int) -> dict[str, tuple[int, int, int, int]]: + """The convolution weight shapes of one BiT bottleneck layer, by module name.""" + mid, out = stage["mid_channels"], stage["out_channels"] + in_channels = stage["in_channels"] if layer_index == 0 else out + shapes = {"downsample.conv": (out, in_channels, 1, 1)} if layer_index == 0 else {} + shapes.update({"conv1": (mid, in_channels, 1, 1), "conv2": (mid, mid, 3, 3), + "conv3": (out, mid, 1, 1)}) + return shapes + + +def bit_weight_shapes(resolved: dict) -> Iterator[tuple[str, tuple[int, ...]]]: + """Every BiT convolution weight the graph reads, with the shape the configuration implies. + + A generator in graph order, so that a check against a checkpoint stops at the + first missing weight however deep the configured stages are. + """ + backbone = resolved["backbone"] + yield f"{BIT_PREFIX}.embedder.convolution.weight", (backbone["embedding_size"], 3, 7, 7) + for stage_index, stage in enumerate(backbone["stages"]): + for layer_index in range(stage["depth"]): + prefix = f"{BIT_PREFIX}.encoder.stages.{stage_index}.layers.{layer_index}" + for module, shape in bit_layer_shapes(stage, layer_index).items(): + yield f"{prefix}.{module}.weight", shape + + +def check_weight_shapes(tensors: dict, expected: Iterable[tuple[str, tuple[int, ...]]]) -> None: + """Refuse a checkpoint whose tensors lack the shapes its configuration implies.""" + for name, shape in expected: + if name not in tensors: + raise KeyError(f"DPT checkpoint is missing {name}") + actual = tuple(int(size) for size in tensors[name].shape) + if actual != shape: + raise ValueError( + f"DPT checkpoint does not match its configuration: {name} has shape {actual}, " + f"the configuration implies {shape}") + + +def check_requested_image_size(label: str, value, image_size: int) -> None: + """A requested build image size must be the checkpoint's own, as an integer (384.5 is not 384).""" + if value is None: + return + if isinstance(value, bool) or not isinstance(value, int): + raise ValueError(f"dpt {label} must be an integer; got {value!r}") + if value != image_size: + raise NotImplementedError( + f"dpt builds the checkpoint's native {label} ({image_size}) only; images of any size " + "are resized to it at run time") + + +def check_engine_input(processor: dict, precision: str) -> None: + """The fp16 engine casts its float32 input to fp16 first: every normalized sample must fit.""" + if precision != "fp16": + return + peak = float(np.abs(_normalized(processor["rescale_factor"], processor["image_mean"], + processor["image_std"])).max()) + if peak > _FLOAT16_MAX: + raise ValueError( + f"DPT normalization reaches |{peak:.6g}|, past fp16's {_FLOAT16_MAX:g}: the fp16 " + "engine's input would overflow; build fp32") diff --git a/families/dpt/graph.py b/families/dpt/graph.py new file mode 100644 index 0000000000..dee72e5365 --- /dev/null +++ b/families/dpt/graph.py @@ -0,0 +1,204 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +"""TensorRT graph helpers for the DPT-Hybrid BiT backbone, ViT encoder and DPT neck.""" + +from __future__ import annotations + +import numpy as np +import tensorrt as trt + +from .checkpoint import as_engine_weights + + +def retype(network, tensor, target): + if tensor.dtype == target: + return tensor + return network.add_cast(tensor, target).get_output(0) + + +def add_constant(network, shape, values, dtype=np.float32): + weights = trt.Weights(as_engine_weights(np.asarray(values).reshape(shape), dtype)) + return network.add_constant(tuple(shape), weights).get_output(0) + + +def add_conv2d(network, inp, weight, bias, *, stride=(1, 1), pre_padding=(0, 0), + post_padding=(0, 0), dtype=np.float32): + """2-D convolution with explicit (possibly asymmetric) zero padding. + + ``weight`` is [out, in, kh, kw]; ``bias`` may be None. + """ + weight = np.asarray(weight) + out_channels, _, kernel_h, kernel_w = (int(v) for v in weight.shape) + conv = network.add_convolution_nd( + inp, out_channels, (kernel_h, kernel_w), + trt.Weights(as_engine_weights(weight, dtype)), + trt.Weights(as_engine_weights(bias, dtype)) if bias is not None + else trt.Weights(), + ) + conv.stride_nd = tuple(stride) + conv.pre_padding = tuple(pre_padding) + conv.post_padding = tuple(post_padding) + return conv.get_output(0) + + +def add_zero_pad(network, inp, pre_padding, post_padding): + """Pad the spatial axes of [N, C, H, W] with zeros (``F.pad(..., value=0)``).""" + shape = tuple(int(v) for v in inp.shape) + if not any(pre_padding) and not any(post_padding): + return inp + padded = network.add_slice( + inp, + (0, 0, -int(pre_padding[0]), -int(pre_padding[1])), + (shape[0], shape[1], + shape[2] + int(pre_padding[0]) + int(post_padding[0]), + shape[3] + int(pre_padding[1]) + int(post_padding[1])), + (1, 1, 1, 1), + ) + padded.mode = trt.SampleMode.FILL + return padded.get_output(0) + + +def add_max_pool(network, inp, kernel, stride): + pool = network.add_pooling_nd(inp, trt.PoolingType.MAX, tuple(kernel)) + pool.stride_nd = tuple(stride) + return pool.get_output(0) + + +def add_group_norm(network, inp, gamma, beta, groups: int, eps: float, dtype=np.float32): + """GroupNorm over [N, C, H, W]: normalize within channel groups, then scale and shift.""" + shape = tuple(int(v) for v in inp.shape) + channels = shape[1] + if channels % groups: + raise ValueError(f"group norm needs {groups} to divide {channels} channels") + grouped = network.add_shuffle(inp) + grouped.reshape_dims = (shape[0], groups, channels // groups, shape[2], shape[3]) + # Statistics over the channels of one group and the whole map. + axes = (1 << 2) | (1 << 3) | (1 << 4) + unit_shape = (1, groups, 1, 1, 1) + ones = add_constant(network, unit_shape, np.ones(unit_shape), dtype=dtype) + zeros = add_constant(network, unit_shape, np.zeros(unit_shape), dtype=dtype) + layer = network.add_normalization( + grouped.get_output(0), retype(network, ones, inp.dtype), + retype(network, zeros, inp.dtype), axes) + layer.epsilon = float(eps) + restored = network.add_shuffle(layer.get_output(0)) + restored.reshape_dims = shape + normalized = restored.get_output(0) + + # The affine term is per channel, not per group. + affine_shape = (1, channels, 1, 1) + scale = retype(network, add_constant(network, affine_shape, gamma, dtype=dtype), inp.dtype) + shift = retype(network, add_constant(network, affine_shape, beta, dtype=dtype), inp.dtype) + scaled = network.add_elementwise( + normalized, scale, trt.ElementWiseOperation.PROD).get_output(0) + return network.add_elementwise(scaled, shift, trt.ElementWiseOperation.SUM).get_output(0) + + +def add_layer_norm(network, inp, gamma, beta, eps, dtype=np.float32): + """Normalize over the last axis, then scale and shift.""" + rank = len(tuple(inp.shape)) + width = int(np.asarray(gamma).size) + shape = (1,) * (rank - 1) + (width,) + scale = retype(network, add_constant(network, shape, gamma, dtype=dtype), inp.dtype) + shift = retype(network, add_constant(network, shape, beta, dtype=dtype), inp.dtype) + layer = network.add_normalization(inp, scale, shift, 1 << (rank - 1)) + layer.epsilon = float(eps) + return layer.get_output(0) + + +def add_linear(network, inp, weight, bias, dtype=np.float32): + """Linear over the last axis. ``weight`` is [out_features, in_features].""" + weight = np.asarray(weight) + rank = len(tuple(inp.shape)) + out_features, in_features = int(weight.shape[0]), int(weight.shape[1]) + rhs_shape = (1,) * (rank - 2) + (in_features, out_features) + rhs = retype(network, add_constant(network, rhs_shape, weight.T, dtype=dtype), inp.dtype) + product = network.add_matrix_multiply( + inp, trt.MatrixOperation.NONE, rhs, trt.MatrixOperation.NONE).get_output(0) + if bias is None: + return product + bias_shape = (1,) * (rank - 1) + (out_features,) + bias_t = retype(network, add_constant(network, bias_shape, bias, dtype=dtype), product.dtype) + return network.add_elementwise(product, bias_t, trt.ElementWiseOperation.SUM).get_output(0) + + +def add_relu(network, inp): + return network.add_activation(inp, trt.ActivationType.RELU).get_output(0) + + +def add_gelu(network, inp): + """The exact erf GELU that transformers' "gelu" activation uses.""" + return network.add_activation(inp, trt.ActivationType.GELU_ERF).get_output(0) + + +def add_sum(network, left, right): + return network.add_elementwise( + left, retype(network, right, left.dtype), trt.ElementWiseOperation.SUM).get_output(0) + + +def split_heads(network, x, tokens, num_heads, head_dim): + """[1, tokens, hidden] -> [1, heads, tokens, head_dim].""" + shuffle = network.add_shuffle(x) + shuffle.reshape_dims = (1, tokens, num_heads, head_dim) + shuffle.second_transpose = (0, 2, 1, 3) + return shuffle.get_output(0) + + +def merge_heads(network, x, tokens, hidden): + """[1, heads, tokens, head_dim] -> [1, tokens, hidden].""" + shuffle = network.add_shuffle(x) + shuffle.first_transpose = (0, 2, 1, 3) + shuffle.reshape_dims = (1, tokens, hidden) + return shuffle.get_output(0) + + +def add_attention(network, query, key, value, scale): + """softmax(Q K^T * scale) V over the token axis of a [1, H, T, D] layout.""" + scores = network.add_matrix_multiply( + query, trt.MatrixOperation.NONE, key, trt.MatrixOperation.TRANSPOSE).get_output(0) + scale_t = retype( + network, add_constant(network, (1, 1, 1, 1), np.array([scale], dtype=np.float32)), + scores.dtype) + scores = network.add_elementwise(scores, scale_t, trt.ElementWiseOperation.PROD).get_output(0) + softmax = network.add_softmax(scores) + softmax.axes = 1 << 3 + return network.add_matrix_multiply( + softmax.get_output(0), trt.MatrixOperation.NONE, value, trt.MatrixOperation.NONE + ).get_output(0) + + +def map_to_tokens(network, x): + """[1, C, H, W] -> [1, H * W, C], row-major over the map (``flatten(2).transpose(1, 2)``).""" + shape = tuple(int(v) for v in x.shape) + shuffle = network.add_shuffle(x) + shuffle.reshape_dims = (shape[0], shape[1], shape[2] * shape[3]) + shuffle.second_transpose = (0, 2, 1) + return shuffle.get_output(0) + + +def tokens_to_map(network, x, height, width): + """[1, H * W, C] -> [1, C, H, W].""" + channels = int(tuple(x.shape)[-1]) + shuffle = network.add_shuffle(x) + shuffle.reshape_dims = (1, height, width, channels) + shuffle.second_transpose = (0, 3, 1, 2) + return shuffle.get_output(0) + + +def add_resize_to(network, inp, target, align_corners: bool): + """Bilinear resize of [N, C, H, W] onto (height, width). + + ``align_corners`` selects PyTorch's two conventions, which TensorRT spells as + different coordinate transformations. + """ + resize = network.add_resize(inp) + resize.resize_mode = trt.InterpolationMode.LINEAR + resize.coordinate_transformation = ( + trt.ResizeCoordinateTransformation.ALIGN_CORNERS + if align_corners + else trt.ResizeCoordinateTransformation.HALF_PIXEL + ) + shape = tuple(int(v) for v in inp.shape) + resize.shape = (shape[0], shape[1], int(target[0]), int(target[1])) + return resize.get_output(0) diff --git a/families/dpt/model.py b/families/dpt/model.py new file mode 100644 index 0000000000..130d2edfd8 --- /dev/null +++ b/families/dpt/model.py @@ -0,0 +1,436 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +"""Build one DPT-Hybrid monocular-depth engine. + +A BiT ResNet stem and three bottleneck stages feed a ViT-B/16 encoder through a +1x1 projection; the DPT neck reassembles BiT stages 1-2 and two ViT taps into +four maps and fuses them; a small convolution head predicts relative inverse +depth at the input resolution. Details that are silently wrong-but-plausible +when guessed are taken from the reference: + +* Every BiT convolution standardizes its weight per output channel (mean 0, + biased variance 1, epsilon 1e-8) before convolving. The weights are + constants, so the standardization is applied here, in float64, once. +* BiT pads the 7x7 stride-2 stem convolution, the stem max pool and every + stride-2 3x3 convolution TF-style ("SAME"): asymmetric, extra row and column + at the bottom and right. The max pool pads with zeros, not -inf. +* The neck takes the ViT layers named by ``backbone_out_indices[2:]`` before the + encoder's final LayerNorm, concatenates each token with the class token, and + projects the pair back to the hidden width ("project" readout). +* Fusion upsamples with ``align_corners=True``; a residual that has to be + brought onto the running map uses ``align_corners=False``. +""" + +from __future__ import annotations + +import math +from pathlib import Path + +import numpy as np +import tensorrt as trt + +from . import config as config_module +from . import graph as graph_ops +from .checkpoint import load_tensors + +_BIT = config_module.BIT_PREFIX + + +class _Weights: + """Checkpoint tensors by name; every lookup is recorded so leftovers can be refused.""" + + def __init__(self, tensors: dict): + self._tensors = tensors + self.used: set[str] = set() + + def get(self, name: str, shape=None) -> np.ndarray: + if name not in self._tensors: + raise KeyError(f"DPT checkpoint is missing {name}") + value = np.asarray(self._tensors[name], dtype=np.float32) + if shape is not None and tuple(value.shape) != tuple(shape): + raise ValueError(f"DPT tensor {name} has shape {value.shape}, expected {tuple(shape)}") + self.used.add(name) + return value + + def has(self, name: str) -> bool: + return name in self._tensors + + def unused(self) -> list[str]: + return sorted(set(self._tensors) - self.used) + + +def standardize(weight: np.ndarray, eps: float) -> np.ndarray: + """BiT weight standardization: per output channel, zero mean and unit biased variance.""" + flat = np.asarray(weight, dtype=np.float64).reshape(weight.shape[0], -1) + mean = flat.mean(axis=1, keepdims=True) + variance = np.square(flat - mean).mean(axis=1, keepdims=True) + return ((flat - mean) / np.sqrt(variance + eps)).reshape(weight.shape).astype(np.float32) + + +def _ws_conv(network, x, weights: _Weights, name, shape, *, stride=1, padding=(0, 0), work_np, + eps): + weight = standardize(weights.get(f"{name}.weight", shape), eps) + if weights.has(f"{name}.bias"): + raise NotImplementedError(f"dpt expects the bias-free BiT convolution {name}") + return graph_ops.add_conv2d( + network, x, weight, None, stride=(stride, stride), + pre_padding=(padding[0], padding[0]), post_padding=(padding[1], padding[1]), + dtype=work_np) + + +def _group_norm(network, x, weights: _Weights, name, groups, work_np, *, relu: bool): + channels = int(tuple(x.shape)[1]) + y = graph_ops.add_group_norm( + network, x, weights.get(f"{name}.weight", (channels,)), + weights.get(f"{name}.bias", (channels,)), groups, config_module.GROUP_NORM_EPS, + dtype=work_np) + return graph_ops.add_relu(network, y) if relu else y + + +def _bit(network, image, weights: _Weights, cfg, work_np): + """BiT stem and bottleneck stages. Returns the output map of every stage.""" + backbone = cfg["backbone"] + groups = backbone["num_groups"] + eps = config_module.LAYER_WEIGHT_EPS + + x = _ws_conv(network, image, weights, f"{_BIT}.embedder.convolution", + (backbone["embedding_size"], 3, 7, 7), stride=2, + padding=backbone["stem_padding"], work_np=work_np, + eps=config_module.STEM_WEIGHT_EPS) + x = _group_norm(network, x, weights, f"{_BIT}.embedder.norm", groups, work_np, relu=True) + pool_before, pool_after = backbone["pool_padding"] + x = graph_ops.add_zero_pad(network, x, (pool_before, pool_before), (pool_after, pool_after)) + x = graph_ops.add_max_pool(network, x, (3, 3), (2, 2)) + + outputs = [] + for stage_index, stage in enumerate(backbone["stages"]): + for layer_index in range(stage["depth"]): + prefix = f"{_BIT}.encoder.stages.{stage_index}.layers.{layer_index}" + shapes = config_module.bit_layer_shapes(stage, layer_index) + stride = stage["stride"] if layer_index == 0 else 1 + shortcut = x + if layer_index == 0: + shortcut = _ws_conv(network, x, weights, f"{prefix}.downsample.conv", + shapes["downsample.conv"], + stride=stride, padding=stage["downsample_padding"], + work_np=work_np, eps=eps) + shortcut = _group_norm(network, shortcut, weights, f"{prefix}.downsample.norm", + groups, work_np, relu=False) + y = _ws_conv(network, x, weights, f"{prefix}.conv1", shapes["conv1"], + work_np=work_np, eps=eps) + y = _group_norm(network, y, weights, f"{prefix}.norm1", groups, work_np, relu=True) + y = _ws_conv(network, y, weights, f"{prefix}.conv2", shapes["conv2"], stride=stride, + padding=stage["conv2_padding"] if layer_index == 0 else (1, 1), + work_np=work_np, eps=eps) + y = _group_norm(network, y, weights, f"{prefix}.norm2", groups, work_np, relu=True) + y = _ws_conv(network, y, weights, f"{prefix}.conv3", shapes["conv3"], + work_np=work_np, eps=eps) + y = _group_norm(network, y, weights, f"{prefix}.norm3", groups, work_np, relu=False) + x = graph_ops.add_relu(network, graph_ops.add_sum(network, y, shortcut)) + expected = (1, stage["out_channels"], stage["out_side"], stage["out_side"]) + if tuple(int(v) for v in x.shape) != expected: + raise RuntimeError(f"BiT stage {stage_index} produced {tuple(x.shape)}, not {expected}") + outputs.append(x) + return outputs + + +def _vit(network, feature_map, weights: _Weights, cfg, work_np): + """Hybrid patch embedding and the ViT encoder; returns the tapped hidden states.""" + hidden = cfg["hidden_size"] + heads = cfg["num_attention_heads"] + head_dim = cfg["head_dim"] + grid = cfg["patch_grid"] + tokens = 1 + grid * grid + eps = cfg["layer_norm_eps"] + channels = int(tuple(feature_map.shape)[1]) + + projected = graph_ops.add_conv2d( + network, feature_map, weights.get("dpt.embeddings.projection.weight", + (hidden, channels, 1, 1)), + weights.get("dpt.embeddings.projection.bias", (hidden,)), dtype=work_np) + patches = graph_ops.map_to_tokens(network, projected) + cls_token = graph_ops.add_constant( + network, (1, 1, hidden), weights.get("dpt.embeddings.cls_token", (1, 1, hidden)), + dtype=work_np) + sequence = network.add_concatenation([cls_token, patches]) + sequence.axis = 1 + position = weights.get("dpt.embeddings.position_embeddings") + if position.shape != (1, tokens, hidden): + raise NotImplementedError( + f"DPT position embeddings cover {position.shape[1]} tokens; this family builds the " + f"checkpoint's native {grid}x{grid} grid ({tokens} tokens) only") + states = graph_ops.add_sum( + network, sequence.get_output(0), + graph_ops.add_constant(network, (1, tokens, hidden), position, dtype=work_np)) + + linear_bias = cfg["qkv_bias"] + scale = 1.0 / math.sqrt(head_dim) + taps = {} + for index in range(cfg["num_hidden_layers"]): + prefix = f"dpt.encoder.layer.{index}" + residual = states + normed = graph_ops.add_layer_norm( + network, states, weights.get(f"{prefix}.layernorm_before.weight", (hidden,)), + weights.get(f"{prefix}.layernorm_before.bias", (hidden,)), eps, dtype=work_np) + projections = [] + for part in ("query", "key", "value"): + name = f"{prefix}.attention.attention.{part}" + bias = weights.get(f"{name}.bias", (hidden,)) if linear_bias else None + projections.append(graph_ops.split_heads( + network, + graph_ops.add_linear(network, normed, weights.get(f"{name}.weight", + (hidden, hidden)), + bias, dtype=work_np), + tokens, heads, head_dim)) + context = graph_ops.merge_heads( + network, graph_ops.add_attention(network, *projections, scale), tokens, hidden) + attended = graph_ops.add_linear( + network, context, weights.get(f"{prefix}.attention.output.dense.weight", + (hidden, hidden)), + weights.get(f"{prefix}.attention.output.dense.bias", (hidden,)), dtype=work_np) + states = graph_ops.add_sum(network, attended, residual) + + residual = states + normed = graph_ops.add_layer_norm( + network, states, weights.get(f"{prefix}.layernorm_after.weight", (hidden,)), + weights.get(f"{prefix}.layernorm_after.bias", (hidden,)), eps, dtype=work_np) + inner = graph_ops.add_gelu(network, graph_ops.add_linear( + network, normed, weights.get(f"{prefix}.intermediate.dense.weight", + (cfg["intermediate_size"], hidden)), + weights.get(f"{prefix}.intermediate.dense.bias", (cfg["intermediate_size"],)), + dtype=work_np)) + outer = graph_ops.add_linear( + network, inner, weights.get(f"{prefix}.output.dense.weight", + (hidden, cfg["intermediate_size"])), + weights.get(f"{prefix}.output.dense.bias", (hidden,)), dtype=work_np) + states = graph_ops.add_sum(network, outer, residual) + if index in cfg["tap_layers"]: + taps[index] = states + if index >= max(cfg["tap_layers"]): + # Layers past the last tap (and the encoder's final LayerNorm) feed only + # the pooled output, which depth estimation does not use. + break + return [taps[index] for index in cfg["tap_layers"]] + + +def _reassemble(network, state, zeros, weights: _Weights, cfg, stage: int, work_np): + """Drop the class token, append it to every token, project, lay out and resize. + + ``zeros`` is a [1, patches, hidden] zero tensor; adding the class token to it + broadcasts the token over every patch exactly. + """ + hidden = cfg["hidden_size"] + grid = cfg["patch_grid"] + prefix = "neck.reassemble_stage" + patches = network.add_slice(state, (0, 1, 0), (1, grid * grid, hidden), (1, 1, 1)) + cls_token = network.add_slice(state, (0, 0, 0), (1, 1, hidden), (1, 1, 1)) + readout = graph_ops.add_sum(network, zeros, cls_token.get_output(0)) + pair = network.add_concatenation([patches.get_output(0), readout]) + pair.axis = 2 + projected = graph_ops.add_gelu(network, graph_ops.add_linear( + network, pair.get_output(0), + weights.get(f"{prefix}.readout_projects.{stage}.0.weight", (hidden, 2 * hidden)), + weights.get(f"{prefix}.readout_projects.{stage}.0.bias", (hidden,)), dtype=work_np)) + feature = graph_ops.tokens_to_map(network, projected, grid, grid) + + channels = cfg["neck_hidden_sizes"][stage] + feature = graph_ops.add_conv2d( + network, feature, weights.get(f"{prefix}.layers.{stage}.projection.weight", + (channels, hidden, 1, 1)), + weights.get(f"{prefix}.layers.{stage}.projection.bias", (channels,)), dtype=work_np) + factor = cfg["reassemble_factors"][stage] + if factor < 1.0: + step = int(round(1.0 / factor)) + feature = graph_ops.add_conv2d( + network, feature, weights.get(f"{prefix}.layers.{stage}.resize.weight", + (channels, channels, 3, 3)), + weights.get(f"{prefix}.layers.{stage}.resize.bias", (channels,)), + stride=(step, step), pre_padding=(1, 1), post_padding=(1, 1), dtype=work_np) + return feature + + +def _residual_unit(network, x, weights: _Weights, prefix, cfg, work_np): + """Pre-activation residual unit: conv2(relu(conv1(relu(x)))) + x.""" + channels = cfg["fusion_hidden_size"] + hidden = graph_ops.add_relu(network, x) + for index, conv in enumerate(("convolution1", "convolution2")): + bias = (weights.get(f"{prefix}.{conv}.bias", (channels,)) if cfg["fusion_bias"] + else None) + hidden = graph_ops.add_conv2d( + network, hidden, weights.get(f"{prefix}.{conv}.weight", (channels, channels, 3, 3)), + bias, pre_padding=(1, 1), post_padding=(1, 1), dtype=work_np) + if index == 0: + hidden = graph_ops.add_relu(network, hidden) + return graph_ops.add_sum(network, hidden, x) + + +def _neck(network, features, weights: _Weights, cfg, work_np): + fusion = cfg["fusion_hidden_size"] + maps = [ + graph_ops.add_conv2d( + network, feature, weights.get(f"neck.convs.{index}.weight", + (fusion, cfg["neck_hidden_sizes"][index], 3, 3)), + None, pre_padding=(1, 1), post_padding=(1, 1), dtype=work_np) + for index, feature in enumerate(features) + ] + fused = None + for index, feature in enumerate(reversed(maps)): + prefix = f"neck.fusion_stage.layers.{index}" + if fused is None: + hidden = feature + else: + residual = feature + target = tuple(int(v) for v in fused.shape)[-2:] + if tuple(int(v) for v in residual.shape)[-2:] != target: + residual = graph_ops.add_resize_to(network, residual, target, align_corners=False) + residual = _residual_unit(network, residual, weights, f"{prefix}.residual_layer1", + cfg, work_np) + hidden = graph_ops.add_sum(network, fused, residual) + hidden = _residual_unit(network, hidden, weights, f"{prefix}.residual_layer2", cfg, + work_np) + side = tuple(int(v) for v in hidden.shape)[-2:] + hidden = graph_ops.add_resize_to(network, hidden, (side[0] * 2, side[1] * 2), + align_corners=True) + fused = graph_ops.add_conv2d( + network, hidden, weights.get(f"{prefix}.projection.weight", (fusion, fusion, 1, 1)), + weights.get(f"{prefix}.projection.bias", (fusion,)), dtype=work_np) + return fused + + +def _head(network, fused, weights: _Weights, cfg, work_np): + fusion = cfg["fusion_hidden_size"] + half = fusion // 2 + hidden = graph_ops.add_conv2d( + network, fused, weights.get("head.head.0.weight", (half, fusion, 3, 3)), + weights.get("head.head.0.bias", (half,)), pre_padding=(1, 1), post_padding=(1, 1), + dtype=work_np) + side = tuple(int(v) for v in hidden.shape)[-2:] + hidden = graph_ops.add_resize_to(network, hidden, (side[0] * 2, side[1] * 2), + align_corners=True) + hidden = graph_ops.add_conv2d( + network, hidden, weights.get("head.head.2.weight", (32, half, 3, 3)), + weights.get("head.head.2.bias", (32,)), pre_padding=(1, 1), post_padding=(1, 1), + dtype=work_np) + hidden = graph_ops.add_relu(network, hidden) + hidden = graph_ops.add_conv2d( + network, hidden, weights.get("head.head.4.weight", (1, 32, 1, 1)), + weights.get("head.head.4.bias", (1,)), dtype=work_np) + return graph_ops.add_relu(network, hidden) + + +def _build_network(network, weights: _Weights, cfg: dict, work_np, work_trt) -> None: + size = cfg["image_size"] + pixel_values = network.add_input("pixel_values", trt.float32, (1, 3, size, size)) + image = graph_ops.retype(network, pixel_values, work_trt) + + stages = _bit(network, image, weights, cfg, work_np) + taps = _vit(network, stages[-1], weights, cfg, work_np) + patches, hidden = cfg["patch_grid"] ** 2, cfg["hidden_size"] + zeros = graph_ops.add_constant(network, (1, patches, hidden), np.zeros((1, patches, hidden)), + dtype=work_np) + features = stages[:2] + [ + _reassemble(network, state, zeros, weights, cfg, stage, work_np) + for stage, state in zip((2, 3), taps) + ] + depth = _head(network, _neck(network, features, weights, cfg, work_np), weights, cfg, + work_np) + if tuple(int(v) for v in depth.shape) != (1, 1, size, size): + raise RuntimeError(f"DPT head produced {tuple(depth.shape)}, not (1, 1, {size}, {size})") + depth = graph_ops.retype(network, depth, trt.float32) + depth.name = "predicted_depth" + network.mark_output(depth) + + # Weights the depth path never reads: the encoder's final LayerNorm and the + # layers after the last tap feed only the pooled output, the first fusion + # layer has no residual, and the identity reassemble stages carry nothing. + unused = [name for name in weights.unused() if not _ignorable(name, cfg)] + if unused: + raise ValueError("DPT checkpoint has tensors this family does not map: " + + ", ".join(unused[:8])) + + +def _ignorable(name: str, cfg: dict) -> bool: + if name.startswith("dpt.layernorm.") or name.startswith("neck.fusion_stage.layers.0." + "residual_layer1."): + return True + if name.startswith("dpt.encoder.layer."): + return int(name.split(".")[3]) > max(cfg["tap_layers"]) + return False + + +def build_engine(weights: _Weights, cfg: dict, *, precision: str, verbose: bool = False) -> bytes: + logger = trt.Logger(trt.Logger.VERBOSE if verbose else trt.Logger.WARNING) + builder = trt.Builder(logger) + network = builder.create_network(1 << int(trt.NetworkDefinitionCreationFlag.STRONGLY_TYPED)) + builder_config = builder.create_builder_config() + builder_config.builder_optimization_level = 3 + if precision == "fp16": + work_np, work_trt = np.float16, trt.float16 + else: + work_np, work_trt = np.float32, trt.float32 + # An FP32 engine computes in FP32: no TF32 GEMMs or convolutions. + builder_config.clear_flag(trt.BuilderFlag.TF32) + _build_network(network, weights, cfg, work_np, work_trt) + plan = builder.build_serialized_network(network, builder_config) + if plan is None: + raise RuntimeError("DPT TensorRT engine build failed") + return bytes(plan) + + +def build(request, writer) -> None: + """Build one DPT-Hybrid monocular-depth bundle.""" + if request.task != "monocular_depth": + raise ValueError("dpt supports only task=monocular_depth") + if request.backend != "trt": + raise ValueError("dpt supports only backend=trt") + if request.dynamic_kv_cache: + raise NotImplementedError("dpt does not support dynamic_kv_cache") + if request.max_sequence_length not in {None, 1}: + raise NotImplementedError("dpt supports only max_sequence_length=1") + if request.max_batch_size != 1: + raise NotImplementedError("dpt does not support max_batch_size") + if request.tensor_parallel_size != 1: + raise NotImplementedError("dpt does not support tensor parallelism") + if request.context_parallel_size != 1: + raise NotImplementedError("dpt does not support context parallelism") + if request.video_num_frames is not None: + raise NotImplementedError("dpt does not support video_num_frames") + if request.quantization not in {None, "none"}: + raise NotImplementedError(f"dpt does not support quantization={request.quantization!r}") + if request.fp32_layers: + raise NotImplementedError("dpt does not support mixed-precision layers") + if request.mtp_seq_len is not None: + raise NotImplementedError("dpt does not support MTP speculative decoding") + precision = str(request.precision).lower() + if precision not in {"fp32", "fp16"}: + raise ValueError(f"Unsupported dpt precision: {precision}") + + model_dir = Path(request.model_dir) + cfg = config_module.load(model_dir) + config_module.check_requested_image_size("image_height", request.image_height, + cfg["image_size"]) + config_module.check_requested_image_size("image_width", request.image_width, + cfg["image_size"]) + config_module.check_engine_input(cfg["processor"], precision) + + tensors = load_tensors(model_dir) + # Before any graph is built: a backbone configured wider or narrower than the + # checkpoint's weights is refused, not built from the weights alone. + config_module.check_weight_shapes(tensors, config_module.bit_weight_shapes(cfg)) + weights = _Weights(tensors) + plan = build_engine(weights, cfg, precision=precision, verbose=bool(request.verbose)) + + processor = cfg["processor"] + writer.set_header(family="dpt", task=request.task, backend=request.backend) + writer.add_bytes("engine.plan", plan) + writer.add_json( + "runtime.json", + { + "input_image_h": cfg["image_size"], + "input_image_w": cfg["image_size"], + "rescale_factor": processor["rescale_factor"], + "image_mean": processor["image_mean"], + "image_std": processor["image_std"], + }, + ) diff --git a/families/dpt/requirements.txt b/families/dpt/requirements.txt new file mode 100644 index 0000000000..f43ac85079 --- /dev/null +++ b/families/dpt/requirements.txt @@ -0,0 +1,6 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +torch>=2.6 +transformers==5.2.0 +Pillow==13.0.0 diff --git a/families/dpt/runtime/CMakeLists.txt b/families/dpt/runtime/CMakeLists.txt new file mode 100644 index 0000000000..b358688730 --- /dev/null +++ b/families/dpt/runtime/CMakeLists.txt @@ -0,0 +1,81 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +add_library(trtmc_model_dpt SHARED + image_ops.cpp + pipeline.cpp + plugin.cpp +) +# The image operations reproduce reference arithmetic operation by operation; +# fusing a multiply and an add would round differently. +set_source_files_properties(image_ops.cpp PROPERTIES COMPILE_OPTIONS "-ffp-contract=off") + +target_include_directories(trtmc_model_dpt + PRIVATE + ${PROJECT_SOURCE_DIR} + ${PROJECT_SOURCE_DIR}/core/runtime/include +) +target_include_directories(trtmc_model_dpt SYSTEM PRIVATE + ${TRTMC_CUDA_INCLUDE_DIR} +) +target_link_libraries(trtmc_model_dpt PRIVATE + trtmc_core + nlohmann_json::nlohmann_json + ${TRTMC_CUDART_LIBRARY} +) +target_compile_options(trtmc_model_dpt PRIVATE + "$<$:-Wall;-Wextra;-Wpedantic>" +) +set_target_properties(trtmc_model_dpt PROPERTIES + LIBRARY_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}" + BUILD_RPATH "\$ORIGIN" + INSTALL_RPATH "\$ORIGIN" +) +install(TARGETS trtmc_model_dpt + LIBRARY DESTINATION ${CMAKE_INSTALL_LIBDIR} +) +# The library carries code adapted from Pillow and PyTorch; their notices ship with it. +install(FILES ${CMAKE_CURRENT_SOURCE_DIR}/../NOTICE + DESTINATION ${CMAKE_INSTALL_DATADIR}/trtmc/families/dpt +) + +if(TRTMC_BUILD_TESTS) + add_executable(test_dpt_image_ops + ${PROJECT_SOURCE_DIR}/families/dpt/tests/cpp/test_image_ops.cpp + image_ops.cpp + ) + target_include_directories(test_dpt_image_ops PRIVATE + ${PROJECT_SOURCE_DIR} + ) + target_compile_options(test_dpt_image_ops PRIVATE + -Wall -Wextra -Wpedantic + ) + add_test( + NAME dpt_image_ops + COMMAND test_dpt_image_ops + ) + + add_executable(test_dpt_pipeline + ${PROJECT_SOURCE_DIR}/families/dpt/tests/cpp/test_pipeline.cpp + image_ops.cpp + pipeline.cpp + ) + target_include_directories(test_dpt_pipeline PRIVATE + ${PROJECT_SOURCE_DIR} + ${PROJECT_SOURCE_DIR}/core/runtime/include + ) + target_include_directories(test_dpt_pipeline SYSTEM PRIVATE + ${TRTMC_CUDA_INCLUDE_DIR} + ) + target_link_libraries(test_dpt_pipeline PRIVATE + trtmc_core + nlohmann_json::nlohmann_json + ) + target_compile_options(test_dpt_pipeline PRIVATE + -Wall -Wextra -Wpedantic + ) + add_test( + NAME dpt_pipeline + COMMAND test_dpt_pipeline + ) +endif() diff --git a/families/dpt/runtime/image_ops.cpp b/families/dpt/runtime/image_ops.cpp new file mode 100644 index 0000000000..2873476096 --- /dev/null +++ b/families/dpt/runtime/image_ops.cpp @@ -0,0 +1,328 @@ +/* + * SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. + * SPDX-License-Identifier: Apache-2.0 + */ + +#include "families/dpt/runtime/image_ops.h" + +#include +#include +#include +#include +#include +#include + +namespace trtmc::dpt { +namespace { + +// Pillow keeps 8 bits for the result and two for overflow of an int. +constexpr int kPrecisionBits = 32 - 8 - 2; + +void require_size(std::int32_t height, std::int32_t width, const char* what) { + if (height <= 0 || width <= 0) + throw std::invalid_argument(std::string("dpt ") + what + " dimensions must be positive"); + const auto limit = static_cast(std::numeric_limits::max()) / 4U; + if (static_cast(height) * static_cast(width) > limit) + throw std::invalid_argument(std::string("dpt ") + what + " is too large"); +} + +std::uint8_t clip8(int value) { + const int shifted = value >> kPrecisionBits; + return static_cast(std::clamp(shifted, 0, 255)); +} + +double bilinear_filter(double x) { + if (x < 0.0) + x = -x; + return x < 1.0 ? 1.0 - x : 0.0; +} + +// One axis of Pillow's resampling: for every output index the first input +// index, the tap count and fixed-point weights (precompute_coeffs with the +// bilinear filter over the box (0, in_size), then normalize_coeffs_8bpc). +struct AxisCoefficients { + int ksize{0}; + std::vector first; + std::vector count; + std::vector weights; +}; + +AxisCoefficients precompute_coefficients(int in_size, int out_size) { + const float in0 = 0.0F; + const auto in1 = static_cast(in_size); + const double scale = static_cast(in1 - in0) / out_size; + const double filterscale = scale < 1.0 ? 1.0 : scale; + const double support = 1.0 * filterscale; + const int ksize = static_cast(std::ceil(support)) * 2 + 1; + const double inv_filterscale = 1.0 / filterscale; + + AxisCoefficients result; + result.ksize = ksize; + result.first.resize(static_cast(out_size)); + result.count.resize(static_cast(out_size)); + result.weights.assign(static_cast(out_size) * static_cast(ksize), 0); + std::vector kernel(static_cast(ksize)); + for (int xx = 0; xx < out_size; ++xx) { + const double center = in0 + (xx + 0.5) * scale; + int xmin = static_cast(center - support + 0.5); + if (xmin < 0) + xmin = 0; + int xmax = static_cast(center + support + 0.5); + if (xmax > in_size) + xmax = in_size; + xmax -= xmin; + double total = 0.0; + for (int x = 0; x < xmax; ++x) { + const double weight = bilinear_filter((x + xmin - center + 0.5) * inv_filterscale); + kernel[static_cast(x)] = weight; + total += weight; + } + if (total != 0.0) { + for (int x = 0; x < xmax; ++x) + kernel[static_cast(x)] /= total; + } + std::int32_t* fixed = &result.weights[static_cast(xx) * ksize]; + for (int x = 0; x < xmax; ++x) { + const double value = kernel[static_cast(x)]; + const double scaled = value * (1 << kPrecisionBits); + fixed[x] = value < 0 ? static_cast(-0.5 + scaled) : static_cast(0.5 + scaled); + } + result.first[static_cast(xx)] = xmin; + result.count[static_cast(xx)] = xmax; + } + return result; +} + +std::vector horizontal_pass(const std::vector& source, int rows, + int in_width, int out_width) { + const AxisCoefficients axis = precompute_coefficients(in_width, out_width); + std::vector output(static_cast(rows) * out_width * 3U); + for (int y = 0; y < rows; ++y) { + const std::uint8_t* line = &source[static_cast(y) * in_width * 3U]; + std::uint8_t* target = &output[static_cast(y) * out_width * 3U]; + for (int xx = 0; xx < out_width; ++xx) { + const int xmin = axis.first[static_cast(xx)]; + const int taps = axis.count[static_cast(xx)]; + const std::int32_t* weight = &axis.weights[static_cast(xx) * axis.ksize]; + int sums[3] = {1 << (kPrecisionBits - 1), 1 << (kPrecisionBits - 1), + 1 << (kPrecisionBits - 1)}; + for (int x = 0; x < taps; ++x) { + const std::uint8_t* pixel = line + static_cast(x + xmin) * 3U; + for (int channel = 0; channel < 3; ++channel) + sums[channel] += pixel[channel] * weight[x]; + } + for (int channel = 0; channel < 3; ++channel) + target[static_cast(xx) * 3U + channel] = clip8(sums[channel]); + } + } + return output; +} + +std::vector vertical_pass(const std::vector& source, int width, + int in_height, int out_height) { + const AxisCoefficients axis = precompute_coefficients(in_height, out_height); + std::vector output(static_cast(out_height) * width * 3U); + for (int yy = 0; yy < out_height; ++yy) { + const int ymin = axis.first[static_cast(yy)]; + const int taps = axis.count[static_cast(yy)]; + const std::int32_t* weight = &axis.weights[static_cast(yy) * axis.ksize]; + std::uint8_t* target = &output[static_cast(yy) * width * 3U]; + for (int xx = 0; xx < width; ++xx) { + int sums[3] = {1 << (kPrecisionBits - 1), 1 << (kPrecisionBits - 1), + 1 << (kPrecisionBits - 1)}; + for (int y = 0; y < taps; ++y) { + const std::uint8_t* pixel = + &source[(static_cast(y + ymin) * width + xx) * 3U]; + for (int channel = 0; channel < 3; ++channel) + sums[channel] += pixel[channel] * weight[y]; + } + for (int channel = 0; channel < 3; ++channel) + target[static_cast(xx) * 3U + channel] = clip8(sums[channel]); + } + } + return output; +} + +// PyTorch's cubic convolution kernel (A = -0.75) in float, as +// get_cubic_upsample_coefficients evaluates it. +float cubic_convolution1(float x, float a) { + return ((a + 2) * x - (a + 3)) * x * x + 1; +} + +float cubic_convolution2(float x, float a) { + return ((a * x - 5 * a) * x + 8 * a) * x - 4 * a; +} + +struct CubicAxis { + std::vector> index; + std::vector> weight; +}; + +CubicAxis cubic_axis(std::int32_t in_size, std::int32_t out_size) { + // area_pixel_compute_scale and area_pixel_compute_source_index with + // align_corners=False and no explicit scale, in float. + const float scale = static_cast(in_size) / static_cast(out_size); + CubicAxis axis; + axis.index.resize(static_cast(out_size)); + axis.weight.resize(static_cast(out_size)); + for (std::int32_t i = 0; i < out_size; ++i) { + const float real = scale * (static_cast(i) + 0.5F) - 0.5F; + const auto floor_index = static_cast(std::floor(real)); + const std::int64_t input_index = std::min(floor_index, in_size - 1); + const float lambda = std::min(std::max(real - static_cast(input_index), 0.0F), 1.0F); + const float a = -0.75F; + const float x1 = lambda; + const float x2 = static_cast(1.0 - static_cast(lambda)); + auto& weight = axis.weight[static_cast(i)]; + weight[0] = cubic_convolution2(static_cast(static_cast(x1) + 1.0), a); + weight[1] = cubic_convolution1(x1, a); + weight[2] = cubic_convolution1(x2, a); + weight[3] = cubic_convolution2(static_cast(static_cast(x2) + 1.0), a); + auto& index = axis.index[static_cast(i)]; + for (std::int64_t tap = 0; tap < 4; ++tap) { + index[static_cast(tap)] = static_cast( + std::clamp(input_index + tap - 1, 0, in_size - 1)); + } + } + return axis; +} + +// rescale() multiplies in float64 and stores float32; normalize() subtracts +// and divides in float32. The caller has checked that the product fits float32. +float rescaled(std::uint8_t level, double rescale_factor) { + return static_cast(static_cast(level) * rescale_factor); +} + +} // namespace + +void check_preprocess_config(const PreprocessConfig& config) { + require_size(config.input_image_h, config.input_image_w, "engine input"); + constexpr double kFloatMax = std::numeric_limits::max(); + if (!std::isfinite(config.rescale_factor) || config.rescale_factor <= 0.0 || + config.rescale_factor > kFloatMax / 255.0) { + throw std::invalid_argument( + "dpt rescale factor must be positive and keep 255 within float32"); + } + for (std::size_t channel = 0; channel < 3U; ++channel) { + const float mean = config.image_mean[channel]; + const float std = config.image_std[channel]; + if (!std::isfinite(mean) || !std::isfinite(std) || std == 0.0F) + throw std::invalid_argument("dpt image mean and std must be finite, std non-zero"); + for (int level = 0; level < 256; ++level) { + const float value = rescaled(static_cast(level), config.rescale_factor); + if (!std::isfinite((value - mean) / std)) { + throw std::invalid_argument( + "dpt image mean and std overflow float32 for an 8-bit sample"); + } + } + } +} + +std::vector to_rgb8(const float* pixels, std::int32_t height, std::int32_t width) { + if (pixels == nullptr) + throw std::invalid_argument("dpt source image must be non-empty"); + require_size(height, width, "source image"); + const auto count = static_cast(height) * static_cast(width) * 3U; + std::vector rgb(count); + for (std::size_t index = 0; index < count; ++index) { + const float value = pixels[index]; + if (!std::isfinite(value)) + throw std::invalid_argument("dpt source image contains a non-finite pixel"); + const float level = std::round(value * 255.0F); + rgb[index] = static_cast(std::clamp(level, 0.0F, 255.0F)); + } + return rgb; +} + +std::vector resize_bilinear_rgb8(const std::uint8_t* rgb, std::int32_t height, + std::int32_t width, std::int32_t out_height, + std::int32_t out_width) { + if (rgb == nullptr) + throw std::invalid_argument("dpt resize source must be non-empty"); + require_size(height, width, "resize source"); + require_size(out_height, out_width, "resize target"); + + const bool need_horizontal = out_width != width; + const bool need_vertical = out_height != height; + // Pillow 13 runs the vertical pass first when the height shrinks by more + // than twice as many pixels as the width does. + const bool horizontal_first = + !((height - out_height) > 0 && static_cast(height - out_height) > + static_cast(width - out_width) * 2); + + std::vector image(rgb, rgb + static_cast(height) * width * 3U); + int rows = height; + int columns = width; + const auto horizontal = [&]() { + image = horizontal_pass(image, rows, columns, out_width); + columns = out_width; + }; + const auto vertical = [&]() { + image = vertical_pass(image, columns, rows, out_height); + rows = out_height; + }; + if (horizontal_first) { + if (need_horizontal) + horizontal(); + if (need_vertical) + vertical(); + } else { + if (need_vertical) + vertical(); + if (need_horizontal) + horizontal(); + } + return image; +} + +std::vector preprocess_image(const float* pixels, std::int32_t height, std::int32_t width, + const PreprocessConfig& config) { + check_preprocess_config(config); + const auto rgb = to_rgb8(pixels, height, width); + const auto resized = + resize_bilinear_rgb8(rgb.data(), height, width, config.input_image_h, config.input_image_w); + + const auto plane = static_cast(config.input_image_h) * config.input_image_w; + std::vector pixel_values(3U * plane); + for (std::size_t index = 0; index < plane; ++index) { + for (std::size_t channel = 0; channel < 3U; ++channel) { + const float value = rescaled(resized[index * 3U + channel], config.rescale_factor); + pixel_values[channel * plane + index] = + (value - config.image_mean[channel]) / config.image_std[channel]; + } + } + return pixel_values; +} + +std::vector resize_bicubic(const float* source, std::int32_t source_h, std::int32_t source_w, + std::int32_t target_h, std::int32_t target_w) { + if (source == nullptr) + throw std::invalid_argument("dpt depth map must be non-empty"); + require_size(source_h, source_w, "depth map"); + require_size(target_h, target_w, "depth target"); + const CubicAxis rows = cubic_axis(source_h, target_h); + const CubicAxis columns = cubic_axis(source_w, target_w); + + std::vector output(static_cast(target_h) * target_w); + for (std::int32_t y = 0; y < target_h; ++y) { + const auto& row_index = rows.index[static_cast(y)]; + const auto& row_weight = rows.weight[static_cast(y)]; + for (std::int32_t x = 0; x < target_w; ++x) { + const auto& column_index = columns.index[static_cast(x)]; + const auto& column_weight = columns.weight[static_cast(x)]; + // Width inside, height outside, each accumulated tap by tap. + float value = 0.0F; + for (std::size_t j = 0; j < 4U; ++j) { + const float* line = source + static_cast(row_index[j]) * source_w; + float across = line[column_index[0]] * column_weight[0]; + for (std::size_t k = 1; k < 4U; ++k) + across += line[column_index[k]] * column_weight[k]; + value = j == 0 ? across * row_weight[0] : value + across * row_weight[j]; + } + output[static_cast(y) * target_w + x] = value; + } + } + return output; +} + +} // namespace trtmc::dpt diff --git a/families/dpt/runtime/image_ops.h b/families/dpt/runtime/image_ops.h new file mode 100644 index 0000000000..087325736b --- /dev/null +++ b/families/dpt/runtime/image_ops.h @@ -0,0 +1,52 @@ +/* + * SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. + * SPDX-License-Identifier: Apache-2.0 + */ + +#pragma once + +#include +#include +#include + +namespace trtmc::dpt { + +struct PreprocessConfig { + std::int32_t input_image_h{384}; + std::int32_t input_image_w{384}; + double rescale_factor{1.0 / 255.0}; + std::array image_mean{0.5F, 0.5F, 0.5F}; + std::array image_std{0.5F, 0.5F, 0.5F}; +}; + +// What preprocess_image needs of a configuration: a positive engine input size, +// a finite positive rescale factor, and float32 means and standard deviations +// with which every 8-bit sample rescales and normalizes to a finite value, +// computed one operation at a time as preprocess_image computes it. Throws +// std::invalid_argument otherwise. +void check_preprocess_config(const PreprocessConfig& config); + +// Interleaved RGB pixels in [0, 1] (8-bit samples divided by 255) back to the +// 8-bit samples the reference's PIL image holds: round(value * 255), clamped. +std::vector to_rgb8(const float* pixels, std::int32_t height, std::int32_t width); + +// Pillow 13.0.0 Image.resize(size, Image.BILINEAR) of an interleaved 8-bit RGB +// image: two separable passes with 22-bit fixed-point weights, each rounded +// to 8 bits, the vertical pass first when the height shrinks by more than +// twice as many pixels as the width. Adapted from Pillow; see NOTICE. +std::vector resize_bilinear_rgb8(const std::uint8_t* rgb, std::int32_t height, + std::int32_t width, std::int32_t out_height, + std::int32_t out_width); + +// The DPT image processor: resize to the engine input, rescale, normalize, +// planar CHW float32. +std::vector preprocess_image(const float* pixels, std::int32_t height, std::int32_t width, + const PreprocessConfig& config); + +// torch.nn.functional.interpolate(mode="bicubic", align_corners=False) of one +// row-major [height, width] float map: cubic convolution with A = -0.75 and +// border-clamped taps. Adapted from PyTorch; see NOTICE. +std::vector resize_bicubic(const float* source, std::int32_t source_h, std::int32_t source_w, + std::int32_t target_h, std::int32_t target_w); + +} // namespace trtmc::dpt diff --git a/families/dpt/runtime/pipeline.cpp b/families/dpt/runtime/pipeline.cpp new file mode 100644 index 0000000000..b2d095f4bf --- /dev/null +++ b/families/dpt/runtime/pipeline.cpp @@ -0,0 +1,199 @@ +/* + * SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. + * SPDX-License-Identifier: Apache-2.0 + */ + +#include "families/dpt/runtime/pipeline.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace trtmc::dpt { +namespace { + +constexpr std::array kRuntimeKeys = {"input_image_h", "input_image_w", + "rescale_factor", "image_mean", "image_std"}; + +[[noreturn]] void contract_error(const std::string& what) { + throw std::runtime_error("dpt runtime.json " + what); +} + +// nlohmann keeps the last of two equal keys; refuse them instead. +nlohmann::json parse_unique_keys(const std::string& text) { + std::vector> open_objects; + const nlohmann::json::parser_callback_t callback = + [&open_objects](int /*depth*/, nlohmann::json::parse_event_t event, + nlohmann::json& parsed) { + if (event == nlohmann::json::parse_event_t::object_start) { + open_objects.emplace_back(); + } else if (event == nlohmann::json::parse_event_t::object_end) { + open_objects.pop_back(); + } else if (event == nlohmann::json::parse_event_t::key) { + const auto key = parsed.get(); + if (!open_objects.back().insert(key).second) + contract_error("repeats the key " + key); + } + return true; + }; + try { + return nlohmann::json::parse(text, callback); + } catch (const nlohmann::json::exception& error) { + contract_error(std::string("is not valid JSON: ") + error.what()); + } +} + +// A JSON integer (not 384.0) from 1 to INT32_MAX, checked before narrowing. +std::int32_t positive_int32(const nlohmann::json& json, const char* key) { + const auto& value = json.at(key); + constexpr auto kMax = static_cast(std::numeric_limits::max()); + if (value.is_number_unsigned()) { + const auto number = value.get(); + if (number >= 1U && number <= kMax) + return static_cast(number); + } else if (value.is_number_integer()) { + const auto number = value.get(); + if (number >= 1 && static_cast(number) <= kMax) + return static_cast(number); + } + contract_error(std::string(key) + " must be an integer from 1 to 2147483647"); +} + +double finite_number(const nlohmann::json& value, const std::string& what) { + if (!value.is_number()) + contract_error(what + " must be a number"); + const auto number = value.get(); + if (!std::isfinite(number)) + contract_error(what + " must be finite"); + return number; +} + +std::array channel_values(const nlohmann::json& json, const char* key) { + const auto& value = json.at(key); + if (!value.is_array() || value.size() != 3U) + contract_error(std::string(key) + " must hold three numbers"); + std::array result{}; + for (std::size_t channel = 0; channel < 3U; ++channel) { + const double number = finite_number(value[channel], key); + if (std::fabs(number) > static_cast(std::numeric_limits::max())) + contract_error(std::string(key) + " must fit float32"); + result[channel] = static_cast(number); + } + return result; +} + +bool all_finite(const float* values, std::size_t count) { + return std::all_of(values, values + count, [](float value) { return std::isfinite(value); }); +} + +const Tensor& require_output(const std::unordered_map& outputs, + const char* name) { + const auto found = outputs.find(name); + if (found == outputs.end()) + throw std::runtime_error("dpt engine did not produce " + std::string(name)); + return found->second; +} + +} // namespace + +PreprocessConfig parse_runtime_config(const std::string& text) { + const auto json = parse_unique_keys(text); + if (!json.is_object()) + contract_error("must hold a JSON object"); + for (const auto& item : json.items()) { + if (std::find(kRuntimeKeys.begin(), kRuntimeKeys.end(), item.key()) == kRuntimeKeys.end()) + contract_error("has the unknown key " + item.key()); + } + for (const char* key : kRuntimeKeys) { + if (!json.contains(key)) + contract_error(std::string("is missing ") + key); + } + PreprocessConfig config; + config.input_image_h = positive_int32(json, "input_image_h"); + config.input_image_w = positive_int32(json, "input_image_w"); + config.rescale_factor = finite_number(json.at("rescale_factor"), "rescale_factor"); + config.image_mean = channel_values(json, "image_mean"); + config.image_std = channel_values(json, "image_std"); + try { + check_preprocess_config(config); + } catch (const std::invalid_argument& error) { + contract_error(std::string("does not hold a usable image pipeline: ") + error.what()); + } + return config; +} + +void check_engine_io(const ITrtModule& module, const PreprocessConfig& config) { + const std::vector input_shape{1, 3, config.input_image_h, config.input_image_w}; + const std::vector output_shape{1, 1, config.input_image_h, config.input_image_w}; + const auto inputs = module.input_info(); + if (inputs.size() != 1U || inputs[0].name != "pixel_values" || + inputs[0].dtype != DType::kFloat32 || inputs[0].shape != input_shape) { + throw std::runtime_error( + "dpt engine must take one float32 pixel_values [1, 3, H, W] of runtime.json"); + } + const auto outputs = module.output_info(); + if (outputs.size() != 1U || outputs[0].name != "predicted_depth" || + outputs[0].dtype != DType::kFloat32 || outputs[0].shape != output_shape) { + throw std::runtime_error( + "dpt engine must return one float32 predicted_depth [1, 1, H, W] of runtime.json"); + } +} + +DptPipeline::DptPipeline(std::unique_ptr model, PreprocessConfig preprocess_config) + : model_(std::move(model)), preprocess_config_(std::move(preprocess_config)) { + if (!model_ || !model_->ok()) + throw std::runtime_error("DptPipeline: invalid model"); + try { + check_preprocess_config(preprocess_config_); + } catch (const std::invalid_argument& error) { + throw std::runtime_error(std::string("DptPipeline: ") + error.what()); + } + check_engine_io(*model_, preprocess_config_); +} + +MonocularDepthResult DptPipeline::estimate_depth(const float* pixels, std::int32_t height, + std::int32_t width) { + auto pixel_values = preprocess_image(pixels, height, width, preprocess_config_); + + Tensor image; + image.data = pixel_values.data(); + image.shape = {1, 3, preprocess_config_.input_image_h, preprocess_config_.input_image_w}; + image.dtype = DType::kFloat32; + + auto outputs = model_->forward({{"pixel_values", image}}); + const Tensor& depth = require_output(outputs, "predicted_depth"); + if (depth.data == nullptr || depth.dtype != DType::kFloat32 || depth.shape.size() != 4 || + depth.shape[0] != 1 || depth.shape[1] != 1 || + depth.shape[2] != preprocess_config_.input_image_h || + depth.shape[3] != preprocess_config_.input_image_w) { + throw std::runtime_error("dpt engine output does not match the engine input size"); + } + const auto* engine_depth = static_cast(depth.data); + const auto engine_count = static_cast(preprocess_config_.input_image_h) * + static_cast(preprocess_config_.input_image_w); + if (!all_finite(engine_depth, engine_count)) + throw std::runtime_error("dpt engine produced a non-finite depth value"); + + MonocularDepthResult result; + result.height = height; + result.width = width; + // post_process_depth_estimation: bicubic, align_corners=False, onto the + // caller's image. + result.depth = resize_bicubic(engine_depth, preprocess_config_.input_image_h, + preprocess_config_.input_image_w, height, width); + if (!all_finite(result.depth.data(), result.depth.size())) + throw std::runtime_error("dpt depth map overflows float32 when resized to the image"); + return result; +} + +} // namespace trtmc::dpt diff --git a/families/dpt/runtime/pipeline.h b/families/dpt/runtime/pipeline.h new file mode 100644 index 0000000000..e8d96f0a7e --- /dev/null +++ b/families/dpt/runtime/pipeline.h @@ -0,0 +1,41 @@ +/* + * SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. + * SPDX-License-Identifier: Apache-2.0 + */ + +#pragma once + +#include "families/dpt/runtime/image_ops.h" +#include "trtmc/runtime/trt_module.h" +#include "trtmc/task.h" + +#include +#include + +namespace trtmc::dpt { + +// A bundle's runtime.json: exactly the keys the build writes, each of its JSON +// type (no conversion), no key twice, and values check_preprocess_config +// accepts. Throws std::runtime_error otherwise. +PreprocessConfig parse_runtime_config(const std::string& text); + +// The engine's inputs and outputs against runtime.json: one float32 input +// "pixel_values" [1, 3, H, W] and one float32 output "predicted_depth" +// [1, 1, H, W]. Throws std::runtime_error otherwise. +void check_engine_io(const ITrtModule& module, const PreprocessConfig& config); + +// Resize to the engine's fixed input, run it, and bring the relative inverse +// depth back to the caller's image size the way the reference post-processes. +class DptPipeline final : public IMonocularDepth { + public: + DptPipeline(std::unique_ptr model, PreprocessConfig preprocess_config); + + MonocularDepthResult estimate_depth(const float* pixels, std::int32_t height, + std::int32_t width) override; + + private: + std::unique_ptr model_; + PreprocessConfig preprocess_config_; +}; + +} // namespace trtmc::dpt diff --git a/families/dpt/runtime/plugin.cpp b/families/dpt/runtime/plugin.cpp new file mode 100644 index 0000000000..03e281a2df --- /dev/null +++ b/families/dpt/runtime/plugin.cpp @@ -0,0 +1,46 @@ +/* + * SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. + * SPDX-License-Identifier: Apache-2.0 + */ + +#include "families/dpt/runtime/pipeline.h" +#include "trtmc/runtime/family_factory.h" +#include "trtmc/runtime/trt_backend.h" + +#include +#include +#include +#include + +namespace trtmc::dpt { +namespace { + +std::vector require_section(const BundleReader& bundle, const char* name) { + const auto* section = bundle.find_section(name); + if (section == nullptr || section->length == 0) + throw std::runtime_error("bundle section is missing or empty: " + std::string(name)); + return bundle.read_section(name); +} + +std::unique_ptr load_engine(IBackend& backend, const std::vector& plan) { + ModuleCreateOptions options{}; + auto engine = backend.create_module(plan.data(), plan.size(), options); + if (!engine || !engine->ok()) + throw std::runtime_error("dpt engine failed to load"); + return engine; +} + +} // namespace +} // namespace trtmc::dpt + +extern "C" trtmc::ITask* trtmc_create_family(const trtmc::FamilyContext& context) { + if (context.kv_cache_size_bytes != 0) + throw std::invalid_argument("dpt does not support --kv-cache-size"); + const auto config_data = trtmc::dpt::require_section(context.reader, "runtime.json"); + auto config = + trtmc::dpt::parse_runtime_config(std::string(config_data.begin(), config_data.end())); + const auto plan = trtmc::dpt::require_section(context.reader, "engine.plan"); + auto engine = trtmc::dpt::load_engine(context.backend, plan); + // The constructor checks the engine's inputs and outputs before first use. + return new trtmc::dpt::DptPipeline(std::move(engine), std::move(config)); +} diff --git a/families/dpt/support.py b/families/dpt/support.py new file mode 100644 index 0000000000..6bf2e4ce05 --- /dev/null +++ b/families/dpt/support.py @@ -0,0 +1,14 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +"""Family-owned model and task support for DPT.""" + +from tensorrt_model_connect.model_support import family_support + + +describe = family_support( + model_types=("dpt",), + architectures=("DPTForDepthEstimation",), + tasks=("monocular_depth",), + default_task="monocular_depth", +) diff --git a/families/dpt/tests/__init__.py b/families/dpt/tests/__init__.py new file mode 100644 index 0000000000..ab05a13cd4 --- /dev/null +++ b/families/dpt/tests/__init__.py @@ -0,0 +1,4 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +"""DPT family tests.""" diff --git a/families/dpt/tests/cpp/generate_image_ops_goldens.py b/families/dpt/tests/cpp/generate_image_ops_goldens.py new file mode 100644 index 0000000000..0a39de766f --- /dev/null +++ b/families/dpt/tests/cpp/generate_image_ops_goldens.py @@ -0,0 +1,140 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +"""Write image_ops_goldens.h, the exact expectations of test_image_ops.cpp. + +Needs Pillow 13.0.0, transformers 5.2.0 and torch. Pillow resizes small +pseudo-random RGB images (horizontal-first, vertical-first, single-axis, +up- and downscaling, identity), ``DPTImageProcessor`` preprocesses one small +image end to end, and torch resizes a small float map bicubically on the CPU. +Run ``clang-format -i`` on the output afterwards. +""" + +from __future__ import annotations + +import sys +from pathlib import Path + +import numpy as np +import PIL +import torch +import transformers +from PIL import Image +from transformers import DPTImageProcessor + +# (height, width, out_height, out_width, seed) +RESIZES = ( + (5, 7, 4, 3, 1), # both axes shrink a little: horizontal pass first + (13, 4, 3, 5, 2), # height shrinks by more than twice the width: vertical first + (6, 6, 9, 6, 3), # vertical upscale only + (3, 11, 3, 4, 4), # horizontal downscale only + (10, 16, 3, 5, 5), # both shrink, horizontal first + (20, 10, 5, 9, 6), # height shrinks, width grows: vertical first + (4, 4, 4, 4, 7), # identity +) +PROCESSOR = (9, 5, 4, 3, 11) +BICUBIC_TARGETS = ((7, 3), (2, 9), (5, 4), (11, 13)) + + +def lcg_image(height: int, width: int, seed: int) -> np.ndarray: + """Pseudo-random bytes the C++ test regenerates with the same recurrence.""" + state = seed + values = np.empty(height * width * 3, dtype=np.uint8) + for index in range(values.size): + state = (state * 1103515245 + 12345) & 0x7FFFFFFF + values[index] = (state >> 16) & 0xFF + return values.reshape(height, width, 3) + + +def _bytes(values) -> str: + return "{" + ", ".join(str(int(value)) for value in values) + "}" + + +def _floats(values) -> str: + # Hexadecimal literals carry float32 values exactly. + return "{" + ", ".join(float(np.float32(value)).hex() + "F" for value in values) + "}" + + +def main(output: Path) -> None: + lines = [ + "/*", + " * SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. " + "All rights reserved.", + " * SPDX-License-Identifier: Apache-2.0", + " */", + "", + f"// Generated by generate_image_ops_goldens.py with Pillow {PIL.__version__}, " + f"transformers {transformers.__version__} and torch {torch.__version__}.", + "", + "#pragma once", + "", + "#include ", + "#include ", + "", + "namespace dpt_goldens {", + "", + "struct ResizeGolden {", + " int height;", + " int width;", + " int out_height;", + " int out_width;", + " std::uint32_t seed;", + " std::vector expected;", + "};", + "", + "struct BicubicGolden {", + " int height;", + " int width;", + " std::vector expected;", + "};", + "", + "inline const ResizeGolden kResizeGoldens[] = {", + ] + for height, width, out_height, out_width, seed in RESIZES: + resized = np.asarray(Image.fromarray(lcg_image(height, width, seed), "RGB").resize( + (out_width, out_height), Image.Resampling.BILINEAR)) + assert resized.shape == (out_height, out_width, 3) + lines.append(f" {{{height}, {width}, {out_height}, {out_width}, {seed}U, " + f"{_bytes(resized.reshape(-1))}}},") + lines.append("};") + + height, width, out_height, out_width, seed = PROCESSOR + processor = DPTImageProcessor( + do_resize=True, size={"height": out_height, "width": out_width}, resample=2, + keep_aspect_ratio=False, ensure_multiple_of=1, do_rescale=True, + rescale_factor=0.00392156862745098, do_normalize=True, image_mean=[0.5, 0.5, 0.5], + image_std=[0.5, 0.5, 0.5]) + pixel_values = processor(images=Image.fromarray(lcg_image(height, width, seed), "RGB"), + return_tensors="np")["pixel_values"][0] + assert pixel_values.dtype == np.float32 + assert pixel_values.shape == (3, out_height, out_width) + lines += [ + "", + f"inline constexpr int kProcessorSize[4] = {{{height}, {width}, {out_height}, " + f"{out_width}}};", + f"inline constexpr std::uint32_t kProcessorSeed = {seed}U;", + f"inline const std::vector kProcessorGolden = {_floats(pixel_values.reshape(-1))};", + ] + + generator = torch.Generator().manual_seed(0) + depth = torch.rand(5, 4, generator=generator, dtype=torch.float32) * 10.0 + lines += [ + "", + "inline constexpr int kBicubicSourceSize[2] = {5, 4};", + f"inline const std::vector kBicubicSource = {_floats(depth.reshape(-1).numpy())};", + "", + "inline const BicubicGolden kBicubicGoldens[] = {", + ] + for target in BICUBIC_TARGETS: + resized = torch.nn.functional.interpolate( + depth[None, None], size=target, mode="bicubic", align_corners=False)[0, 0] + lines.append(f" {{{target[0]}, {target[1]}, {_floats(resized.reshape(-1).numpy())}}},") + lines += ["};", "", "} // namespace dpt_goldens", ""] + output.write_text("\n".join(lines), encoding="utf-8") + + +if __name__ == "__main__": + if PIL.__version__ != "13.0.0" or transformers.__version__ != "5.2.0": + raise SystemExit("generate with Pillow 13.0.0 and transformers 5.2.0") + main(Path(sys.argv[1]) if len(sys.argv) > 1 + else Path(__file__).resolve().parent / "image_ops_goldens.h") diff --git a/families/dpt/tests/cpp/image_ops_goldens.h b/families/dpt/tests/cpp/image_ops_goldens.h new file mode 100644 index 0000000000..9391fca9c8 --- /dev/null +++ b/families/dpt/tests/cpp/image_ops_goldens.h @@ -0,0 +1,153 @@ +/* + * SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. + * SPDX-License-Identifier: Apache-2.0 + */ + +// Generated by generate_image_ops_goldens.py with Pillow 13.0.0, transformers 5.2.0 and +// torch 2.15.0+cpu. + +#pragma once + +#include +#include + +namespace dpt_goldens { + +struct ResizeGolden { + int height; + int width; + int out_height; + int out_width; + std::uint32_t seed; + std::vector expected; +}; + +struct BicubicGolden { + int height; + int width; + std::vector expected; +}; + +inline const ResizeGolden kResizeGoldens[] = { + {5, 7, 4, 3, 1U, {150, 120, 157, 170, 135, 187, 123, 85, 152, 124, 75, 101, + 106, 110, 173, 149, 102, 122, 136, 118, 73, 170, 171, 141, + 103, 148, 141, 120, 167, 58, 187, 128, 117, 125, 118, 121}}, + {13, 4, 3, 5, 2U, {149, 76, 123, 109, 136, 141, 103, 167, 131, 106, 155, 123, 89, 113, 144, + 117, 103, 130, 100, 135, 135, 112, 141, 110, 139, 135, 90, 159, 139, 107, + 181, 46, 120, 122, 101, 135, 82, 123, 129, 79, 136, 126, 108, 171, 149}}, + {6, 6, 9, 6, 3U, {83, 195, 125, 120, 142, 180, 77, 183, 72, 47, 109, 70, 61, 25, 229, + 112, 36, 76, 135, 178, 176, 104, 197, 150, 97, 217, 106, 112, 129, 81, + 118, 103, 140, 65, 60, 165, 180, 168, 195, 81, 221, 140, 109, 247, 150, + 173, 126, 98, 188, 188, 42, 23, 83, 226, 154, 201, 67, 51, 100, 217, + 83, 236, 191, 157, 36, 119, 242, 213, 9, 43, 81, 113, 96, 154, 98, + 110, 134, 173, 157, 231, 203, 104, 111, 88, 160, 185, 73, 135, 74, 96, + 43, 111, 169, 167, 202, 94, 218, 193, 198, 60, 186, 55, 76, 130, 134, + 198, 66, 89, 39, 158, 207, 133, 211, 37, 137, 52, 172, 84, 96, 73, + 122, 51, 92, 106, 61, 19, 32, 96, 118, 161, 149, 137, 93, 54, 96, + 73, 54, 112, 69, 133, 43, 120, 146, 125, 26, 22, 20, 198, 84, 251, + 68, 91, 26, 56, 33, 146, 3, 235, 4, 157, 232, 248}}, + {3, 11, 3, 4, 4U, {95, 89, 153, 141, 90, 108, 167, 156, 55, 149, 155, 142, + 139, 168, 72, 79, 104, 57, 138, 140, 85, 103, 166, 74, + 120, 145, 152, 169, 179, 136, 98, 177, 82, 140, 143, 75}}, + {10, 16, 3, 5, 5U, {150, 141, 121, 101, 122, 111, 115, 164, 86, 135, 123, 99, 130, 103, 115, + 135, 114, 98, 121, 83, 105, 140, 115, 124, 144, 125, 134, 107, 120, 132, + 145, 105, 120, 143, 94, 110, 138, 88, 100, 120, 139, 157, 88, 145, 149}}, + {20, 10, 5, 9, 6U, {175, 134, 104, 134, 121, 139, 140, 120, 153, 145, 111, 139, 141, 99, 102, + 132, 117, 111, 142, 119, 121, 110, 166, 135, 158, 116, 124, 163, 140, 93, + 84, 111, 172, 100, 116, 182, 140, 114, 145, 107, 138, 165, 119, 149, 150, + 131, 161, 146, 97, 135, 148, 81, 175, 148, 129, 79, 113, 93, 134, 115, + 107, 162, 125, 82, 132, 95, 126, 129, 113, 127, 127, 160, 143, 122, 161, + 173, 109, 98, 83, 85, 124, 130, 136, 171, 117, 126, 139, 126, 178, 110, + 131, 119, 93, 150, 113, 138, 188, 148, 152, 121, 141, 160, 91, 112, 134, + 96, 103, 66, 125, 125, 191, 174, 140, 153, 123, 172, 141, 135, 121, 143, + 143, 127, 156, 126, 115, 123, 146, 120, 136, 97, 129, 90, 124, 149, 90}}, + {4, 4, 4, 4, 7U, {108, 78, 116, 146, 19, 37, 34, 46, 49, 161, 205, 19, + 190, 18, 237, 66, 105, 102, 206, 36, 252, 35, 215, 218, + 141, 32, 151, 97, 106, 6, 149, 110, 194, 138, 212, 3, + 19, 104, 40, 212, 87, 30, 60, 93, 238, 110, 94, 192}}, +}; + +inline constexpr int kProcessorSize[4] = {9, 5, 4, 3}; +inline constexpr std::uint32_t kProcessorSeed = 11U; +inline const std::vector kProcessorGolden = { + -0x1.7171700000000p-4F, 0x1.bdbdc00000000p-2F, -0x1.e5e5e40000000p-2F, -0x1.2d2d2c0000000p-2F, + -0x1.4141400000000p-6F, 0x1.4141800000000p-6F, -0x1.f9f9f80000000p-3F, -0x1.1111100000000p-4F, + 0x1.7171800000000p-4F, 0x1.a9a9b00000000p-3F, 0x1.f5f5f80000000p-2F, -0x1.c1c1c00000000p-6F, + 0x1.b9b9c00000000p-3F, 0x1.8989900000000p-3F, -0x1.c5c5c40000000p-2F, -0x1.4141400000000p-6F, + 0x1.8182000000000p-7F, -0x1.a1a1a00000000p-5F, 0x1.0102000000000p-8F, 0x1.f9fa000000000p-3F, + 0x1.9191a00000000p-4F, -0x1.8181800000000p-7F, -0x1.3939380000000p-3F, -0x1.5555540000000p-2F, + -0x1.1d1d1c0000000p-2F, -0x1.9595940000000p-2F, 0x1.4d4d500000000p-2F, -0x1.5d5d5c0000000p-2F, + -0x1.2525240000000p-2F, 0x1.4141800000000p-6F, 0x1.8989900000000p-3F, 0x1.d1d1e00000000p-4F, + -0x1.7171700000000p-4F, 0x1.9191a00000000p-4F, 0x1.e1e2000000000p-5F, 0x1.1111200000000p-4F}; + +inline constexpr int kBicubicSourceSize[2] = {5, 4}; +inline const std::vector kBicubicSource = { + 0x1.3d9aae0000000p+2F, 0x1.eba9760000000p+2F, 0x1.c501240000000p-1F, 0x1.51ff800000000p+0F, + 0x1.8980500000000p+1F, 0x1.95cf740000000p+2F, 0x1.39a8e80000000p+2F, 0x1.1edcc00000000p+3F, + 0x1.239a160000000p+2F, 0x1.94ad100000000p+2F, 0x1.be95680000000p+1F, 0x1.01195c0000000p+2F, + 0x1.c93b400000000p-3F, 0x1.b047660000000p+0F, 0x1.782d5e0000000p+1F, 0x1.4bda9c0000000p+2F, + 0x1.be81dc0000000p+2F, 0x1.0000f00000000p+3F, 0x1.9c3c440000000p+0F, 0x1.694dc40000000p+1F}; + +inline const BicubicGolden kBicubicGoldens[] = { + {7, 3, {0x1.67b95e0000000p+2F, 0x1.1a90f60000000p+2F, 0x1.24b98a0000000p-1F, + 0x1.0ecf5a0000000p+2F, 0x1.4a4d100000000p+2F, 0x1.72e39e0000000p+2F, + 0x1.f293200000000p+1F, 0x1.6939e20000000p+2F, 0x1.fb22ac0000000p+2F, + 0x1.36faac0000000p+2F, 0x1.416a4a0000000p+2F, 0x1.f2324c0000000p+1F, + 0x1.caa3cc0000000p-1F, 0x1.5626dc0000000p+1F, 0x1.2bc7700000000p+2F, + 0x1.679aa40000000p+1F, 0x1.82490c0000000p+1F, 0x1.0038940000000p+2F, + 0x1.f161340000000p+2F, 0x1.3f3b1c0000000p+2F, 0x1.2d2fd60000000p+1F}}, + {2, + 9, + {0x1.7e57be0000000p+1F, 0x1.ee768c0000000p+1F, 0x1.6b7d7c0000000p+2F, 0x1.a9af3a0000000p+2F, + 0x1.5749800000000p+2F, 0x1.07dcf00000000p+2F, 0x1.4e62fe0000000p+2F, 0x1.cc4b660000000p+2F, + 0x1.04b5420000000p+3F, 0x1.26c4320000000p+0F, 0x1.7d12c00000000p+0F, 0x1.112ec00000000p+1F, + 0x1.560ec00000000p+1F, 0x1.4318d20000000p+1F, 0x1.4071240000000p+1F, 0x1.b2ff3e0000000p+1F, + 0x1.1d47ca0000000p+2F, 0x1.40bc3e0000000p+2F}}, + {5, + 4, + {0x1.3d9aae0000000p+2F, 0x1.eba9760000000p+2F, 0x1.c501240000000p-1F, 0x1.51ff800000000p+0F, + 0x1.8980500000000p+1F, 0x1.95cf740000000p+2F, 0x1.39a8e80000000p+2F, 0x1.1edcc00000000p+3F, + 0x1.239a160000000p+2F, 0x1.94ad100000000p+2F, 0x1.be95680000000p+1F, 0x1.01195c0000000p+2F, + 0x1.c93b400000000p-3F, 0x1.b047660000000p+0F, 0x1.782d5e0000000p+1F, 0x1.4bda9c0000000p+2F, + 0x1.be81dc0000000p+2F, 0x1.0000f00000000p+3F, 0x1.9c3c440000000p+0F, 0x1.694dc40000000p+1F}}, + {11, + 13, + {0x1.37c7f40000000p+2F, 0x1.4623660000000p+2F, 0x1.8769ac0000000p+2F, 0x1.e05fd40000000p+2F, + 0x1.024f300000000p+3F, 0x1.b5659e0000000p+2F, 0x1.1896a20000000p+2F, 0x1.bf8a5c0000000p+0F, + -0x1.7232540000000p-5F, -0x1.3e838a0000000p-2F, 0x1.84524a0000000p-3F, 0x1.fa4d560000000p-2F, + 0x1.fe04420000000p-2F, 0x1.146af60000000p+2F, 0x1.23b9ae0000000p+2F, 0x1.6460ee0000000p+2F, + 0x1.bb087c0000000p+2F, 0x1.e663c20000000p+2F, 0x1.adcfb00000000p+2F, 0x1.2b243e0000000p+2F, + 0x1.40fcf00000000p+1F, 0x1.4045c80000000p+0F, 0x1.5ed0280000000p+0F, 0x1.105cee0000000p+1F, + 0x1.54475c0000000p+1F, 0x1.5ff22e0000000p+1F, 0x1.9a92980000000p+1F, 0x1.bd90140000000p+1F, + 0x1.1f795c0000000p+2F, 0x1.7341100000000p+2F, 0x1.ad95240000000p+2F, 0x1.a0cc9a0000000p+2F, + 0x1.4f50800000000p+2F, 0x1.fb34820000000p+1F, 0x1.e0476e0000000p+1F, 0x1.29734c0000000p+2F, + 0x1.7c248e0000000p+2F, 0x1.bbf5f60000000p+2F, 0x1.cd2f8e0000000p+2F, 0x1.5fc0e00000000p+1F, + 0x1.8229880000000p+1F, 0x1.f813880000000p+1F, 0x1.46b25e0000000p+2F, 0x1.84805a0000000p+2F, + 0x1.9267140000000p+2F, 0x1.6541760000000p+2F, 0x1.3bc88e0000000p+2F, 0x1.54aaee0000000p+2F, + 0x1.a2ecbe0000000p+2F, 0x1.ff2a8a0000000p+2F, 0x1.2421540000000p+3F, 0x1.2ee9f80000000p+3F, + 0x1.f21ce60000000p+1F, 0x1.06a3760000000p+2F, 0x1.3829560000000p+2F, 0x1.780aa60000000p+2F, + 0x1.a5fdfe0000000p+2F, 0x1.a08fa60000000p+2F, 0x1.6832f20000000p+2F, 0x1.2e9d1c0000000p+2F, + 0x1.25868a0000000p+2F, 0x1.4dffa60000000p+2F, 0x1.88064e0000000p+2F, 0x1.b4d72a0000000p+2F, + 0x1.c0f8400000000p+2F, 0x1.170d460000000p+2F, 0x1.2096140000000p+2F, 0x1.46af160000000p+2F, + 0x1.790e120000000p+2F, 0x1.9621c20000000p+2F, 0x1.8002c60000000p+2F, 0x1.416a480000000p+2F, + 0x1.fa61de0000000p+1F, 0x1.ac7dc20000000p+1F, 0x1.b43dfe0000000p+1F, 0x1.e31e0a0000000p+1F, + 0x1.02002c0000000p+2F, 0x1.04d9ec0000000p+2F, 0x1.02dada0000000p+1F, 0x1.1339760000000p+1F, + 0x1.4ac9260000000p+1F, 0x1.90ef400000000p+1F, 0x1.cc400e0000000p+1F, 0x1.df28b60000000p+1F, + 0x1.c0a3b20000000p+1F, 0x1.9dae700000000p+1F, 0x1.a352780000000p+1F, 0x1.cac38a0000000p+1F, + 0x1.fbac340000000p+1F, 0x1.1113fc0000000p+2F, 0x1.16a09a0000000p+2F, 0x1.39c7ce0000000p-8F, + 0x1.0d8adc0000000p-3F, 0x1.f3c9e60000000p-2F, 0x1.d151f20000000p-1F, 0x1.7060460000000p+0F, + 0x1.fff5be0000000p+0F, 0x1.26630c0000000p+1F, 0x1.52bba80000000p+1F, 0x1.ac46fa0000000p+1F, + 0x1.055d1a0000000p+2F, 0x1.2e80660000000p+2F, 0x1.50bd820000000p+2F, 0x1.5c621a0000000p+2F, + 0x1.f3ba500000000p+0F, 0x1.07a9280000000p+1F, 0x1.3939d20000000p+1F, 0x1.78e32c0000000p+1F, + 0x1.a845660000000p+1F, 0x1.a47a1a0000000p+1F, 0x1.68deb40000000p+1F, 0x1.3484540000000p+1F, + 0x1.4667ba0000000p+1F, 0x1.9644a60000000p+1F, 0x1.f8a3fa0000000p+1F, 0x1.230eaa0000000p+2F, + 0x1.2e43340000000p+2F, 0x1.6ccd8a0000000p+2F, 0x1.72ab840000000p+2F, 0x1.92a4a80000000p+2F, + 0x1.bfc8fa0000000p+2F, 0x1.c98ad20000000p+2F, 0x1.87ad1e0000000p+2F, 0x1.1502200000000p+2F, + 0x1.479f200000000p+1F, 0x1.995bfa0000000p+0F, 0x1.dab9360000000p+0F, 0x1.55b7a20000000p+1F, + 0x1.a0fa6a0000000p+1F, 0x1.b034500000000p+1F, 0x1.e6569e0000000p+2F, 0x1.eb9a720000000p+2F, + 0x1.0781480000000p+3F, 0x1.2153de0000000p+3F, 0x1.2280cc0000000p+3F, 0x1.e239b20000000p+2F, + 0x1.4408e60000000p+2F, 0x1.4cd2d20000000p+1F, 0x1.154f4a0000000p+0F, 0x1.28e1720000000p+0F, + 0x1.0129aa0000000p+1F, 0x1.4c58040000000p+1F, 0x1.5838be0000000p+1F}}, +}; + +} // namespace dpt_goldens diff --git a/families/dpt/tests/cpp/test_image_ops.cpp b/families/dpt/tests/cpp/test_image_ops.cpp new file mode 100644 index 0000000000..a2eca1d431 --- /dev/null +++ b/families/dpt/tests/cpp/test_image_ops.cpp @@ -0,0 +1,165 @@ +/* + * SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. + * SPDX-License-Identifier: Apache-2.0 + */ + +#include "families/dpt/runtime/image_ops.h" +#include "families/dpt/tests/cpp/image_ops_goldens.h" + +#include +#include +#include +#include +#include +#include +#include +#include + +namespace { + +int failures = 0; + +void check(bool condition, const char* what) { + if (!condition) { + std::fprintf(stderr, "FAIL: %s\n", what); + ++failures; + } +} + +// The recurrence of generate_image_ops_goldens.py. +std::vector lcg_image(int height, int width, std::uint32_t seed) { + std::vector values(static_cast(height) * width * 3U); + std::uint32_t state = seed; + for (auto& value : values) { + state = (state * 1103515245U + 12345U) & 0x7FFFFFFFU; + value = static_cast((state >> 16) & 0xFFU); + } + return values; +} + +// What the CLI hands a family: 8-bit samples divided by 255. +std::vector to_unit(const std::vector& bytes) { + std::vector pixels(bytes.size()); + for (std::size_t index = 0; index < bytes.size(); ++index) + pixels[index] = static_cast(bytes[index]) / 255.0F; + return pixels; +} + +template +bool throws_invalid_argument(Function function) { + try { + function(); + } catch (const std::invalid_argument&) { + return true; + } + return false; +} + +void test_bilinear_resize_matches_pillow() { + for (const auto& golden : dpt_goldens::kResizeGoldens) { + const auto source = lcg_image(golden.height, golden.width, golden.seed); + const auto resized = trtmc::dpt::resize_bilinear_rgb8( + source.data(), golden.height, golden.width, golden.out_height, golden.out_width); + check(resized == golden.expected, "8-bit bilinear resize is byte-identical to Pillow"); + } +} + +void test_rgb8_recovers_every_level_and_clamps() { + std::vector levels(256U * 3U); + for (std::size_t level = 0; level < 256U; ++level) { + for (std::size_t channel = 0; channel < 3U; ++channel) + levels[level * 3U + channel] = static_cast(level) / 255.0F; + } + const auto rgb = trtmc::dpt::to_rgb8(levels.data(), 16, 16); + bool exact = true; + for (std::size_t index = 0; index < rgb.size(); ++index) + exact = exact && rgb[index] == index / 3U; + check(exact, "every 8-bit level survives the round trip through value / 255"); + + const float outside[3] = {-0.25F, 1.5F, 0.5F}; + const auto clamped = trtmc::dpt::to_rgb8(outside, 1, 1); + check(clamped[0] == 0 && clamped[1] == 255 && clamped[2] == 128, + "values outside [0, 1] clamp to the 8-bit range"); + + const float invalid[3] = {0.5F, std::numeric_limits::quiet_NaN(), 0.5F}; + check(throws_invalid_argument([&] { trtmc::dpt::to_rgb8(invalid, 1, 1); }), + "a non-finite pixel is rejected"); +} + +void test_preprocessing_matches_the_image_processor() { + const auto& size = dpt_goldens::kProcessorSize; + const auto source = to_unit(lcg_image(size[0], size[1], dpt_goldens::kProcessorSeed)); + trtmc::dpt::PreprocessConfig config; + config.input_image_h = size[2]; + config.input_image_w = size[3]; + config.rescale_factor = 0.00392156862745098; + const auto pixel_values = trtmc::dpt::preprocess_image(source.data(), size[0], size[1], config); + check(pixel_values.size() == dpt_goldens::kProcessorGolden.size() && + std::memcmp(pixel_values.data(), dpt_goldens::kProcessorGolden.data(), + pixel_values.size() * sizeof(float)) == 0, + "resize, rescale and normalize match DPTImageProcessor bit for bit"); +} + +void test_bicubic_resize_matches_torch() { + const auto& size = dpt_goldens::kBicubicSourceSize; + float range = 0.0F; + for (const float value : dpt_goldens::kBicubicSource) + range = std::fmax(range, std::fabs(value)); + // torch's CPU kernel fuses some multiply-adds, as its compiler chooses; this + // one evaluates the same formula unfused. Sixteen taps whose weights sum to + // at most 1.6 in magnitude stay within 32 float32 epsilons of the range. + const float tolerance = 32.0F * std::numeric_limits::epsilon() * range; + for (const auto& golden : dpt_goldens::kBicubicGoldens) { + const auto resized = trtmc::dpt::resize_bicubic(dpt_goldens::kBicubicSource.data(), size[0], + size[1], golden.height, golden.width); + bool close = resized.size() == golden.expected.size(); + for (std::size_t index = 0; close && index < resized.size(); ++index) + close = std::fabs(resized[index] - golden.expected[index]) <= tolerance; + check(close, "bicubic resize matches torch interpolate(align_corners=False)"); + } + const auto same = trtmc::dpt::resize_bicubic(dpt_goldens::kBicubicSource.data(), size[0], + size[1], size[0], size[1]); + check(same == dpt_goldens::kBicubicSource, "a same-size bicubic resize is the identity"); +} + +void test_rejects_bad_input() { + const std::uint8_t byte = 0; + const float value = 0.0F; + trtmc::dpt::PreprocessConfig config; + check(throws_invalid_argument([&] { trtmc::dpt::to_rgb8(nullptr, 1, 1); }), + "a null image is rejected"); + check(throws_invalid_argument([&] { trtmc::dpt::to_rgb8(&value, 0, 1); }), + "an empty image is rejected"); + check(throws_invalid_argument([&] { trtmc::dpt::resize_bilinear_rgb8(&byte, 1, 1, 0, 1); }), + "an empty resize target is rejected"); + check(throws_invalid_argument([&] { trtmc::dpt::resize_bicubic(nullptr, 1, 1, 1, 1); }), + "a null depth map is rejected"); + config.image_std = {0.5F, 0.0F, 0.5F}; + const float pixel[3] = {0.5F, 0.5F, 0.5F}; + check(throws_invalid_argument([&] { trtmc::dpt::preprocess_image(pixel, 1, 1, config); }), + "a zero standard deviation is rejected"); + // Finite and non-zero, but 0.5 / 1e-40 overflows float32. + config.image_std = {0.5F, 1e-40F, 0.5F}; + check(throws_invalid_argument([&] { trtmc::dpt::preprocess_image(pixel, 1, 1, config); }), + "a standard deviation that normalizes a sample to infinity is rejected"); + config.image_std = {0.5F, 0.5F, 0.5F}; + config.rescale_factor = 1e308; + check(throws_invalid_argument([&] { trtmc::dpt::preprocess_image(pixel, 1, 1, config); }), + "a rescale factor that takes 255 past float32 is rejected"); +} + +} // namespace + +int main() { + test_bilinear_resize_matches_pillow(); + test_rgb8_recovers_every_level_and_clamps(); + test_preprocessing_matches_the_image_processor(); + test_bicubic_resize_matches_torch(); + test_rejects_bad_input(); + if (failures != 0) { + std::fprintf(stderr, "%d dpt image check(s) failed\n", failures); + return EXIT_FAILURE; + } + std::printf("dpt image checks passed\n"); + return EXIT_SUCCESS; +} diff --git a/families/dpt/tests/cpp/test_pipeline.cpp b/families/dpt/tests/cpp/test_pipeline.cpp new file mode 100644 index 0000000000..d677c10250 --- /dev/null +++ b/families/dpt/tests/cpp/test_pipeline.cpp @@ -0,0 +1,278 @@ +/* + * SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. + * SPDX-License-Identifier: Apache-2.0 + */ + +#include "families/dpt/runtime/pipeline.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace { + +int failures = 0; + +void check(bool condition, const std::string& what) { + if (!condition) { + std::fprintf(stderr, "FAIL: %s\n", what.c_str()); + ++failures; + } +} + +template +bool throws_runtime_error(Function function) { + try { + function(); + } catch (const std::runtime_error&) { + return true; + } + return false; +} + +constexpr std::int64_t kSide = 384; + +// An engine double that reports configurable I/O and returns a configurable +// depth map, and checks what the pipeline hands it. +class FakeEngine final : public trtmc::ITrtModule { + public: + trtmc::TensorMap forward(const trtmc::TensorMap& inputs) override { + ++calls; + const auto found = inputs.find("pixel_values"); + input_ok = inputs.size() == 1U && found != inputs.end() && found->second.data != nullptr && + found->second.dtype == trtmc::DType::kFloat32 && + found->second.shape == std::vector{1, 3, kSide, kSide}; + return {{output_name, {depth.data(), output_shape, output_dtype}}}; + } + trtmc::DeviceTensorMap forward_device(const trtmc::DeviceTensorMap&) override { return {}; } + void forward_device_async(const trtmc::DeviceTensorMap&) override {} + void forward_async(const trtmc::TensorMap&) override {} + void sync() override {} + cudaStream_t stream() const override { return nullptr; } + void enable_cuda_graph() override {} + bool cuda_graph_active() const override { return false; } + bool cuda_graph_captured() const override { return false; } + int32_t profile_idx() const override { return 0; } + std::vector input_info() const override { return inputs; } + std::vector output_info() const override { return outputs; } + bool has_input(const std::string&) const override { return false; } + bool has_output(const std::string&) const override { return false; } + trtmc::DType tensor_dtype(const std::string&) const override { return trtmc::DType::kFloat32; } + std::vector tensor_shape(const std::string&) const override { return {}; } + std::vector input_profile_shape(const std::string&, int32_t, + trtmc::ProfileShapeSelector) const override { + return {}; + } + int32_t optimization_profile_count() const override { return 1; } + void* device_ptr(const std::string&) const override { return nullptr; } + void bind_external(const std::string&, void*) override {} + void bind_external(const std::string&, void*, const std::vector&) override {} + int32_t input_rank(const std::string&) const override { return 4; } + bool input_is_dynamic(const std::string&) const override { return false; } + void reset_execution_context() override {} + void set_timing_label(std::string) override {} + bool ok() const override { return healthy; } + void keep_alive(std::shared_ptr) override {} + + std::vector inputs{ + {"pixel_values", {1, 3, kSide, kSide}, trtmc::DType::kFloat32, true}}; + std::vector outputs{ + {"predicted_depth", {1, 1, kSide, kSide}, trtmc::DType::kFloat32, false}}; + bool healthy{true}; + std::string output_name{"predicted_depth"}; + std::vector output_shape{1, 1, kSide, kSide}; + trtmc::DType output_dtype{trtmc::DType::kFloat32}; + std::vector depth = std::vector(static_cast(kSide * kSide), 2.0F); + int calls{0}; + bool input_ok{false}; +}; + +const std::map kHealthyRuntime = { + {"input_image_h", "384"}, + {"input_image_w", "384"}, + {"rescale_factor", "0.00392156862745098"}, + {"image_mean", "[0.5, 0.5, 0.5]"}, + {"image_std", "[0.5, 0.5, 0.5]"}, +}; + +std::string runtime_json(const std::map& values, + const std::string& extra = "") { + std::string text = "{"; + for (const auto& [key, value] : values) + text += (text.size() > 1 ? ", \"" : "\"") + key + "\": " + value; + return text + extra + "}"; +} + +std::string with(const char* key, const char* value) { + auto values = kHealthyRuntime; + values[key] = value; + return runtime_json(values); +} + +std::string without(const char* key) { + auto values = kHealthyRuntime; + values.erase(key); + return runtime_json(values); +} + +trtmc::dpt::PreprocessConfig healthy_config() { + return trtmc::dpt::parse_runtime_config(runtime_json(kHealthyRuntime)); +} + +void test_runtime_json_is_read_exactly() { + const auto config = healthy_config(); + check(config.input_image_h == 384 && config.input_image_w == 384 && + config.rescale_factor == 0.00392156862745098 && config.image_mean[1] == 0.5F && + config.image_std[2] == 0.5F, + "the build's runtime.json is read as written"); + + const std::vector> refused = { + {"an integer written as a float", with("input_image_h", "384.0")}, + {"a boolean for an integer", with("input_image_w", "true")}, + {"a negative size", with("input_image_h", "-384")}, + {"a zero size", with("input_image_w", "0")}, + {"a size that wraps to 384 in int32", with("input_image_h", "4294967680")}, + {"a size past int64", with("input_image_w", "18446744073709551615")}, + {"a number written as a string", with("rescale_factor", "\"0.00392156862745098\"")}, + {"an explicit null", with("rescale_factor", "null")}, + {"a zero rescale factor", with("rescale_factor", "0")}, + {"a negative rescale factor", with("rescale_factor", "-0.0039")}, + {"a rescale factor that overflows float32", with("rescale_factor", "1e308")}, + {"two means", with("image_mean", "[0.5, 0.5]")}, + {"a mean past float32", with("image_mean", "[0.5, 0.5, 1e39]")}, + {"a zero std", with("image_std", "[0.5, 0, 0.5]")}, + {"a std that rounds to zero in float32", with("image_std", "[0.5, 1e-50, 0.5]")}, + {"a std that normalizes a sample to infinity", with("image_std", "[0.5, 1e-40, 0.5]")}, + {"a std given as one number", with("image_std", "0.5")}, + {"a missing key", without("image_std")}, + {"an unknown key", runtime_json(kHealthyRuntime, ", \"resample\": 2")}, + {"a repeated key", runtime_json(kHealthyRuntime, ", \"input_image_h\": 512")}, + {"an array instead of an object", "[384, 384]"}, + {"truncated JSON", "{\"input_image_h\": 384"}, + }; + for (const auto& [what, text] : refused) { + check(throws_runtime_error([&] { trtmc::dpt::parse_runtime_config(text); }), + "runtime.json with " + what + " is refused"); + } +} + +std::unique_ptr healthy_engine() { + return std::make_unique(); +} + +bool refused_at_load(std::unique_ptr engine, + trtmc::dpt::PreprocessConfig config = healthy_config()) { + return throws_runtime_error( + [&] { trtmc::dpt::DptPipeline pipeline(std::move(engine), config); }); +} + +void test_engine_io_is_checked_at_load() { + check(!refused_at_load(healthy_engine()), "an engine of the runtime contract loads"); + + auto engine = healthy_engine(); + engine->inputs[0].name = "image"; + check(refused_at_load(std::move(engine)), "an engine input of another name is refused"); + engine = healthy_engine(); + engine->inputs[0].dtype = trtmc::DType::kFloat16; + check(refused_at_load(std::move(engine)), "an fp16 engine input is refused"); + engine = healthy_engine(); + engine->inputs[0].shape = {1, 3, kSide, kSide - 1}; + check(refused_at_load(std::move(engine)), "an engine input of another size is refused"); + engine = healthy_engine(); + engine->inputs[0].shape = {-1, 3, kSide, kSide}; + check(refused_at_load(std::move(engine)), "a dynamic engine input is refused"); + engine = healthy_engine(); + engine->inputs.push_back(engine->inputs[0]); + engine->inputs[1].name = "mask"; + check(refused_at_load(std::move(engine)), "an engine with a second input is refused"); + + engine = healthy_engine(); + engine->outputs[0].name = "depth"; + check(refused_at_load(std::move(engine)), "an engine output of another name is refused"); + engine = healthy_engine(); + engine->outputs[0].dtype = trtmc::DType::kFloat16; + check(refused_at_load(std::move(engine)), "an fp16 engine output is refused"); + engine = healthy_engine(); + engine->outputs[0].shape = {1, kSide, kSide}; + check(refused_at_load(std::move(engine)), "an engine output of another rank is refused"); + engine = healthy_engine(); + engine->outputs.clear(); + check(refused_at_load(std::move(engine)), "an engine without an output is refused"); + + engine = healthy_engine(); + engine->healthy = false; + check(refused_at_load(std::move(engine)), "an engine that failed to load is refused"); + auto config = healthy_config(); + config.input_image_w = 512; + check(refused_at_load(healthy_engine(), config), + "an engine whose size differs from runtime.json is refused"); + config = healthy_config(); + config.image_std = {0.5F, 0.0F, 0.5F}; + check(refused_at_load(healthy_engine(), config), + "a configuration the image operations refuse is refused at load"); +} + +std::vector grey_image(std::int32_t height, std::int32_t width) { + return std::vector(static_cast(height) * width * 3U, 0.5F); +} + +void test_depth_is_checked_before_and_after_the_resize() { + constexpr std::int32_t kHeight = 4; + constexpr std::int32_t kWidth = 6; + const auto image = grey_image(kHeight, kWidth); + + auto engine = healthy_engine(); + auto* fake = engine.get(); + trtmc::dpt::DptPipeline pipeline(std::move(engine), healthy_config()); + const auto result = pipeline.estimate_depth(image.data(), kHeight, kWidth); + bool constant = result.depth.size() == static_cast(kHeight * kWidth); + for (const float value : result.depth) + constant = constant && std::fabs(value - 2.0F) <= 1e-5F; + check(fake->calls == 1 && fake->input_ok, "the engine gets one float32 [1, 3, 384, 384] input"); + check(result.height == kHeight && result.width == kWidth && constant, + "a constant depth map resizes to a constant map of the image's size"); + + fake->depth[1000] = std::numeric_limits::quiet_NaN(); + check(throws_runtime_error([&] { pipeline.estimate_depth(image.data(), kHeight, kWidth); }), + "a NaN from the engine is refused before the resize"); + fake->depth[1000] = std::numeric_limits::infinity(); + check(throws_runtime_error([&] { pipeline.estimate_depth(image.data(), kHeight, kWidth); }), + "an infinity from the engine is refused before the resize"); + + // The bicubic taps of a 384 -> 4 resize are -0.09375, 0.59375, 0.59375 and + // -0.09375: their running sum passes 1 and overflows a map of FLT_MAX. + fake->depth.assign(fake->depth.size(), std::numeric_limits::max()); + check(throws_runtime_error([&] { pipeline.estimate_depth(image.data(), kHeight, kWidth); }), + "a finite engine map that overflows in the resize is refused"); + + fake->depth.assign(fake->depth.size(), 2.0F); + fake->output_shape = {1, kSide, kSide}; + check(throws_runtime_error([&] { pipeline.estimate_depth(image.data(), kHeight, kWidth); }), + "an engine output of another shape is refused at run time"); + fake->output_shape = {1, 1, kSide, kSide}; + fake->output_name = "depth"; + check(throws_runtime_error([&] { pipeline.estimate_depth(image.data(), kHeight, kWidth); }), + "a missing engine output is refused at run time"); +} + +} // namespace + +int main() { + test_runtime_json_is_read_exactly(); + test_engine_io_is_checked_at_load(); + test_depth_is_checked_before_and_after_the_resize(); + if (failures != 0) { + std::fprintf(stderr, "%d dpt pipeline check(s) failed\n", failures); + return EXIT_FAILURE; + } + std::printf("dpt pipeline checks passed\n"); + return EXIT_SUCCESS; +} diff --git a/families/dpt/tests/data/test_img.jpeg b/families/dpt/tests/data/test_img.jpeg new file mode 100644 index 0000000000000000000000000000000000000000..095c03620f4efba781e30520da7f1462b08a6a30 GIT binary patch literal 55258 zcmb4KQ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i`W|~_Mvvj7S!Y1yoz*3FI+`=$7~7F2 z8)GCBup*y(p#`yt+F2C{4p@wt80^E-Ad}1WG^OtZJWq)5xgl5~j@QQei!(B|%A;|N zY0gGBG~)NMHPIODVvJkOJS7;cf?fOB9Ax0*$ODXLbDniw6|54+9+TZXb82ux>4boB zgOimiS0|~?Hl{8uB!E1{^(c&?R$|8hWN)`px%0t3gc4sQ*22nUXD=Uk#9?qUazPvF zILAScI<n$G*YzXk1gVt8Rwo(pP8|HI$zLj_2@@a8E70{(7ay4Z7jiO>cVykW7wsD-03K zKgPQxcG6th0U21{-3w&ohlR+-agP@+TMV{2&@Q-qcRVvZK|?~a2vL^|<-&E;FcS&L zZaNz1Sz7GL!9I>SV+_RP4-N^_w=Q2jsd*KM8t_8&71a3G+1lHdJUVp|t-457Voq|o z8{==*x&6hLbu8%Q9_`Ap9Y{acw}jNTjNE9cc=pLWs7D}UBYn+TG+-m({s2xXPVZiH z;2))Goscf-e=){0Lo1!YJol#A4wB4r2O*k)+-GgDF-!nx+~=9Bl<@DrmT0;L8~_Nw z$vo>JFsxVtb3g!8+;5M1z)`E0UGh0m)pAaqur}Vj$?9@>PykvbDi4{g2v-CFzh1P$ zra@D-S0~pM?HZ1Hf&3@|Uh8gI^XrPobGZ6bYKyBF=6TjisuT~M`C@t67M*Mrlo830|e zk`BP`1pp7b*c@Py^{J}h0girjMrLg!om*sT-vY2e103_6IUKP-5eiPsGJOyCnwE{S zhks6WGNDFx<+jz8j9>yuEz8R^0TK^V30`?MG*hG(85(hwJdH<6t2TW1#TQPkEzc(d zBdq`oC?^c0 None: + if not condition: + raise ValueError(f"{path.name}: {message}") + + +def _check_manifest(path: Path, manifest: dict) -> None: + """Every field the test reads, with its JSON type and range.""" + for key in ("name", "hf_id", "hf_revision", "bundle"): + _require(isinstance(manifest.get(key), str) and bool(manifest[key]), path, + f"{key} must be a non-empty string") + _require(manifest.get("family") == FAMILY, path, f"family must be {FAMILY!r}") + _require(manifest.get("task") in TASKS, path, f"task must be one of {sorted(TASKS)}") + _require(manifest.get("precision") in PRECISIONS, path, + f"precision must be one of {sorted(PRECISIONS)}") + _require(manifest.get("trust_remote_code") is False, path, "trust_remote_code must be false") + for key in ("tensor_parallel_size", "max_sequence_length"): + value = manifest.get(key) + _require(type(value) is int and value == 1, path, f"{key} must be the integer 1") + _require(isinstance(manifest.get("testcases"), list) and bool(manifest["testcases"]), path, + "testcases must be a non-empty list") + for case in manifest["testcases"]: + _require(isinstance(case, dict) and isinstance(case.get("name"), str) and bool(case["name"]), + path, "every testcase needs a non-empty string name") + for key in ("premerge", "transpose"): + _require(isinstance(case.get(key), bool), path, f"{case['name']} {key} must be a boolean") + image = case.get("test_image") + _require(isinstance(image, str) and Path(image).name == image and image not in ("", ".", ".."), + path, f"{case['name']} test_image must name a file in tests/data") + for key in THRESHOLDS: + value = case.get(key) + _require(type(value) in (int, float) and math.isfinite(value) and 0.0 < value <= 1.0, + path, f"{case['name']} {key} must be a number in (0, 1]; got {value!r}") + + +def _case_index() -> dict[str, tuple[Path, dict, dict]]: + result = {} + for path in sorted(MANIFEST_ROOT.glob("*.json")): + manifest = json.loads(path.read_text(encoding="utf-8")) + _require(isinstance(manifest, dict), path, "must hold a JSON object") + _check_manifest(path, manifest) + for case in manifest["testcases"]: + name = case["name"] + _require(name not in result and name != ELSEWHERE, path, + f"testcase {name} is declared twice or reserved") + result[name] = (path, manifest, case) + return result + + +CASES = _case_index() + + +def _filters(config, option: str) -> set[str]: + return {item.strip() for raw in config.getoption(option) or [] for item in str(raw).split(",") + if item.strip()} + + +def _collects_only_this_family(config) -> bool: + """Whether every path the session was given lies in this family (pytest families/dpt/...).""" + args = [str(arg).split("::")[0] for arg in getattr(config, "args", None) or []] + base = Path(getattr(getattr(config, "invocation_params", None), "dir", None) or Path.cwd()) + family_root = TEST_ROOT.parent + return bool(args) and all((base / arg).resolve().is_relative_to(family_root) for arg in args) + + +def _selected_cases(config) -> tuple[list[str], bool]: + """The selected cases, and whether any E2E selector was given. + + A selector is this family's when it is one of its names (the family, a + manifest, a case) or extends a manifest name, so that a misspelled case such + as ``dpt-hybrid-midas-landscap`` is caught in any session. Every case or + manifest selector of this family must then run. When the selection is this + family's alone (every model selector is its own, or the session collects only + its files), every selector must run. A selection of another family leaves this + file empty, so pytest skips it. + """ + model_filters = _filters(config, "--e2e-model") + models_file = config.getoption("--e2e-models-file") + if models_file: + model_filters.update( + line.strip() + for line in Path(models_file).read_text(encoding="utf-8").splitlines() + if line.strip() and not line.lstrip().startswith("#") + ) + testcase_filters = _filters(config, "--e2e-testcase") + if not model_filters and not testcase_filters: + return sorted(CASES), False + selected = [] + for name, (_, manifest, _) in CASES.items(): + model_match = not model_filters or bool({FAMILY, manifest["name"], name} & model_filters) + testcase_match = not testcase_filters or name in testcase_filters + if model_match and testcase_match: + selected.append(name) + manifests = {manifest["name"] for _, manifest, _ in CASES.values()} + own_names = {FAMILY} | manifests | set(CASES) + + def ours(name: str) -> bool: + return name in own_names or any(name.startswith(f"{manifest}-") for manifest in manifests) + + our_models = {name for name in model_filters if ours(name)} + our_cases = {name for name in testcase_filters if ours(name)} + if model_filters and not our_models and not our_cases: + return [], True # another family's selection + alone = (bool(model_filters) and model_filters == our_models) or _collects_only_this_family(config) + if not (our_models or our_cases or alone): + return [], True # another family's testcases + if alone: + unmatched = (testcase_filters - set(selected)) | (model_filters - own_names) + else: + unmatched = (our_cases - set(selected)) | (our_models - own_names) + if not selected or unmatched: + raise pytest.UsageError( + f"the E2E selection of {FAMILY} " + + (f"asks for what it cannot run ({', '.join(sorted(unmatched))})" if unmatched + else "matches none of its cases") + + f" (models: {', '.join(sorted(model_filters)) or 'none'}; testcases: " + f"{', '.join(sorted(testcase_filters)) or 'none'}); its cases are " + + ", ".join(sorted(CASES))) + return sorted(selected), True + + +def _require_one_checkpoint(names: list[str]) -> None: + """The model-directory override names one checkpoint; refuse it for a selection of several. + + Otherwise every selected case would build and run the override's checkpoint, + and a case of another checkpoint would pass without testing it. + """ + if not os.environ.get(MODEL_DIR_OVERRIDE): + return + checkpoints = sorted({(CASES[name][1]["hf_id"], CASES[name][1]["hf_revision"]) + for name in names}) + if len(checkpoints) > 1: + raise pytest.UsageError( + f"{MODEL_DIR_OVERRIDE} stands for one checkpoint, but the selected cases use " + f"{len(checkpoints)}: " + ", ".join(f"{hf_id}@{revision}" for hf_id, revision in checkpoints) + + "; select the cases of one checkpoint") + + +def _testcase_only(config) -> bool: + return bool(_filters(config, "--e2e-testcase")) and not _filters(config, "--e2e-model") \ + and not config.getoption("--e2e-models-file") + + +def pytest_generate_tests(metafunc) -> None: + if "case_name" in metafunc.fixturenames: + names, enabled = _selected_cases(metafunc.config) + if enabled and not names and _testcase_only(metafunc.config): + metafunc.parametrize("case_name", [ELSEWHERE], ids=[ELSEWHERE]) + return + parameters = names + if enabled: + _require_one_checkpoint(names) + else: + parameters = [ + pytest.param( + name, + marks=pytest.mark.skip( + reason="direct E2E requires one of the three explicit E2E selectors" + ), + ) + for name in names + ] + metafunc.parametrize("case_name", parameters, ids=names) + + +def _required_path(value: str | None, label: str) -> Path: + assert value, f"selected {FAMILY} E2E requires {label}" + # Absolute, so that a relative TRTMC_BINARY such as ./trtmc launches the + # checked file: Path drops the "./", and subprocess looks a bare name up on PATH. + path = Path(value).absolute() + assert path.exists(), f"selected {FAMILY} E2E {label} does not exist: {path}" + return path + + +def _model_dir(manifest: dict) -> Path: + # pytest_generate_tests refuses the override for a selection of several checkpoints. + explicit = os.environ.get(MODEL_DIR_OVERRIDE) + if explicit: + return _required_path(explicit, MODEL_DIR_OVERRIDE) + from huggingface_hub import snapshot_download + + try: + snapshot = snapshot_download( + repo_id=manifest["hf_id"], revision=manifest["hf_revision"], local_files_only=True + ) + except Exception as error: + raise AssertionError( + f"selected {FAMILY} E2E requires the exact cached checkpoint {manifest['hf_id']}" + ) from error + return Path(snapshot) + + +def _runtime() -> tuple[Path, Path]: + binary = _required_path(os.environ.get("TRTMC_BINARY"), "TRTMC_BINARY") + runtime_root = _required_path(os.environ.get("TRTMC_RUNTIME_ROOT"), "TRTMC_RUNTIME_ROOT") + assert (runtime_root / "libtrtmc_backend_trt.so").is_file() + assert (runtime_root / f"libtrtmc_model_{FAMILY}.so").is_file() + import torch + + assert torch.cuda.is_available(), f"selected {FAMILY} E2E requires CUDA" + return binary, runtime_root + + +def _asset(name: str) -> Path: + path = TEST_ROOT / "data" / str(name) + assert path.is_file(), f"selected {FAMILY} E2E asset does not exist: {path}" + return path + + +# One bundle per manifest and one reference model per checkpoint, shared by the +# cases of a session. +_BUNDLES: dict[str, Path] = {} +_REFERENCES: dict[str, tuple] = {} + + +def _bundle(model_dir: Path, manifest: dict, tmp_path_factory) -> Path: + if manifest["name"] not in _BUNDLES: + bundle = tmp_path_factory.mktemp(manifest["name"]) / manifest["bundle"] + build( + BuildRequest( + model_dir=model_dir, + output_path=bundle, + family=FAMILY, + task=manifest["task"], + precision=manifest["precision"], + tensor_parallel_size=manifest["tensor_parallel_size"], + max_sequence_length=manifest["max_sequence_length"], + ) + ) + _BUNDLES[manifest["name"]] = bundle + return _BUNDLES[manifest["name"]] + + +def _input_image(case: dict, tmp_path: Path): + """The case's image as RGB, turned to portrait when asked, and its PNG copy.""" + from PIL import Image + + with Image.open(_asset(case["test_image"])) as source: + image = source.convert("RGB") + if case["transpose"]: + image = image.transpose(Image.Transpose.ROTATE_90) + path = tmp_path / "input.png" + image.save(path) + return image, path + + +def _native(binary: Path, runtime_root: Path, bundle: Path, image_path: Path): + import numpy as np + + invocation = [str(binary), "depth", str(bundle), "--runtime-root", str(runtime_root), + "--image", str(image_path)] + env = os.environ.copy() + env["LD_LIBRARY_PATH"] = ":".join( + value for value in (str(runtime_root), env.get("LD_LIBRARY_PATH", "")) if value + ) + completed = subprocess.run( + invocation, check=True, capture_output=True, text=True, env=env, timeout=3600 + ) + record_evidence("commands", {"argv": completed.args}) + # The CLI prints its result as the last line, one JSON object. + payload = None + for line in reversed(completed.stdout.splitlines()): + if line.startswith("{"): + payload = json.loads(line) + break + assert isinstance(payload, dict), f"native {FAMILY} returned no JSON object: {completed.stdout[-1000:]}" + height, width = payload.get("height"), payload.get("width") + assert type(height) is int and type(width) is int and height > 0 and width > 0, ( + f"native {FAMILY} returned no positive integer height and width: {height!r}, {width!r}" + ) + assert isinstance(payload.get("depth"), list), f"native {FAMILY} returned no depth list" + depth = np.asarray(payload["depth"], dtype=np.float64) + assert depth.size == height * width, f"native {FAMILY} depth map does not cover the image" + return depth.reshape(height, width) + + +def _official(model_dir: Path): + import torch + from transformers import DPTForDepthEstimation, DPTImageProcessor + + key = str(model_dir) + if key not in _REFERENCES: + processor = DPTImageProcessor.from_pretrained(key) + model = DPTForDepthEstimation.from_pretrained(key, dtype=torch.float32).eval() + _REFERENCES[key] = (processor, model) + return _REFERENCES[key] + + +def _reference(model_dir: Path, image): + import numpy as np + import torch + + processor, model = _official(model_dir) + encoding = processor(images=image, return_tensors="pt") + with torch.no_grad(): + outputs = model(**encoding) + depth = processor.post_process_depth_estimation( + outputs, target_sizes=[(image.height, image.width)] + )[0]["predicted_depth"] + return depth.float().numpy().astype(np.float64) + + +def _depth_png(depth, scale: float, path: Path) -> Path: + import numpy as np + from PIL import Image + + levels = np.clip(np.asarray(depth) / scale * 255.0, 0.0, 255.0).round().astype(np.uint8) + Image.fromarray(levels).save(path) + return path + + +def _depth_metrics(native, reference) -> dict[str, float]: + """Correlation, and the largest and mean error relative to the largest reference depth.""" + import numpy as np + + assert reference.ndim == 2 and native.shape == reference.shape, ( + f"native depth map shape {native.shape} differs from the reference's {reference.shape}" + ) + assert np.isfinite(native).all(), f"native {FAMILY} depth map is not finite" + assert np.isfinite(reference).all(), "reference depth map is not finite" + scale = float(np.abs(reference).max()) + assert scale > 0.0, "reference depth map is all zero" + correlation = float(np.corrcoef(native.ravel(), reference.ravel())[0, 1]) + assert math.isfinite(correlation), "a constant depth map has no correlation" + difference = np.abs(native - reference) + return { + "scale": scale, + "correlation": correlation, + "max_error": float(difference.max() / scale), + "mean_error": float(difference.mean() / scale), + } + + +def _assert_parity(native, reference, image, case: dict, tmp_path: Path) -> None: + assert native.shape == (image.height, image.width), ( + f"depth map shape {native.shape} is not the image's {(image.height, image.width)}" + ) + metrics = _depth_metrics(native, reference) + # Bounds from the manifests (correlation / largest / mean error): fp32 0.999999 / + # 1e-4 / 1e-5, fp16 0.99999 / 0.05 / 0.002. Calibrated on 1x B300, TensorRT 11.4: + # - healthy fp32, 10 runs (6 builds; the builds are identical): > 0.9999999999996 / + # 2.8e-6 - 7.8e-6 / 2.0e-7 - 2.1e-7; healthy fp16, 8 runs (4 builds x 2 cases, each + # build picks other kernels): >= 0.9999977 / 6.2e-3 - 3.0e-2 / 2.5e-4 - 5.7e-4. + # - defective, 24 runs: 12 porting mistakes injected into the float32 reference, each + # on both cases; at best 0.999999993 / 6.3e-4 / 4.9e-5. The fp32 bounds reject all + # 24. The fp16 bounds reject the 16 whose errors exceed fp16 rounding (resize + # filter, normalization, channel order, stem padding, ViT taps, fusion and output + # interpolation); the other 8 (rescale 1/256, BiT weight-standardization eps, + # tanh GELU, LayerNorm eps) stay within the fp16 engine's own error, and the fp32 + # case, which runs in premerge, rejects them. + checks = [ + {"name": "depth_correlation", "label": "Pearson correlation", + "scope": "independent_reference", "actual": metrics["correlation"], "operator": ">=", + "expected": case["min_depth_correlation"], + "passed": metrics["correlation"] >= case["min_depth_correlation"]}, + {"name": "max_depth_relative_error", "label": "Largest |error| / max |reference|", + "scope": "independent_reference", "actual": metrics["max_error"], "operator": "<=", + "expected": case["max_depth_relative_error"], + "passed": metrics["max_error"] <= case["max_depth_relative_error"]}, + {"name": "mean_depth_relative_error", "label": "Mean |error| / max |reference|", + "scope": "independent_reference", "actual": metrics["mean_error"], "operator": "<=", + "expected": case["max_mean_depth_relative_error"], + "passed": metrics["mean_error"] <= case["max_mean_depth_relative_error"]}, + ] + native_png = _depth_png(native, metrics["scale"], tmp_path / "native_depth.png") + reference_png = _depth_png(reference, metrics["scale"], tmp_path / "reference_depth.png") + record_evidence("native", {"image": native_png}) + record_evidence("reference", {"image": reference_png}) + record_evidence( + "reference_comparison", + { + "label": case["name"], + "scope": "independent_reference", + "enforced": True, + "native": native_png, + "reference": reference_png, + "checks": checks, + }, + ) + failed = [check for check in checks if not check["passed"]] + assert not failed, f"depth parity failed: {failed}" + + +def _check_session_selection(request) -> None: + """Fail when a testcase selector names a case that no collected E2E test of the session runs. + + Selectors that name another collected family's cases pass; a misspelled one + fails here even when other selectors matched, in any session. + """ + requested = _filters(request.config, "--e2e-testcase") + if not requested: + return + collected = set() + for item in request.session.items: + params = getattr(getattr(item, "callspec", None), "params", {}) + if re.fullmatch(r"test_.*e2e", getattr(item, "originalname", "") or "") and "case_name" in params: + collected.add(params["case_name"]) + collected.discard(ELSEWHERE) # this placeholder runs no case + missing = sorted(requested - collected) + if missing: + pytest.fail(f"--e2e-testcase names no E2E case of this session: {', '.join(missing)}") + + +def check_selection(request) -> None: + """Both checks of the E2E selectors, for any test of the session (the host-side ones too).""" + _selected_cases(request.config) + _check_session_selection(request) + + +def test_e2e(case_name: str, request, tmp_path: Path, tmp_path_factory) -> None: + _check_session_selection(request) + if case_name == ELSEWHERE: + pytest.skip(f"the E2E selection names other families' cases, not {FAMILY}'s") + _, manifest, case = CASES[case_name] + binary, runtime_root = _runtime() + model_dir = _model_dir(manifest) + image, image_path = _input_image(case, tmp_path) + record_evidence("inputs", {"image": image_path}) + + with evidence_stage("build"): + bundle = _bundle(model_dir, manifest, tmp_path_factory) + with evidence_stage("native"): + native = _native(binary, runtime_root, bundle, image_path) + # The CLI has loaded the case's only engine and run it. + mark_loaded() + with evidence_stage("reference"): + reference = _reference(model_dir, image) + with evidence_stage("compare"): + _assert_parity(native, reference, image, case, tmp_path) diff --git a/families/dpt/tests/test_support.py b/families/dpt/tests/test_support.py new file mode 100644 index 0000000000..0896ab0cb3 --- /dev/null +++ b/families/dpt/tests/test_support.py @@ -0,0 +1,704 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +"""Identity, default task, build-configuration policy and E2E selection for DPT, without a GPU.""" + +import copy + +import pytest + +from families.dpt import config as config_module +from families.dpt.support import describe +from tensorrt_model_connect.model_support import ModelMetadata + +# The fields of Intel/dpt-hybrid-midas that decide the graph and the image pipeline. +_HYBRID = { + "model_type": "dpt", + "architectures": ["DPTForDepthEstimation"], + "is_hybrid": True, + "hidden_size": 768, + "num_hidden_layers": 12, + "num_attention_heads": 12, + "intermediate_size": 3072, + "hidden_act": "gelu", + "layer_norm_eps": 1e-12, + "image_size": 384, + "patch_size": 16, + "qkv_bias": True, + "backbone_out_indices": [2, 5, 8, 11], + "readout_type": "project", + "reassemble_factors": [1, 1, 1, 0.5], + "neck_hidden_sizes": [256, 512, 768, 768], + "fusion_hidden_size": 256, + "head_in_index": -1, + "use_batch_norm_in_fusion_residual": False, + "backbone_featmap_shape": [1, 1024, 24, 24], + "neck_ignore_stages": [0, 1], + "backbone_config": { + "model_type": "bit", + "depths": [3, 4, 9], + "embedding_dynamic_padding": True, + "embedding_size": 64, + "global_padding": "SAME", + "hidden_act": "relu", + "hidden_sizes": [256, 512, 1024, 2048], + "layer_type": "bottleneck", + "num_groups": 32, + "out_features": ["stage1", "stage2", "stage3"], + "output_stride": 32, + }, +} +_PROCESSOR = { + "do_normalize": True, + "do_rescale": True, + "do_resize": True, + "ensure_multiple_of": 1, + "image_mean": [0.5, 0.5, 0.5], + "image_std": [0.5, 0.5, 0.5], + "keep_aspect_ratio": False, + "resample": 2, + "rescale_factor": 0.00392156862745098, + "size": {"height": 384, "width": 384}, +} + + +def _config(**overrides) -> dict: + raw = copy.deepcopy(_HYBRID) + raw.update(overrides) + return raw + + +def _backbone(**overrides) -> dict: + raw = _config() + raw["backbone_config"].update(overrides) + return raw + + +def test_model_type_resolves_to_monocular_depth(): + support = describe(ModelMetadata(config={"model_type": "dpt"}, model_index={})) + assert support is not None + assert support.tasks == ("monocular_depth",) + assert support.default_task == "monocular_depth" + assert support.default_precision == "fp32" + + +def test_architecture_also_resolves(): + support = describe(ModelMetadata(config={"architectures": ["DPTForDepthEstimation"]}, + model_index={})) + assert support is not None + assert support.default_task == "monocular_depth" + + +def test_depth_anything_is_not_claimed(): + # Depth Anything carries a DPT neck too, but it is its own model type. + for config in ({"model_type": "depth_anything"}, + {"architectures": ["DepthAnythingForDepthEstimation"]}): + assert describe(ModelMetadata(config=config, model_index={})) is None + + +def test_hybrid_midas_geometry(): + resolved = config_module.resolve(_config(), _PROCESSOR) + backbone = resolved["backbone"] + # SAME padding: 7x7 stride 2 on 384 pads 2 before and 3 after; the pool 0 and 1. + assert backbone["stem_padding"] == (2, 3) + assert backbone["pool_padding"] == (0, 1) + stages = backbone["stages"] + assert [stage["out_channels"] for stage in stages] == [256, 512, 1024] + assert [stage["mid_channels"] for stage in stages] == [64, 128, 256] + assert [stage["stride"] for stage in stages] == [1, 2, 2] + assert [stage["out_side"] for stage in stages] == [96, 48, 24] + # Stride-2 3x3 convolutions pad only after; stride-1 ones pad symmetrically. + assert [stage["conv2_padding"] for stage in stages] == [(1, 1), (0, 1), (0, 1)] + assert [stage["downsample_padding"] for stage in stages] == [(0, 0), (0, 0), (0, 0)] + assert resolved["patch_grid"] == 24 + assert resolved["tap_layers"] == [8, 11] + assert resolved["head_dim"] == 64 + assert resolved["fusion_bias"] is True + assert resolved["processor"] == { + "rescale_factor": 0.00392156862745098, + "image_mean": [0.5, 0.5, 0.5], + "image_std": [0.5, 0.5, 0.5], + } + + +def test_vit_taps_follow_layer_order_like_the_reference(): + # The reference keeps encoder layers in order and filters by membership, so a + # reversed list still feeds layer 8 before layer 11 into the neck. + resolved = config_module.resolve(_config(backbone_out_indices=[2, 5, 11, 8]), _PROCESSOR) + assert resolved["tap_layers"] == [8, 11] + + +def test_a_vit_layer_named_twice_is_refused(): + with pytest.raises(ValueError, match="twice"): + config_module.resolve(_config(backbone_out_indices=[2, 5, 8, 8]), _PROCESSOR) + + +def test_a_hybrid_config_without_backbone_config_takes_the_hybrid_defaults(): + raw = _config() + del raw["backbone_config"] + resolved = config_module.resolve(raw, _PROCESSOR) + assert [stage["depth"] for stage in resolved["backbone"]["stages"]] == [3, 4, 9] + + +@pytest.mark.parametrize( + ("raw", "message"), + [ + (_config(is_hybrid=False), "DPT-Hybrid"), + (_config(architectures=["DPTForSemanticSegmentation"]), "DPTForDepthEstimation"), + (_config(model_type="depth_anything"), "model_type"), + (_config(add_projection=True), "add_projection"), + (_config(use_batch_norm_in_fusion_residual=True), "batch norm"), + (_config(neck_ignore_stages=[]), "neck_ignore_stages"), + (_config(reassemble_factors=[1, 1, 2, 0.5]), "reassemble factors"), + (_config(patch_size=32), "patch grid"), + (_backbone(layer_type="preactivation"), "bottleneck"), + (_backbone(global_padding=None), "SAME"), + (_backbone(model_type="dinov2"), "BiT backbone"), + (_backbone(out_features=["stage3"]), "three-stage"), + ], +) +def test_unsupported_configs_are_refused(raw, message): + with pytest.raises((NotImplementedError, ValueError), match=message): + config_module.resolve(raw, _PROCESSOR) + + +@pytest.mark.parametrize( + ("override", "message"), + [ + ({"keep_aspect_ratio": True}, "keep_aspect_ratio"), + ({"resample": 3}, "bilinear"), + ({"size": {"height": 512, "width": 512}}, "384x384"), + ({"do_pad": True}, "padded"), + ({"do_normalize": False}, "do_normalize"), + ({"image_std": [0.5, 0.0, 0.5]}, "non-zero"), + ], +) +def test_unsupported_image_processing_is_refused(override, message): + processor = dict(_PROCESSOR, **override) + with pytest.raises((NotImplementedError, ValueError), match=message): + config_module.resolve(_config(), processor) + + +def test_processor_defaults_are_the_library_defaults(): + # DPTImageProcessor resamples bicubically unless told otherwise, which this + # family does not reproduce. + processor = {key: value for key, value in _PROCESSOR.items() if key != "resample"} + with pytest.raises(NotImplementedError, match="bilinear"): + config_module.resolve(_config(), processor) + + +@pytest.mark.parametrize( + ("raw", "message"), + [ + (_config(hidden_size=768.0), "hidden_size must be an integer"), + (_config(num_channels=True), "num_channels must be an integer"), + (_config(hidden_size=None), "hidden_size must be an integer"), + (_config(image_size=2**40), "image_size is out of range"), + (_config(qkv_bias="false"), "qkv_bias must be true or false"), + (_config(qkv_bias=None), "qkv_bias must be true or false"), + (_config(is_hybrid=1), "is_hybrid must be true or false"), + (_config(layer_norm_eps=float("nan")), "layer_norm_eps must be a finite number"), + (_config(layer_norm_eps="1e-12"), "layer_norm_eps must be a finite number"), + (_config(backbone_out_indices=[2, 5, 8.0, 11]), "backbone_out_indices must be an integer"), + (_config(reassemble_factors=[1, 1, 1, "0.5"]), "reassemble_factors must be a finite number"), + (_config(use_bias_in_fusion_residual="true"), "use_bias_in_fusion_residual"), + (_config(architectures=[]), "architectures"), + (_config(backbone="google/bit-50"), "named backbone"), + (_backbone(depths=[3, 4, 9.0]), "BiT depths must be an integer"), + (_backbone(num_groups=None), "BiT num_groups must be an integer"), + (_backbone(width_factor="1"), "BiT width_factor must be a finite number"), + (_backbone(embedding_dynamic_padding="true"), "embedding_dynamic_padding"), + ], +) +def test_config_values_keep_their_json_types(raw, message): + # Each of these would pass a coercing reader (int(768.0), bool("false"), an + # explicit null taking the default) and build something the checkpoint is not. + with pytest.raises((NotImplementedError, ValueError), match=message): + config_module.resolve(raw, _PROCESSOR) + + +def test_null_is_accepted_where_transformers_accepts_it(): + raw = _config(architectures=None, use_bias_in_fusion_residual=None, backbone=None, + backbone_config=None) + resolved = config_module.resolve(raw, _PROCESSOR) + assert resolved["fusion_bias"] is True + assert [stage["depth"] for stage in resolved["backbone"]["stages"]] == [3, 4, 9] + + +@pytest.mark.parametrize( + ("override", "message"), + [ + ({"rescale_factor": "0.00392156862745098"}, "rescale_factor must be a finite number"), + ({"rescale_factor": None}, "rescale_factor must be a finite number"), + ({"resample": 2.0}, "resample must be an integer"), + ({"do_resize": "true"}, "do_resize must be true or false"), + ({"size": {"height": 384.0, "width": 384}}, "size.height must be an integer"), + ({"size": {"height": 384, "width": 384, "shortest_edge": 384}}, "384x384"), + ({"image_mean": 0.5}, "image_mean must be a list"), + # Accepted by a finite-and-non-zero check, but the runtime computes in float32: + ({"rescale_factor": 1e308}, "keep 255 within float32"), + ({"image_mean": [0.5, 0.5, 1e39]}, "fit float32"), + ({"image_std": [0.5, 1e-50, 0.5]}, "non-zero in float32"), + ({"image_std": [0.5, 1e-40, 0.5]}, "overflow float32"), + ], +) +def test_image_processor_values_are_checked_as_the_runtime_computes(override, message): + processor = dict(_PROCESSOR, **override) + with pytest.raises((NotImplementedError, ValueError), match=message): + config_module.resolve(_config(), processor) + + +@pytest.mark.parametrize( + ("text", "message"), + [ + ('{"model_type": "dpt", "hidden_size": 768, "hidden_size": 1024}', "repeats the key"), + ('{"model_type": "dpt", "backbone_config": {"depths": [3], "depths": [3, 4, 9]}}', + "repeats the key"), + ('{"model_type": "dpt", "layer_norm_eps": NaN}', "non-finite"), + ('{"model_type": "dpt", "layer_norm_eps": 1e400}', "non-finite"), + ('["dpt"]', "JSON object"), + ], +) +def test_json_files_are_read_strictly(tmp_path, text, message): + path = tmp_path / "config.json" + path.write_text(text, encoding="utf-8") + with pytest.raises(ValueError, match=message): + config_module._read_json(path) + + +class _Options: + """The three E2E selectors, and the paths given to pytest, as its config holds them.""" + + def __init__(self, models=(), testcases=(), models_file=None, args=()): + from pathlib import Path + from types import SimpleNamespace + + self._values = {"--e2e-model": list(models), "--e2e-testcase": list(testcases), + "--e2e-models-file": models_file} + self.args = list(args) + self.invocation_params = SimpleNamespace(dir=Path(__file__).resolve().parents[3]) + + def getoption(self, name, default=None): + return self._values.get(name, default) + + +_FP32 = ["dpt-hybrid-midas-landscape", "dpt-hybrid-midas-portrait"] +_FP16 = ["dpt-hybrid-midas-fp16-landscape", "dpt-hybrid-midas-fp16-portrait"] + + +@pytest.mark.parametrize( + ("models", "testcases", "expected"), + [ + ([], [], (sorted(_FP16 + _FP32), False)), + (["dpt"], [], (sorted(_FP16 + _FP32), True)), + (["dpt-hybrid-midas-fp16"], [], (_FP16, True)), + ([], ["dpt-hybrid-midas-landscape"], (["dpt-hybrid-midas-landscape"], True)), + (["dpt"], ["dpt-hybrid-midas-portrait, dpt-hybrid-midas-fp16-portrait"], + (["dpt-hybrid-midas-fp16-portrait", "dpt-hybrid-midas-portrait"], True)), + # Another family's selection leaves this file empty, so pytest skips it. + (["wavlm"], [], ([], True)), + ([], ["wavlm-base-plus-ctc"], ([], True)), + # A selection of several families cannot tell another family's case from a typo. + (["dpt", "wavlm"], ["dpt-hybrid-midas-landscape", "wavlm-base-plus-ctc"], + (["dpt-hybrid-midas-landscape"], True)), + ([], ["dpt-hybrid-midas-landscape,wavlm-base-plus-ctc"], (["dpt-hybrid-midas-landscape"], True)), + ], +) +def test_e2e_selection(models, testcases, expected): + from families.dpt.tests.test_e2e import _selected_cases + + assert _selected_cases(_Options(models, testcases)) == expected + + +@pytest.mark.parametrize( + ("models", "testcases"), + [ + (["dpt"], ["dpt-hybrid-midas-landscap"]), + (["dpt-hybrid-midas-fp16"], ["dpt-hybrid-midas-landscape"]), + (["wavlm"], ["dpt-hybrid-midas-landscape"]), + ], +) +def test_e2e_selection_that_names_dpt_but_matches_nothing_fails(models, testcases): + from families.dpt.tests.test_e2e import _selected_cases + + with pytest.raises(pytest.UsageError, match="the E2E selection of dpt"): + _selected_cases(_Options(models, testcases)) + + +@pytest.mark.parametrize( + ("models", "testcases", "args"), + [ + # The family alone is selected, so the misspelled case would silently not run. + (["dpt"], ["dpt-hybrid-midas-landscape,dpt-hybrid-midas-landscap"], []), + (["dpt-hybrid-midas-fp16"], ["dpt-hybrid-midas-fp16-landscape", "dpt-hybrid-midas-portrait"], []), + # Only this family's files are collected, the way CI runs them. + ([], ["dpt-hybrid-midas-landscape,dpt-hybrid-midas-landscap"], + ["families/dpt/tests/test_e2e.py"]), + (["dpt", "wavlm"], [], ["families/dpt/tests/test_e2e.py::test_e2e"]), + ], +) +def test_e2e_selection_of_dpt_alone_must_run_every_requested_case(models, testcases, args): + from families.dpt.tests.test_e2e import _selected_cases + + with pytest.raises(pytest.UsageError, match="asks for what it cannot run"): + _selected_cases(_Options(models, testcases, args=args)) + assert _selected_cases(_Options(["dpt"], ["dpt-hybrid-midas-landscape"], + args=["families/dpt/tests/test_e2e.py"])) \ + == (["dpt-hybrid-midas-landscape"], True) + # Another family's selection still leaves this file empty, whatever is collected. + assert _selected_cases(_Options(["wavlm"], args=["families/dpt/tests/test_e2e.py"])) == ([], True) + + +@pytest.mark.parametrize( + ("models", "testcases"), + [ + # Several families collected: a selector extending a dpt manifest name is still dpt's. + ([], ["dpt-hybrid-midas-landscap"]), + ([], ["dpt-hybrid-midas-landscape,dpt-hybrid-midas-landscap,wavlm-base-plus-ctc"]), + (["dpt-hybrid-midas-fp1"], []), + (["dpt-hybrid-midas-fp1", "wavlm"], ["wavlm-base-plus-ctc"]), + ], +) +def test_e2e_selection_of_a_misspelled_dpt_name_fails_in_any_session(models, testcases): + from families.dpt.tests.test_e2e import _selected_cases + + with pytest.raises(pytest.UsageError, match="asks for what it cannot run"): + _selected_cases(_Options(models, testcases)) + + +def test_e2e_models_file_selects_and_fails_the_same_way(tmp_path): + from families.dpt.tests.test_e2e import _selected_cases + + listing = tmp_path / "models.txt" + listing.write_text("# comment\ndpt-hybrid-midas-fp16\n\n", encoding="utf-8") + assert _selected_cases(_Options(models_file=str(listing))) == (_FP16, True) + with pytest.raises(pytest.UsageError, match="the E2E selection of dpt"): + _selected_cases(_Options(testcases=["dpt-hybrid-midas-landscape"], + models_file=str(listing))) + with pytest.raises(pytest.UsageError, match="asks for what it cannot run"): + _selected_cases(_Options(testcases=["dpt-hybrid-midas-fp16-landscape,dpt-hybrid-midas-fp16-landscap"], + models_file=str(listing))) + + +def test_e2e_model_dir_override_stands_for_one_checkpoint(monkeypatch): + from families.dpt.tests import test_e2e as e2e + + monkeypatch.setenv(e2e.MODEL_DIR_OVERRIDE, "/checkpoint") + e2e._require_one_checkpoint(sorted(e2e.CASES)) # both manifests use one checkpoint + cases = copy.deepcopy(e2e.CASES) + path, manifest, case = cases["dpt-hybrid-midas-fp16-landscape"] + cases["dpt-hybrid-midas-fp16-landscape"] = (path, dict(manifest, hf_revision="0" * 40), case) + monkeypatch.setattr(e2e, "CASES", cases) + with pytest.raises(pytest.UsageError, match="stands for one checkpoint"): + e2e._require_one_checkpoint(sorted(cases)) + monkeypatch.delenv(e2e.MODEL_DIR_OVERRIDE) + e2e._require_one_checkpoint(sorted(cases)) + + +@pytest.mark.parametrize( + ("change", "message"), + [ + (lambda case: case.update(min_depth_correlation="0.999999"), "min_depth_correlation"), + (lambda case: case.update(max_depth_relative_error=True), "max_depth_relative_error"), + (lambda case: case.update(max_mean_depth_relative_error=float("nan")), "max_mean"), + (lambda case: case.update(max_depth_relative_error=0), "max_depth_relative_error"), + (lambda case: case.update(transpose="false"), "transpose must be a boolean"), + (lambda case: case.pop("premerge"), "premerge must be a boolean"), + (lambda case: case.update(test_image="../manifests/dpt-hybrid-midas.json"), "test_image"), + ], +) +def test_e2e_manifests_are_checked(change, message): + import json + from pathlib import Path + + from families.dpt.tests import test_e2e as e2e + + path = Path(e2e.MANIFEST_ROOT) / "dpt-hybrid-midas.json" + manifest = json.loads(path.read_text(encoding="utf-8")) + e2e._check_manifest(path, manifest) + change(manifest["testcases"][0]) + with pytest.raises(ValueError, match=message): + e2e._check_manifest(path, manifest) + + +def test_depth_shapes_are_checked_before_any_error_is_computed(): + import numpy as np + + from families.dpt.tests.test_e2e import _depth_metrics + + row = np.linspace(1.0, 2.0, 6) + # A (1, 6) reference broadcasts against a (4, 6) map without complaint. + with pytest.raises(AssertionError, match="differs from the reference"): + _depth_metrics(np.tile(row, (4, 1)), row[None, :]) + values = _depth_metrics(np.tile(row, (4, 1)), np.tile(row, (4, 1)) * 1.01) + assert values["max_error"] == pytest.approx(0.01 / 1.01) + with pytest.raises(AssertionError, match="not finite"): + _depth_metrics(np.full((2, 3), np.nan), np.ones((2, 3))) + + +def test_bit_weights_must_have_the_shapes_the_configuration_implies(): + from types import SimpleNamespace + + resolved = config_module.resolve(_config(), _PROCESSOR) + shapes = dict(config_module.bit_weight_shapes(resolved)) + bit = config_module.BIT_PREFIX + # The stem, and 3 + 4 + 9 bottleneck layers of three convolutions plus one + # downsample per stage. + assert len(shapes) == 1 + 3 * (3 + 4 + 9) + 3 + assert shapes[f"{bit}.embedder.convolution.weight"] == (64, 3, 7, 7) + assert shapes[f"{bit}.encoder.stages.0.layers.0.downsample.conv.weight"] == (256, 64, 1, 1) + assert shapes[f"{bit}.encoder.stages.1.layers.0.conv1.weight"] == (128, 256, 1, 1) + assert shapes[f"{bit}.encoder.stages.2.layers.8.conv3.weight"] == (1024, 256, 1, 1) + checkpoint = {name: SimpleNamespace(shape=shape) for name, shape in shapes.items()} + config_module.check_weight_shapes(checkpoint, shapes.items()) + + # A configuration that names a wider stem than the checkpoint holds is refused, + # rather than built from the 64-channel weights. + wider = config_module.resolve(_backbone(embedding_size=128), _PROCESSOR) + with pytest.raises(ValueError, match=r"embedder\.convolution\.weight has shape \(64, 3, 7, 7\)"): + config_module.check_weight_shapes(checkpoint, config_module.bit_weight_shapes(wider)) + deeper = config_module.resolve(_backbone(depths=[3, 4, 10]), _PROCESSOR) + with pytest.raises(KeyError, match=r"stages\.2\.layers\.9"): + config_module.check_weight_shapes(checkpoint, config_module.bit_weight_shapes(deeper)) + + +def test_an_extreme_bit_depth_is_refused_at_the_first_missing_weight(): + import time + from types import SimpleNamespace + + shapes = dict(config_module.bit_weight_shapes(config_module.resolve(_config(), _PROCESSOR))) + checkpoint = {name: SimpleNamespace(shape=shape) for name, shape in shapes.items()} + deepest = config_module.resolve(_backbone(depths=[3, 4, 2**31 - 1]), _PROCESSOR) + started = time.monotonic() + # Checked lazily: the expected names stop at the checkpoint's last layer, + # instead of first listing two billion layers. + with pytest.raises(KeyError, match=r"stages\.2\.layers\.9\.conv1"): + config_module.check_weight_shapes(checkpoint, config_module.bit_weight_shapes(deepest)) + assert time.monotonic() - started < 5.0 + + +@pytest.mark.parametrize("value", [384.5, 384.0, "384", True]) +def test_a_requested_image_size_must_be_an_integer(value): + with pytest.raises(ValueError, match="must be an integer"): + config_module.check_requested_image_size("image_height", value, 384) + + +def test_a_requested_image_size_must_be_the_checkpoints(): + config_module.check_requested_image_size("image_width", None, 384) + config_module.check_requested_image_size("image_width", 384, 384) + with pytest.raises(NotImplementedError, match="native image_width"): + config_module.check_requested_image_size("image_width", 512, 384) + + +def test_the_fp16_engine_input_must_fit_fp16(): + processor = config_module.resolve(_config(), _PROCESSOR)["processor"] + config_module.check_engine_input(processor, "fp16") # [-1, 1] + # Finite in float32, so the configuration resolves; (1 - 0.5) / 1e-6 is past fp16. + narrow = config_module.resolve(_config(), dict(_PROCESSOR, image_std=[1e-6] * 3))["processor"] + config_module.check_engine_input(narrow, "fp32") + with pytest.raises(ValueError, match="past fp16"): + config_module.check_engine_input(narrow, "fp16") + + +@pytest.mark.parametrize("eps", [1e100, 1e-100]) +def test_layer_norm_eps_must_be_a_positive_float32_value(eps): + # 1e100 is infinite and 1e-100 zero once TensorRT stores the epsilon as float32. + with pytest.raises(ValueError, match="positive float32"): + config_module.resolve(_config(layer_norm_eps=eps), _PROCESSOR) + + +@pytest.mark.parametrize("factor", [2**-100, 1 / 48, 0.4]) +def test_a_tap_reassemble_factor_must_give_a_stride_within_the_grid(factor): + # 2**-100 would be a stride of 2**100; 1/48 strides past the 24x24 grid; 0.4 is not 1/n. + with pytest.raises(NotImplementedError, match="n from 2 to 24"): + config_module.resolve(_config(reassemble_factors=[1, 1, 1, factor]), _PROCESSOR) + assert config_module.resolve(_config(reassemble_factors=[1, 1, 1, 0.25]), _PROCESSOR) + + +@pytest.mark.parametrize("key", ["size", "image_mean", "image_std"]) +def test_a_null_processor_field_takes_the_image_processors_default(key): + # DPTImageProcessor replaces these three nulls with its defaults; the checkpoint's + # values are those defaults, so the resolved pipeline is the same. + expected = config_module.resolve(_config(), _PROCESSOR)["processor"] + assert config_module.resolve(_config(), dict(_PROCESSOR, **{key: None}))["processor"] == expected + + +@pytest.mark.parametrize( + "selectors", + [ + {"out_features": None, "out_indices": [1, 2, 3]}, + {"out_features": None, "out_indices": [-3, -2, -1]}, + {"out_features": ["stage1", "stage2", "stage3"], "out_indices": [1, 2, 3]}, + ], +) +def test_bit_outputs_may_be_named_by_index(selectors): + resolved = config_module.resolve(_backbone(**selectors), _PROCESSOR) + assert [stage["out_channels"] for stage in resolved["backbone"]["stages"]] == [256, 512, 1024] + + +@pytest.mark.parametrize( + ("selectors", "error", "message"), + [ + ({"out_indices": [0, 1, 2]}, ValueError, "name different stages"), + ({"out_features": None, "out_indices": [1, 2, 2]}, ValueError, "distinct and in order"), + ({"out_features": None, "out_indices": [1, 2, 3.0]}, ValueError, "must be an integer"), + ({"out_features": None, "out_indices": [1, 2, 4]}, ValueError, "must index"), + ({"out_features": ["stage1", "stage3", "stage2"]}, ValueError, "in order"), + ({"out_features": None, "out_indices": None}, NotImplementedError, "three-stage"), + ({"out_features": None, "out_indices": [2, 3]}, NotImplementedError, "three-stage"), + ], +) +def test_bit_output_selectors_are_aligned_like_transformers(selectors, error, message): + with pytest.raises(error, match=message): + config_module.resolve(_backbone(**selectors), _PROCESSOR) + + +@pytest.mark.parametrize( + ("make", "message"), + [ + (lambda torch: torch.zeros(2, dtype=torch.int64), "not floating point"), + (lambda torch: torch.zeros(2, dtype=torch.complex64), "not floating point"), + (lambda torch: torch.tensor([0.0, float("nan")]), "not finite"), + (lambda torch: torch.tensor([1e300], dtype=torch.float64), "not finite"), + ], +) +def test_checkpoint_tensors_must_be_finite_floating_point(make, message): + import torch + + from families.dpt.checkpoint import tensor_arrays + + with pytest.raises(ValueError, match=message): + tensor_arrays({"weight": make(torch)}, "checkpoint") + + +def test_a_checkpoint_is_read_as_float32_with_weights_only(tmp_path): + import numpy as np + import torch + + from families.dpt import checkpoint + + torch.save({"weight": torch.ones(2, dtype=torch.bfloat16)}, tmp_path / checkpoint.CHECKPOINT) + arrays = checkpoint.load_tensors(tmp_path) + assert arrays["weight"].dtype == np.float32 and arrays["weight"].tolist() == [1.0, 1.0] + torch.save([torch.ones(2)], tmp_path / checkpoint.CHECKPOINT) + with pytest.raises(ValueError, match="does not hold a state dict"): + checkpoint.load_tensors(tmp_path) + + +def test_engine_weights_must_fit_their_storage_dtype(): + import numpy as np + + from families.dpt.checkpoint import as_engine_weights + + bias = np.array([0.5, 1e5], dtype=np.float32) + assert as_engine_weights(bias, np.float32).dtype == np.float32 + # Finite in float32, past fp16's 65504: the fp16 engine would hold an infinity. + with pytest.raises(ValueError, match="not finite in float16"): + as_engine_weights(bias, np.float16) + with pytest.raises(ValueError, match="not finite in float32"): + as_engine_weights(np.array([np.nan]), np.float32) + + +def test_the_image_size_stays_within_the_runtimes_input_limit(): + # The runtime refuses more than INT32_MAX / 4 pixels; 32768 x 32768 is past it. + with pytest.raises(ValueError, match="runtime's input limit"): + config_module.resolve(_config(image_size=2**15), _PROCESSOR) + + +def _e2e_item(case_name, name="test_e2e"): + from types import SimpleNamespace + + return SimpleNamespace(originalname=name, callspec=SimpleNamespace(params={"case_name": case_name})) + + +def test_a_testcase_only_selection_of_other_families_checks_the_session(): + from types import SimpleNamespace + + from families.dpt.tests import test_e2e as e2e + + calls = [] + metafunc = SimpleNamespace(fixturenames=["case_name"], config=_Options([], ["wavlm-base-plus-ctc"]), + parametrize=lambda *args, **kwargs: calls.append(args[1])) + e2e.pytest_generate_tests(metafunc) + assert calls == [[e2e.ELSEWHERE]] + + owned = SimpleNamespace(config=metafunc.config, session=SimpleNamespace( + items=[_e2e_item(e2e.ELSEWHERE), _e2e_item("wavlm-base-plus-ctc")])) + e2e._check_session_selection(owned) + # No collected E2E test runs the requested case: the session must not pass. + unowned = SimpleNamespace(config=metafunc.config, session=SimpleNamespace( + items=[_e2e_item(e2e.ELSEWHERE), _e2e_item("wavlm-base-plus-ctc", name="test_tokenizer")])) + with pytest.raises(pytest.fail.Exception, match="wavlm-base-plus-ctc"): + e2e._check_session_selection(unowned) + + +def test_a_misspelled_selector_fails_even_when_another_matched(): + from types import SimpleNamespace + + from families.dpt.tests import test_e2e as e2e + + request = SimpleNamespace( + config=_Options([], ["dpt-hybrid-midas-landscape,landscap"]), + session=SimpleNamespace(items=[_e2e_item("dpt-hybrid-midas-landscape"), + _e2e_item("wavlm-base-plus-ctc")])) + with pytest.raises(pytest.fail.Exception, match="landscap"): + e2e._check_session_selection(request) + request.config = _Options(["dpt", "wavlm"], ["dpt-hybrid-midas-landscape,wavlm-base-plus-ctc"]) + e2e._check_session_selection(request) + + +def test_another_familys_model_selection_still_leaves_the_file_empty(): + from types import SimpleNamespace + + from families.dpt.tests import test_e2e as e2e + + calls = [] + metafunc = SimpleNamespace(fixturenames=["case_name"], config=_Options(["wavlm"]), + parametrize=lambda *args, **kwargs: calls.append(args[1])) + e2e.pytest_generate_tests(metafunc) + assert calls == [[]] + + +def test_the_placeholder_is_not_a_case_of_the_session(): + from types import SimpleNamespace + + from families.dpt.tests import test_e2e as e2e + + request = SimpleNamespace(config=_Options([], [e2e.ELSEWHERE]), + session=SimpleNamespace(items=[_e2e_item(e2e.ELSEWHERE)])) + with pytest.raises(pytest.fail.Exception, match=e2e.ELSEWHERE): + e2e._check_session_selection(request) + + +def test_the_sessions_e2e_selection_holds_on_the_host_too(request): + """The E2E selectors given to this session, checked as test_e2e.py checks them. + + Without selectors this passes. A host-only run with ``--e2e-testcase`` (of this + family or of several) fails here, since no collected E2E test runs the case, + instead of passing without noticing the selection. + """ + from families.dpt.tests.test_e2e import check_selection + + check_selection(request) + + +@pytest.mark.parametrize( + ("models", "testcases", "args"), + [ + ([], ["wavlm-base-plus-ctc"], []), # several families' host tests, another family's case + ([], ["dpt-hybrid-midas-landscape"], ["families/dpt/tests/test_support.py"]), + (["dpt"], ["dpt-hybrid-midas-landscape"], []), + ], +) +def test_a_host_only_session_with_testcases_fails(models, testcases, args): + from types import SimpleNamespace + + from families.dpt.tests.test_e2e import check_selection + + host_items = [_e2e_item("unused", name="test_bit_weights_must_have_the_shapes_the_configuration_implies")] + request = SimpleNamespace(config=_Options(models, testcases, args=args), + session=SimpleNamespace(items=host_items)) + with pytest.raises(pytest.fail.Exception, match="names no E2E case of this session"): + check_selection(request) + request.session.items = host_items + [_e2e_item(name) for name in testcases] + check_selection(request) From 2ed8d21893eeeba2c9d39373511b7246f7750c5b Mon Sep 17 00:00:00 2001 From: Qikai Li Date: Wed, 25 Nov 2026 07:51:00 +0000 Subject: [PATCH 2/2] fix(dpt): refuse old torch loaders and unusable tap factors before the graph Require torch 2.10.0 or later: before it, torch.load with weights_only=True can run code from a crafted checkpoint (CVE-2026-24747). load_tensors checks the installed version before it reads the file, and the tests assert that it passes weights_only=True. Refuse a last ViT tap reassemble factor whose depth map would not come out at the input size, and check the hybrid patch embedding's tensors against the configuration before the graph is built, so that a malformed position embedding is reported with its shape. Signed-off-by: Qikai Li --- families/dpt/README.md | 3 +- families/dpt/checkpoint.py | 8 ++++ families/dpt/config.py | 18 +++++++++ families/dpt/model.py | 10 ++--- families/dpt/requirements.txt | 2 +- families/dpt/tests/test_support.py | 65 +++++++++++++++++++++++++++--- 6 files changed, 92 insertions(+), 14 deletions(-) diff --git a/families/dpt/README.md b/families/dpt/README.md index 665d733268..6ad0ae1a3c 100644 --- a/families/dpt/README.md +++ b/families/dpt/README.md @@ -15,7 +15,8 @@ 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; it is read with `weights_only=True`. +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 diff --git a/families/dpt/checkpoint.py b/families/dpt/checkpoint.py index 41cb5c0cf7..84f60fb95b 100644 --- a/families/dpt/checkpoint.py +++ b/families/dpt/checkpoint.py @@ -10,6 +10,9 @@ 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]: @@ -59,6 +62,11 @@ def load_tensors(model_dir: str | Path) -> dict[str, np.ndarray]: 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}") diff --git a/families/dpt/config.py b/families/dpt/config.py index ff3a5f5c9d..461f5e9947 100644 --- a/families/dpt/config.py +++ b/families/dpt/config.py @@ -469,6 +469,14 @@ def resolve(raw: dict, processor: dict) -> dict: raise NotImplementedError( f"DPT-Hybrid needs BiT's last stage at the patch grid ({grid}); it is " f"{stage3['out_side']}") + # The depth map is the deepest map after four fusion doublings and the head's, 32 + # times its side; the runtime returns it at the input side. + last = factors[3] + deepest = grid if last == 1.0 else (grid + 2 - 3) // int(round(1.0 / last)) + 1 + if 32 * deepest != image_size: + raise NotImplementedError( + f"dpt needs the last ViT tap's reassemble factor to give a {image_size // 32}-pixel map " + f"(the depth map is 32 times its side); factor {last} gives {deepest}") featmap = _integers(values["backbone_featmap_shape"], "backbone_featmap_shape") if len(featmap) != 4 or featmap[1] != stage3["out_channels"]: raise ValueError( @@ -524,6 +532,16 @@ def bit_weight_shapes(resolved: dict) -> Iterator[tuple[str, tuple[int, ...]]]: yield f"{prefix}.{module}.weight", shape +def vit_embedding_shapes(resolved: dict) -> Iterator[tuple[str, tuple[int, ...]]]: + """The hybrid patch embedding's tensors, with the shapes the configuration implies.""" + hidden = resolved["hidden_size"] + tokens = 1 + resolved["patch_grid"] ** 2 + yield "dpt.embeddings.projection.weight", (hidden, resolved["backbone"]["stages"][-1]["out_channels"], 1, 1) + yield "dpt.embeddings.projection.bias", (hidden,) + yield "dpt.embeddings.cls_token", (1, 1, hidden) + yield "dpt.embeddings.position_embeddings", (1, tokens, hidden) + + def check_weight_shapes(tensors: dict, expected: Iterable[tuple[str, tuple[int, ...]]]) -> None: """Refuse a checkpoint whose tensors lack the shapes its configuration implies.""" for name, shape in expected: diff --git a/families/dpt/model.py b/families/dpt/model.py index 130d2edfd8..53c0227739 100644 --- a/families/dpt/model.py +++ b/families/dpt/model.py @@ -24,6 +24,7 @@ from __future__ import annotations +import itertools import math from pathlib import Path @@ -155,11 +156,7 @@ def _vit(network, feature_map, weights: _Weights, cfg, work_np): dtype=work_np) sequence = network.add_concatenation([cls_token, patches]) sequence.axis = 1 - position = weights.get("dpt.embeddings.position_embeddings") - if position.shape != (1, tokens, hidden): - raise NotImplementedError( - f"DPT position embeddings cover {position.shape[1]} tokens; this family builds the " - f"checkpoint's native {grid}x{grid} grid ({tokens} tokens) only") + position = weights.get("dpt.embeddings.position_embeddings", (1, tokens, hidden)) states = graph_ops.add_sum( network, sequence.get_output(0), graph_ops.add_constant(network, (1, tokens, hidden), position, dtype=work_np)) @@ -417,7 +414,8 @@ def build(request, writer) -> None: tensors = load_tensors(model_dir) # Before any graph is built: a backbone configured wider or narrower than the # checkpoint's weights is refused, not built from the weights alone. - config_module.check_weight_shapes(tensors, config_module.bit_weight_shapes(cfg)) + config_module.check_weight_shapes(tensors, itertools.chain( + config_module.bit_weight_shapes(cfg), config_module.vit_embedding_shapes(cfg))) weights = _Weights(tensors) plan = build_engine(weights, cfg, precision=precision, verbose=bool(request.verbose)) diff --git a/families/dpt/requirements.txt b/families/dpt/requirements.txt index f43ac85079..c8b880fd0d 100644 --- a/families/dpt/requirements.txt +++ b/families/dpt/requirements.txt @@ -1,6 +1,6 @@ # SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. # SPDX-License-Identifier: Apache-2.0 -torch>=2.6 +torch>=2.10.0 transformers==5.2.0 Pillow==13.0.0 diff --git a/families/dpt/tests/test_support.py b/families/dpt/tests/test_support.py index 0896ab0cb3..7b1533d8a7 100644 --- a/families/dpt/tests/test_support.py +++ b/families/dpt/tests/test_support.py @@ -4,6 +4,7 @@ """Identity, default task, build-configuration policy and E2E selection for DPT, without a GPU.""" import copy +import re import pytest @@ -512,7 +513,16 @@ def test_a_tap_reassemble_factor_must_give_a_stride_within_the_grid(factor): # 2**-100 would be a stride of 2**100; 1/48 strides past the 24x24 grid; 0.4 is not 1/n. with pytest.raises(NotImplementedError, match="n from 2 to 24"): config_module.resolve(_config(reassemble_factors=[1, 1, 1, factor]), _PROCESSOR) - assert config_module.resolve(_config(reassemble_factors=[1, 1, 1, 0.25]), _PROCESSOR) + # The first tap's map is resized onto the fused one, so any of its strides works. + assert config_module.resolve(_config(reassemble_factors=[1, 1, 0.25, 0.5]), _PROCESSOR) + + +@pytest.mark.parametrize(("factor", "side"), [(1.0, 24), (0.25, 6), (1 / 3, 8)]) +def test_the_last_tap_factor_must_give_a_depth_map_of_the_input_size(factor, side): + # The depth map is 32 times the deepest map's side: 12 for a 384-pixel input. The + # graph would build 768, 192 or 256 pixels instead. + with pytest.raises(NotImplementedError, match=re.escape(f"factor {factor} gives {side}")): + config_module.resolve(_config(reassemble_factors=[1, 1, 1, factor]), _PROCESSOR) @pytest.mark.parametrize("key", ["size", "image_mean", "image_std"]) @@ -578,11 +588,54 @@ def test_a_checkpoint_is_read_as_float32_with_weights_only(tmp_path): from families.dpt import checkpoint torch.save({"weight": torch.ones(2, dtype=torch.bfloat16)}, tmp_path / checkpoint.CHECKPOINT) - arrays = checkpoint.load_tensors(tmp_path) - assert arrays["weight"].dtype == np.float32 and arrays["weight"].tolist() == [1.0, 1.0] - torch.save([torch.ones(2)], tmp_path / checkpoint.CHECKPOINT) - with pytest.raises(ValueError, match="does not hold a state dict"): - checkpoint.load_tensors(tmp_path) + calls = [] + load = torch.load + + def spy(*args, **kwargs): + calls.append(kwargs) + return load(*args, **kwargs) + + with pytest.MonkeyPatch.context() as patch: + patch.setattr(torch, "load", spy) + arrays = checkpoint.load_tensors(tmp_path) + # The loader is restricted to tensors and plain containers, never full pickle. + assert [call.get("weights_only") for call in calls] == [True] + assert arrays["weight"].dtype == np.float32 and arrays["weight"].tolist() == [1.0, 1.0] + torch.save([torch.ones(2)], tmp_path / checkpoint.CHECKPOINT) + with pytest.raises(ValueError, match="does not hold a state dict"): + checkpoint.load_tensors(tmp_path) + + +@pytest.mark.parametrize("version", ["2.9.1", "2.6.0+cu124", "2.10.0.dev20251201"]) +def test_a_torch_that_can_run_code_from_a_checkpoint_is_refused_before_loading(tmp_path, version): + import torch + + from families.dpt import checkpoint + + torch.save({"weight": torch.ones(2)}, tmp_path / checkpoint.CHECKPOINT) + calls = [] + with pytest.MonkeyPatch.context() as patch: + patch.setattr(torch, "__version__", version) + patch.setattr(torch, "load", lambda *args, **kwargs: calls.append(kwargs)) + with pytest.raises(RuntimeError, match="torch 2.10.0 or later"): + checkpoint.load_tensors(tmp_path) + assert calls == [] + + +def test_vit_embeddings_are_checked_before_the_graph(): + from types import SimpleNamespace + + resolved = config_module.resolve(_config(), _PROCESSOR) + shapes = dict(config_module.vit_embedding_shapes(resolved)) + assert shapes["dpt.embeddings.position_embeddings"] == (1, 577, 768) + assert shapes["dpt.embeddings.projection.weight"] == (768, 1024, 1, 1) + checkpoint = {name: SimpleNamespace(shape=shape) for name, shape in shapes.items()} + config_module.check_weight_shapes(checkpoint, shapes.items()) + # A rank-one tensor is reported with its shape, not by indexing a missing axis. + for wrong in ((577,), (1, 1025, 768)): + checkpoint["dpt.embeddings.position_embeddings"] = SimpleNamespace(shape=wrong) + with pytest.raises(ValueError, match=re.escape(f"has shape {wrong}")): + config_module.check_weight_shapes(checkpoint, config_module.vit_embedding_shapes(resolved)) def test_engine_weights_must_fit_their_storage_dtype():