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..6ad0ae1a3c --- /dev/null +++ b/families/dpt/README.md @@ -0,0 +1,99 @@ +# DPT-Hybrid (MiDaS) + +This family builds the Transformers DPT-Hybrid depth model +(`DPTForDepthEstimation` with `is_hybrid: true`, as in +[`Intel/dpt-hybrid-midas`](https://huggingface.co/Intel/dpt-hybrid-midas)) as one +TensorRT engine for the `monocular_depth` task. A BiT ResNet stem and three +bottleneck stages feed a ViT-B/16 encoder; the DPT neck fuses BiT stages 1-2 +with two ViT layers, and the head predicts relative inverse depth (MiDaS units, +larger is nearer) for every pixel of the input image. + +```sh +trtmc build Intel/dpt-hybrid-midas -o dpt-hybrid-midas.bundle +trtmc depth dpt-hybrid-midas.bundle --image photo.jpg +``` + +The default precision is fp32, the checkpoint's own; `--precision fp16` builds +an fp16 engine. Batch is 1. The checkpoint ships only `pytorch_model.bin`, so the +build needs torch 2.10 or later (earlier versions can run code from a crafted file +even with `weights_only=True`); it is read with `weights_only=True`. + +## Image pipeline + +The family reproduces the checkpoint's `DPTImageProcessor` and +`post_process_depth_estimation` in C++: + +- The input (RGB float32 in `[0, 1]`) is taken back to its 8-bit samples and + resized to 384x384 with Pillow 13's bilinear filter (fixed-point, two passes, + the vertical pass first when the height shrinks more than twice as much as the + width), then rescaled by 1/255 and normalized with mean and std 0.5. On the + test image, in landscape and portrait orientation, the engine input is + bit-identical to the processor's `pixel_values`. +- The 384x384 depth map is resized back to the input size bicubically + (`align_corners=False`, A = -0.75), as `post_process_depth_estimation` does. + +Both are adapted from Pillow and PyTorch; see `NOTICE`. + +## Accuracy + +`tests/test_e2e.py` compares the CLI's depth map with the official pipeline in +float32 on the CPU (`DPTImageProcessor`, `DPTForDepthEstimation`, +`post_process_depth_estimation`) on the repository's test photograph in +landscape and in portrait orientation. Errors are relative to the largest +reference depth. 1x NVIDIA B300, CUDA 13, TensorRT 11.4, six builds of the fp32 +engine and four of the fp16 one: + +| Engine | Largest error | Mean error | Correlation | Engine call, batch 1 | +|---|---|---|---|---| +| fp32 | 2.8e-6 - 7.8e-6 | 2.0e-7 - 2.1e-7 | > 0.999999999999 | 8.7 ms | +| fp16 | 6.2e-3 - 3.0e-2 | 2.5e-4 - 5.7e-4 | >= 0.9999977 | 1.7 ms | + +The fp32 builds are identical; the fp16 builds pick different kernels, and their +largest error on the landscape input moves between 1.3e-2 and 3.0e-2. For scale, the official model's +own float32 run on the GPU differs from its CPU run by up to 5.5e-6, and its +float16 run by up to 6.2e-3 (mean 2.8e-4 - 5.3e-4, compared on the 384x384 +maps). On those maps the fp16 engine matches the official float16 run up to the +99th percentile (1.7e-3 against 1.5e-3); its largest errors, on about 0.1 % of +the pixels, are two to five times larger. They build up across the ViT encoder +and the neck: running one stage or the head in fp32 removes at most half of +them, so the engine stays fp16 throughout. + +The bounds were also checked against known-wrong outputs: twelve plausible +porting mistakes injected into the float32 reference (resize filter, +normalization, rescale factor, channel order, BiT stem padding and +weight-standardization epsilon, ViT taps, GELU form, LayerNorm epsilon, fusion +and output interpolation), each on both inputs. The fp32 bounds (largest error +1e-4, mean 1e-5, correlation 0.999999) reject all 24 outputs, none of which +errs by less than 6.3e-4 (largest) or 4.9e-5 (mean). The fp16 bounds (0.05, +0.002, 0.99999) leave the fp16 engine at least 1.7 times its measured errors +and reject 16; the four mistakes they pass (rescale 1/256, +weight-standardization epsilon, tanh GELU, LayerNorm epsilon) err less than +fp16 rounding does, and the fp32 case, which runs in premerge, rejects them. + +## Not supported + +- DPT checkpoints other than DPT-Hybrid: the ViT-only `dpt-large`, and BEiT, + DINOv2 or Swin backbones. The build refuses them by name. +- `DPTForSemanticSegmentation`, `add_projection`, batch norm in the fusion units, + other image-processor settings (aspect-ratio-preserving resize, other + resampling filters, padding). +- Other input resolutions: images of any size are resized to the checkpoint's + 384x384, and the position embeddings are not interpolated. +- Batch sizes above 1, quantization, tensor parallelism. + +## Tests + +```sh +cmake --build build --target test_dpt_image_ops test_dpt_pipeline +ctest --test-dir build --output-on-failure -R '^dpt_' +PYTHONPATH=core/builder:apps/benchmark:. python3 -m pytest families/dpt/tests --e2e-model dpt -q +``` + +`test_dpt_image_ops` checks the resize against Pillow byte for byte, the whole +preprocessing against `DPTImageProcessor` bit for bit, and the bicubic resize +against torch, with goldens from `tests/cpp/generate_image_ops_goldens.py`. +`test_dpt_pipeline` checks, with a stand-in engine, that the runtime refuses a +malformed `runtime.json`, an engine whose inputs or outputs differ from it, and +a non-finite depth map. `tests/test_support.py` covers identity, the default +task, the resolved geometry, every refused configuration value and the E2E case +selection. 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..84f60fb95b --- /dev/null +++ b/families/dpt/checkpoint.py @@ -0,0 +1,74 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +"""Read the tensors of a DPT checkpoint.""" + +from __future__ import annotations + +from pathlib import Path + +import numpy as np + +CHECKPOINT = "pytorch_model.bin" +# Before 2.10.0, torch.load(weights_only=True) can run code from a crafted file +# (CVE-2026-24747, GHSA-63cw-57p8-fm3p). +MIN_TORCH = "2.10.0" + + +def tensor_arrays(state, source: str) -> dict[str, np.ndarray]: + """Float32 copies of a state dict's tensors. + + Every entry must be a named floating-point tensor whose values stay finite in + float32: integer, boolean or complex tensors are not weights of this graph, and a + NaN or infinity (also one that the conversion from float64 creates) would reach + the engine. + """ + import torch + + if not isinstance(state, dict): + raise ValueError(f"{source} does not hold a state dict") + arrays = {} + for name, value in state.items(): + if not isinstance(name, str) or not isinstance(value, torch.Tensor): + raise ValueError(f"{source} holds an entry that is not a named tensor: {name!r}") + if not value.is_floating_point(): + raise ValueError(f"{source}: tensor {name} is {value.dtype}, not floating point") + array = value.detach().to(torch.float32).numpy() + if not np.isfinite(array).all(): + raise ValueError(f"{source}: tensor {name} holds a value that is not finite in float32") + arrays[name] = array + return arrays + + +def as_engine_weights(values, dtype) -> np.ndarray: + """``values`` as the engine stores them; a value that does not fit that dtype is refused. + + A finite float32 weight can still overflow fp16 (100000 becomes infinity). + """ + with np.errstate(over="ignore", invalid="ignore"): + array = np.ascontiguousarray(values, dtype=dtype) + if not np.isfinite(array).all(): + raise ValueError(f"a DPT weight is not finite in {np.dtype(dtype).name}; build fp32") + return array + + +def load_tensors(model_dir: str | Path) -> dict[str, np.ndarray]: + """The checkpoint's state dict as float32 arrays. + + The published repository ships only a PyTorch pickle. ``weights_only=True`` + restricts unpickling to tensors and plain containers. + """ + try: + import torch + except ImportError as error: + raise RuntimeError("dpt requires torch in the build environment") from error + from packaging.version import Version + + installed = str(torch.__version__).split("+")[0] + if Version(installed) < Version(MIN_TORCH): + raise RuntimeError(f"dpt reads checkpoints with torch {MIN_TORCH} or later; found {installed}") + path = Path(model_dir) / CHECKPOINT + if not path.is_file(): + raise FileNotFoundError(f"dpt requires the checkpoint file {path}") + state = torch.load(str(path), map_location="cpu", weights_only=True) + return tensor_arrays(state, str(path)) diff --git a/families/dpt/config.py b/families/dpt/config.py new file mode 100644 index 0000000000..461f5e9947 --- /dev/null +++ b/families/dpt/config.py @@ -0,0 +1,578 @@ +# 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']}") + # 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( + 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 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: + 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..53c0227739 --- /dev/null +++ b/families/dpt/model.py @@ -0,0 +1,434 @@ +# 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 itertools +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", (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)) + + 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, 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)) + + 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..c8b880fd0d --- /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.10.0 +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 0000000000..095c03620f Binary files /dev/null and b/families/dpt/tests/data/test_img.jpeg differ diff --git a/families/dpt/tests/manifests/dpt-hybrid-midas-fp16.json b/families/dpt/tests/manifests/dpt-hybrid-midas-fp16.json new file mode 100644 index 0000000000..67b524c6c0 --- /dev/null +++ b/families/dpt/tests/manifests/dpt-hybrid-midas-fp16.json @@ -0,0 +1,32 @@ +{ + "name": "dpt-hybrid-midas-fp16", + "hf_id": "Intel/dpt-hybrid-midas", + "hf_revision": "11eaf7a1cf4bd70740697dbc216f98980c0aeb03", + "bundle": "dpt-hybrid-midas-fp16.bundle", + "family": "dpt", + "task": "monocular_depth", + "precision": "fp16", + "trust_remote_code": false, + "testcases": [ + { + "name": "dpt-hybrid-midas-fp16-landscape", + "premerge": false, + "test_image": "test_img.jpeg", + "transpose": false, + "min_depth_correlation": 0.99999, + "max_depth_relative_error": 0.05, + "max_mean_depth_relative_error": 0.002 + }, + { + "name": "dpt-hybrid-midas-fp16-portrait", + "premerge": false, + "test_image": "test_img.jpeg", + "transpose": true, + "min_depth_correlation": 0.99999, + "max_depth_relative_error": 0.05, + "max_mean_depth_relative_error": 0.002 + } + ], + "tensor_parallel_size": 1, + "max_sequence_length": 1 +} diff --git a/families/dpt/tests/manifests/dpt-hybrid-midas.json b/families/dpt/tests/manifests/dpt-hybrid-midas.json new file mode 100644 index 0000000000..ce422adc04 --- /dev/null +++ b/families/dpt/tests/manifests/dpt-hybrid-midas.json @@ -0,0 +1,32 @@ +{ + "name": "dpt-hybrid-midas", + "hf_id": "Intel/dpt-hybrid-midas", + "hf_revision": "11eaf7a1cf4bd70740697dbc216f98980c0aeb03", + "bundle": "dpt-hybrid-midas.bundle", + "family": "dpt", + "task": "monocular_depth", + "precision": "fp32", + "trust_remote_code": false, + "testcases": [ + { + "name": "dpt-hybrid-midas-landscape", + "premerge": true, + "test_image": "test_img.jpeg", + "transpose": false, + "min_depth_correlation": 0.999999, + "max_depth_relative_error": 0.0001, + "max_mean_depth_relative_error": 0.00001 + }, + { + "name": "dpt-hybrid-midas-portrait", + "premerge": false, + "test_image": "test_img.jpeg", + "transpose": true, + "min_depth_correlation": 0.999999, + "max_depth_relative_error": 0.0001, + "max_mean_depth_relative_error": 0.00001 + } + ], + "tensor_parallel_size": 1, + "max_sequence_length": 1 +} diff --git a/families/dpt/tests/test_e2e.py b/families/dpt/tests/test_e2e.py new file mode 100644 index 0000000000..16e1eb1528 --- /dev/null +++ b/families/dpt/tests/test_e2e.py @@ -0,0 +1,467 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +"""Direct build, native-runtime and official-reference E2E for DPT. + +The reference is the checkpoint's own Transformers pipeline in float32 on the +CPU: ``DPTImageProcessor`` (the PIL processor the model card uses), +``DPTForDepthEstimation`` and ``post_process_depth_estimation`` onto the +input size. The test image is written as PNG first so that the native CLI and +the reference decode the same 8-bit pixels. +""" + +from __future__ import annotations + +import json +import math +import os +import re +import subprocess +from pathlib import Path + +import pytest + +from tensorrt_model_connect import BuildRequest, build +from tools.e2e_evidence import evidence_stage, mark_loaded, record_evidence + +FAMILY = "dpt" +TASKS = frozenset({"monocular_depth"}) +PRECISIONS = frozenset({"fp32", "fp16"}) +TEST_ROOT = Path(__file__).resolve().parent +MANIFEST_ROOT = TEST_ROOT / "manifests" +MODEL_DIR_OVERRIDE = f"TRTMC_{FAMILY.upper()}_MODEL_DIR" +THRESHOLDS = ("min_depth_correlation", "max_depth_relative_error", + "max_mean_depth_relative_error") +# The one item of a testcase-only selection that names no case of this family; it +# checks, once the session is collected, that another collected family owns them. +ELSEWHERE = "selected-elsewhere" + + +def _require(condition: bool, path: Path, message: str) -> 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..7b1533d8a7 --- /dev/null +++ b/families/dpt/tests/test_support.py @@ -0,0 +1,757 @@ +# 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 re + +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) + # 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"]) +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) + 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(): + 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)