From 8b186d77a20dad4abc8d9ab8b2bf5a53ceed8ddc Mon Sep 17 00:00:00 2001 From: Will Guo Date: Fri, 13 Nov 2026 05:03:12 -0800 Subject: [PATCH 1/2] feat(zoedepth): add native metric depth Signed-off-by: Will Guo --- families/zoedepth/README.md | 39 ++ families/zoedepth/__init__.py | 3 + families/zoedepth/model.py | 484 ++++++++++++++++++ families/zoedepth/requirements.txt | 2 + families/zoedepth/runtime/CMakeLists.txt | 17 + families/zoedepth/runtime/pipeline.cpp | 31 ++ families/zoedepth/runtime/pipeline.h | 17 + families/zoedepth/runtime/plugin.cpp | 28 + families/zoedepth/runtime/preprocess.cpp | 100 ++++ families/zoedepth/runtime/preprocess.h | 12 + families/zoedepth/support.py | 13 + families/zoedepth/tests/__init__.py | 2 + families/zoedepth/tests/cpp/e2e_consumer.cpp | 57 +++ .../tests/cpp/preprocess_consumer.cpp | 30 ++ .../tests/manifests/zoedepth-nyu-kitti.json | 23 + families/zoedepth/tests/math_check.py | 98 ++++ families/zoedepth/tests/requirements.txt | 3 + families/zoedepth/tests/test_e2e.py | 258 ++++++++++ families/zoedepth/tests/test_model.py | 32 ++ families/zoedepth/tests/test_support.py | 14 + 20 files changed, 1263 insertions(+) create mode 100644 families/zoedepth/README.md create mode 100644 families/zoedepth/__init__.py create mode 100644 families/zoedepth/model.py create mode 100644 families/zoedepth/requirements.txt create mode 100644 families/zoedepth/runtime/CMakeLists.txt create mode 100644 families/zoedepth/runtime/pipeline.cpp create mode 100644 families/zoedepth/runtime/pipeline.h create mode 100644 families/zoedepth/runtime/plugin.cpp create mode 100644 families/zoedepth/runtime/preprocess.cpp create mode 100644 families/zoedepth/runtime/preprocess.h create mode 100644 families/zoedepth/support.py create mode 100644 families/zoedepth/tests/__init__.py create mode 100644 families/zoedepth/tests/cpp/e2e_consumer.cpp create mode 100644 families/zoedepth/tests/cpp/preprocess_consumer.cpp create mode 100644 families/zoedepth/tests/manifests/zoedepth-nyu-kitti.json create mode 100644 families/zoedepth/tests/math_check.py create mode 100644 families/zoedepth/tests/requirements.txt create mode 100644 families/zoedepth/tests/test_e2e.py create mode 100644 families/zoedepth/tests/test_model.py create mode 100644 families/zoedepth/tests/test_support.py diff --git a/families/zoedepth/README.md b/families/zoedepth/README.md new file mode 100644 index 0000000000..ec3f00b846 --- /dev/null +++ b/families/zoedepth/README.md @@ -0,0 +1,39 @@ +# ZoeDepth NYU/KITTI + +This owner builds `Intel/zoedepth-nyu-kitti` revision +`f364d4c7936e91f465abba182208dd68142bf0ca` for FP32 monocular metric depth. +It implements the BEiT backbone, relative-position-table interpolation, DPT +readout/fusion, transformer domain classifier, both unnormalized bin-attractor +heads and conditional log-binomial depth distribution using TensorRT math. +The classifier chooses the NYU or KITTI head independently for each image. +The native family implements the existing `IMonocularDepth` interface and the +`trtmc depth` CLI. It does not synthesize camera intrinsics or 3D points. + +The initial profile has batch one and processed RGB dimensions 384×512. +Preprocessing retains the checkpoint's reflect padding, aspect-preserving +nearest-multiple-of-32 geometry, bilinear resize with aligned corners, and +normalization. Images whose published preprocessing produces another shape +are rejected. Typical 384×512 and 480×640 images fit the profile. Public input +pixels are HWC floats in [0,1]. Output is a metric depth map at the original +image resolution, with the upstream bicubic resize and padding removal. +Inference has no Python or PyTorch dependency. + +```bash +trtmc build /path/to/zoedepth-nyu-kitti -o model.bundle \ + --family zoedepth --task monocular_depth --precision fp32 +trtmc depth model.bundle --runtime-root /path/to/runtime --image image.png +``` + +Validation uses the unmodified Transformers 5.3.0 FP32 eager reference. +Small rectangular models compare BEiT taps, fusion, classifier logits and +both routing choices at 5e-5 absolute/relative tolerance. Native pre/post +processing is checked independently against the published image processor. +Real checkpoint tests compare every output pixel for multiple images, +different source resolutions, repeated calls, rejection recovery and CLI +execution at the manifest's fixed tolerances. + +```bash +PYTHONPATH=core/builder:apps/benchmark:. python -m tools.model_ci validate +PYTHONPATH=core/builder:apps/benchmark:. python -m pytest \ + families/zoedepth/tests --e2e-model zoedepth -q +``` diff --git a/families/zoedepth/__init__.py b/families/zoedepth/__init__.py new file mode 100644 index 0000000000..aa748f40bb --- /dev/null +++ b/families/zoedepth/__init__.py @@ -0,0 +1,3 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +"""ZoeDepth metric monocular depth estimation.""" diff --git a/families/zoedepth/model.py b/families/zoedepth/model.py new file mode 100644 index 0000000000..a0e51d0c8b --- /dev/null +++ b/families/zoedepth/model.py @@ -0,0 +1,484 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +"""BEiT, DPT fusion, domain classifier and both unnormalized metric heads.""" + +import json +import math +from pathlib import Path + +import numpy as np +from safetensors.numpy import load_file +import tensorrt as trt + + +class Graph: + def __init__(self, network, weights): + self.n = network + self.w = weights + self.storage = [] + + def weight(self, name): + if name not in self.w: + raise ValueError(f"ZoeDepth checkpoint is missing {name}") + value = np.ascontiguousarray(self.w[name], dtype=np.float32) + if not np.isfinite(value).all(): + raise ValueError(f"ZoeDepth checkpoint contains nonfinite {name}") + self.storage.append(value) + return value + + def constant(self, value, dtype=np.float32): + value = np.asarray(value, dtype=dtype) + if not value.ndim: + value = value.reshape(1) + value = np.ascontiguousarray(value) + self.storage.append(value) + return self.n.add_constant(value.shape, value).get_output(0) + + def binary(self, x, y, op): + if not isinstance(y, trt.ITensor): + y = self.constant(np.full((1,) * len(x.shape), y, dtype=np.float32)) + return self.n.add_elementwise(x, y, op).get_output(0) + + def add(self, x, y): + return self.binary(x, y, trt.ElementWiseOperation.SUM) + + def sub(self, x, y): + return self.binary(x, y, trt.ElementWiseOperation.SUB) + + def mul(self, x, y): + return self.binary(x, y, trt.ElementWiseOperation.PROD) + + def div(self, x, y): + return self.binary(x, y, trt.ElementWiseOperation.DIV) + + def unary(self, x, op): + return self.n.add_unary(x, op).get_output(0) + + def activate(self, x, kind): + return self.n.add_activation(x, kind).get_output(0) + + def relu(self, x): + return self.activate(x, trt.ActivationType.RELU) + + def gelu(self, x): + return self.activate(x, trt.ActivationType.GELU_ERF) + + def softplus(self, x): + layer = self.n.add_activation(x, trt.ActivationType.SOFTPLUS) + layer.alpha = 1.0 + layer.beta = 1.0 + return layer.get_output(0) + + def reshape(self, x, shape, transpose=None): + layer = self.n.add_shuffle(x) + layer.reshape_dims = tuple(shape) + if transpose is not None: + layer.second_transpose = tuple(transpose) + return layer.get_output(0) + + def transpose(self, x, order): + layer = self.n.add_shuffle(x) + layer.first_transpose = tuple(order) + return layer.get_output(0) + + def cat(self, values, axis): + layer = self.n.add_concatenation(values) + layer.axis = axis + return layer.get_output(0) + + def slice(self, x, start, size): + return self.n.add_slice(x, tuple(start), tuple(size), (1,) * len(size)).get_output(0) + + def linear(self, x, name): + weight = self.weight(name + ".weight") + w = self.constant(weight.reshape((1,) * (len(x.shape) - 2) + weight.shape)) + y = self.n.add_matrix_multiply( + x, trt.MatrixOperation.NONE, w, trt.MatrixOperation.TRANSPOSE + ).get_output(0) + if name + ".bias" in self.w: + y = self.add( + y, + self.constant( + self.weight(name + ".bias").reshape((1,) * (len(x.shape) - 1) + (-1,)) + ), + ) + return y + + def norm(self, x, name, eps): + shape = (1,) * (len(x.shape) - 1) + (-1,) + layer = self.n.add_normalization( + x, + self.constant(self.weight(name + ".weight").reshape(shape)), + self.constant(self.weight(name + ".bias").reshape(shape)), + 1 << (len(x.shape) - 1), + ) + layer.epsilon = eps + return layer.get_output(0) + + def conv(self, x, name, stride=1, padding=0, deconv=False): + w = self.weight(name + ".weight") + bias = self.weight(name + ".bias") if name + ".bias" in self.w else trt.Weights() + create = self.n.add_deconvolution_nd if deconv else self.n.add_convolution_nd + layer = create(x, w.shape[1] if deconv else w.shape[0], w.shape[2:], w, bias) + layer.stride_nd = (stride, stride) + layer.padding_nd = (padding, padding) + return layer.get_output(0) + + def resize(self, x, size, align=True): + layer = self.n.add_resize(x) + layer.shape = tuple(x.shape[:-2]) + tuple(size) + layer.resize_mode = trt.InterpolationMode.LINEAR + layer.coordinate_transformation = ( + trt.ResizeCoordinateTransformation.ALIGN_CORNERS + if align + else trt.ResizeCoordinateTransformation.HALF_PIXEL + ) + return layer.get_output(0) + + def softmax(self, x, axis): + layer = self.n.add_softmax(x) + layer.axes = 1 << axis + return layer.get_output(0) + + def reduce(self, x, op, axis): + return self.n.add_reduce(x, op, 1 << axis, True).get_output(0) + + def attention(self, x, prefix, heads, *, beit=False, bias=None): + length, hidden = int(x.shape[1]), int(x.shape[2]) + q, k, v = [ + self.reshape( + self.linear(x, prefix + "." + kind), + (1, length, heads, hidden // heads), + (0, 2, 1, 3), + ) + for kind in ("query", "key", "value") + ] + scores = self.n.add_matrix_multiply( + q, trt.MatrixOperation.NONE, k, trt.MatrixOperation.TRANSPOSE + ).get_output(0) + scores = self.div(scores, math.sqrt(hidden // heads)) + if bias is not None: + scores = self.add(scores, bias) + y = self.n.add_matrix_multiply( + self.softmax(scores, 3), trt.MatrixOperation.NONE, v, trt.MatrixOperation.NONE + ).get_output(0) + y = self.reshape(self.transpose(y, (0, 2, 1, 3)), (1, length, hidden)) + return y if beit else self.linear(y, prefix + ".out_proj") + + +def relative_bias(g, name, old_grid, grid): + table = g.weight(name + ".relative_position_bias_table") + oh, ow = old_grid + height, width = grid + # The upstream table uses (old_width, old_height) in precisely this order. + spatial = table[:-3].reshape(1, 2 * ow - 1, 2 * oh - 1, -1).transpose(0, 3, 1, 2) + spatial = g.resize(g.constant(spatial), (2 * height - 1, 2 * width - 1), False) + spatial = g.reshape(g.transpose(spatial, (0, 2, 3, 1)), (-1, table.shape[1])) + table_tensor = g.cat([spatial, g.constant(table[-3:])], 0) + yy, xx = np.meshgrid(np.arange(height), np.arange(width), indexing="ij") + coords = np.stack([yy.reshape(-1), xx.reshape(-1)]) + delta = coords[:, :, None] - coords[:, None, :] + indices = np.empty((height * width + 1,) * 2, dtype=np.int32) + indices[1:, 1:] = (delta[0] + height - 1) * (2 * width - 1) + delta[1] + width - 1 + total = (2 * height - 1) * (2 * width - 1) + indices[0, :] = total + indices[:, 0] = total + 1 + indices[0, 0] = total + 2 + bias = g.n.add_gather(table_tensor, g.constant(indices, np.int32), 0).get_output(0) + return g.reshape( + g.transpose(bias, (2, 0, 1)), (1, table.shape[1], height * width + 1, height * width + 1) + ) + + +def backbone(g, image, config): + c = config["backbone_config"] + patch = c.get("patch_size", 16) + hidden, heads = c["hidden_size"], c["num_attention_heads"] + grid = (int(image.shape[2]) // patch, int(image.shape[3]) // patch) + length = grid[0] * grid[1] + x = g.conv(image, "backbone.embeddings.patch_embeddings.projection", patch) + x = g.reshape(x, (1, hidden, length), (0, 2, 1)) + x = g.cat([g.constant(g.weight("backbone.embeddings.cls_token")), x], 1) + old_size = c.get("image_size", 224) + old_size = [old_size, old_size] if isinstance(old_size, int) else old_size + old_grid = (old_size[0] // patch, old_size[1] // patch) + taps = [] + for index in range(c["num_hidden_layers"]): + p = f"backbone.encoder.layer.{index}" + normed = g.norm(x, p + ".layernorm_before", c.get("layer_norm_eps", 1e-12)) + bias = relative_bias(g, p + ".attention.attention.relative_position_bias", old_grid, grid) + y = g.attention(normed, p + ".attention.attention", heads, beit=True, bias=bias) + y = g.linear(y, p + ".attention.output.dense") + y = g.mul(y, g.constant(g.weight(p + ".lambda_1").reshape(1, 1, hidden))) + x = g.add(x, y) + y = g.norm(x, p + ".layernorm_after", c.get("layer_norm_eps", 1e-12)) + y = g.linear(g.gelu(g.linear(y, p + ".intermediate.dense")), p + ".output.dense") + x = g.add(x, g.mul(y, g.constant(g.weight(p + ".lambda_2").reshape(1, 1, hidden)))) + if index + 1 in c["out_indices"]: + taps.append(x) + return taps, grid + + +def residual(g, x, p): + y = g.conv(g.relu(x), p + ".convolution1", padding=1) + return g.add(x, g.conv(g.relu(y), p + ".convolution2", padding=1)) + + +def neck(g, taps, grid, config): + features = [] + for i, (x, factor) in enumerate(zip(taps, config["reassemble_factors"])): + length, hidden = grid[0] * grid[1], int(x.shape[-1]) + cls = g.slice(x, (0, 0, 0), (1, 1, hidden)) + # A zero-stride slice repeats the class token for each image patch. + repeat = g.n.add_slice(cls, (0, 0, 0), (1, length, hidden), (1, 0, 1)).get_output(0) + x = g.slice(x, (0, 1, 0), (1, length, hidden)) + x = g.gelu(g.linear(g.cat([x, repeat], 2), f"neck.reassemble_stage.readout_projects.{i}.0")) + x = g.reshape(g.transpose(x, (0, 2, 1)), (1, hidden, *grid)) + p = f"neck.reassemble_stage.layers.{i}" + x = g.conv(x, p + ".projection") + if factor > 1: + x = g.conv(x, p + ".resize", int(factor), deconv=True) + elif factor < 1: + x = g.conv(x, p + ".resize", int(1 / factor), 1) + features.append(g.conv(x, f"neck.convs.{i}", padding=1)) + fused = [] + x = None + for i, feature in enumerate(reversed(features)): + p = f"neck.fusion_stage.layers.{i}" + if x is None: + x = feature + else: + feature = g.resize(feature, x.shape[-2:], False) + x = g.add(x, residual(g, feature, p + ".residual_layer1")) + x = residual(g, x, p + ".residual_layer2") + x = g.resize(x, (int(x.shape[-2]) * 2, int(x.shape[-1]) * 2)) + x = g.conv(x, p + ".projection") + fused.append(x) + return fused, features[-1] + + +def projector(g, x, p): + return g.conv(g.relu(g.conv(x, p + ".conv1")), p + ".conv2") + + +def classifier(g, x, config): + p = "metric_head.patch_transformer" + x = g.conv(x, p + ".embedding_convPxP") + hidden, height, width = map(int, x.shape[1:]) + x = g.reshape(x, (1, hidden, height * width), (0, 2, 1)) + x = g.cat([g.constant(np.zeros((1, 1, hidden), np.float32)), x], 1) + pos = np.arange(height * width + 1, dtype=np.float32)[:, None] + index = np.arange(0, hidden, 2, dtype=np.float32)[None, :] + phase = pos * np.exp(index * (-np.log(np.float32(10000)) / np.float32(hidden))) + encoding = np.concatenate([np.sin(phase), np.cos(phase)], axis=1)[None] + x = g.add(x, g.constant(encoding)) + for i in range(config["num_patch_transformer_layers"]): + q = p + f".transformer_encoder.{i}" + y = g.attention(x, q + ".self_attn", config["patch_transformer_num_attention_heads"]) + x = g.norm(g.add(x, y), q + ".norm1", 1e-5) + y = g.linear(g.relu(g.linear(x, q + ".linear1")), q + ".linear2") + x = g.norm(g.add(x, y), q + ".norm2", 1e-5) + x = g.reshape(g.slice(x, (0, 0, 0), (1, 1, hidden)), (1, hidden)) + return g.linear( + g.relu(g.linear(x, "metric_head.mlp_classifier.linear1")), + "metric_head.mlp_classifier.linear2", + ) + + +def metric_branch(g, bottleneck, features, last, bin_embeddings, name, config): + p = "metric_head" + center = g.softplus(projector(g, bottleneck, p + f".seed_bin_regressors.{name}")) + previous = bin_embeddings[0] + for i, (feature, embedding) in enumerate(zip(features, bin_embeddings[1:])): + a = p + f".attractors.{name}.{i}" + x = g.add(embedding, g.resize(previous, embedding.shape[-2:])) + attractors = g.softplus(projector(g, x, a)) + center = g.resize(center, embedding.shape[-2:]) + delta = g.constant(np.zeros(tuple(center.shape), np.float32)) + # MultipleMetricDepthEstimationHeads supplies its configured count as + # n_bins. The unnormalized module retains n_attractors=16 in every + # stage; its checkpoint convolution is the authoritative point count. + point_count = int(attractors.shape[1]) + for j in range(point_count): + point = g.slice(attractors, (0, j, 0, 0), (1, 1, *attractors.shape[-2:])) + diff = g.sub(point, center) + # The published forward calls inv_attractor with its defaults, not + # the unused attractor_alpha/gamma attributes on the module. + step = g.div(diff, g.add(g.mul(g.mul(diff, diff), 300.0), 1.0)) + delta = g.add(delta, step) + center = g.add(center, g.div(delta, point_count)) + previous = embedding + center = g.resize(center, last.shape[-2:]) + embedding = g.resize(previous, last.shape[-2:]) + q = p + f".conditional_log_binomial.{name}.mlp" + x = g.softplus(g.conv(g.gelu(g.conv(g.cat([last, embedding], 1), q + ".0")), q + ".2")) + size = tuple(x.shape[-2:]) + vals = [g.slice(x, (0, i, 0, 0), (1, 1, *size)) for i in range(4)] + vals = [g.add(v, 1e-4) for v in vals] + probability = g.div(vals[0], g.add(vals[0], vals[1])) + temp = g.add( + g.mul(g.div(vals[2], g.add(vals[2], vals[3])), config["max_temp"] - config["min_temp"]), + config["min_temp"], + ) + complement = g.sub(g.add(g.mul(probability, 0.0), 1.0), probability) + probability = g.binary(probability, 1e-4, trt.ElementWiseOperation.MAX) + complement = g.binary(complement, 1e-4, trt.ElementWiseOperation.MAX) + bins = int(center.shape[1]) + k = np.arange(bins, dtype=np.float32) + n = np.float32(bins - 1) + nn, kk = n + np.float32(1e-7), k + np.float32(1e-7) + log_binom = nn * np.log(nn) - kk * np.log(kk) - (nn - kk) * np.log(nn - kk + np.float32(1e-7)) + scores = g.add( + g.constant(log_binom.reshape(1, bins, 1, 1)), + g.mul(g.constant(k.reshape(1, bins, 1, 1)), g.unary(probability, trt.UnaryOperation.LOG)), + ) + scores = g.add( + scores, + g.mul( + g.constant((n - k).reshape(1, bins, 1, 1)), g.unary(complement, trt.UnaryOperation.LOG) + ), + ) + weights = g.softmax(g.div(scores, temp), 1) + return g.reduce(g.mul(weights, center), trt.ReduceOperation.SUM, 1) + + +def network_outputs(g, image, config): + taps, grid = backbone(g, image, config) + features, bottleneck = neck(g, taps, grid, config) + last = g.conv(features[-1], "relative_head.conv1", padding=1) + last = g.resize(last, (int(last.shape[-2]) * 2, int(last.shape[-1]) * 2)) + last = g.relu(g.conv(last, "relative_head.conv2", padding=1)) + bottleneck = g.conv(bottleneck, "metric_head.conv2") + logits = classifier(g, bottleneck, config) + embeddings = [projector(g, bottleneck, "metric_head.seed_projector")] + embeddings += [projector(g, f, f"metric_head.projectors.{i}") for i, f in enumerate(features)] + names = [c["name"] for c in config["bin_configurations"]] + depths = [ + metric_branch(g, bottleneck, features, last, embeddings, name, config) for name in names + ] + choose_second = g.binary( + g.slice(logits, (0, 1), (1, 1)), + g.slice(logits, (0, 0), (1, 1)), + trt.ElementWiseOperation.GREATER, + ) + choose_second = g.reshape(choose_second, (1, 1, 1, 1)) + depth = g.n.add_select(choose_second, depths[1], depths[0]).get_output(0) + outputs = {"predicted_depth": depth, "domain_logits": logits, "bottleneck": bottleneck} + outputs.update({f"backbone_{i}": x for i, x in enumerate(taps)}) + outputs.update({f"fusion_{i}": x for i, x in enumerate(features)}) + outputs.update({f"metric_{name}": x for name, x in zip(names, depths)}) + return outputs + + +def build_engine(weights, config, height, width, *, debug=False, verbose=False): + 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)) + options = builder.create_builder_config() + options.builder_optimization_level = 3 + options.clear_flag(trt.BuilderFlag.TF32) + graph = Graph(network, weights) + image = network.add_input("pixel_values", trt.float32, (1, 3, height, width)) + outputs = network_outputs(graph, image, config) + for name, value in outputs.items(): + if debug or name in {"predicted_depth", "domain_logits"}: + value.name = name + network.mark_output(value) + plan = builder.build_serialized_network(network, options) + if plan is None: + raise RuntimeError("ZoeDepth TensorRT engine build failed") + return bytes(plan) + + +def validate(config, processor): + c = config.get("backbone_config", {}) + if config.get("model_type") != "zoedepth" or c.get("model_type") != "beit": + raise ValueError("zoedepth requires its BEiT backbone") + if ( + not c.get("use_relative_position_bias") + or c.get("use_shared_relative_position_bias", False) + or c.get("use_absolute_position_embeddings", False) + or c.get("add_fpn", False) + or c.get("reshape_hidden_states", True) + ): + raise ValueError("unsupported ZoeDepth BEiT embedding or feature topology") + if c.get("layer_scale_init_value", 0.1) <= 0 or len(c.get("out_indices", [])) != 4: + raise ValueError("zoedepth requires four scaled BEiT feature taps") + if ( + config.get("readout_type") != "project" + or config.get("bin_centers_type") != "softplus" + or config.get("attractor_kind") != "mean" + or config.get("use_batch_norm_in_fusion_residual", False) + or config.get("add_projection", False) + or config.get("hidden_act") != "gelu" + ): + raise ValueError("unsupported ZoeDepth metric topology") + if ( + config.get("reassemble_factors") != [4, 2, 1, 0.5] + or config.get("num_patch_transformer_layers") != 4 + or config.get("patch_transformer_hidden_size") != 128 + ): + raise ValueError("unsupported ZoeDepth fusion or domain classifier") + bins = config.get("bin_configurations", []) + if ( + len(bins) != 2 + or [b["name"] for b in bins] != ["nyu", "kitti"] + or bins[0]["n_bins"] != bins[1]["n_bins"] + ): + raise ValueError("zoedepth requires matching NYU and KITTI bin counts") + expected = { + "do_pad": True, + "do_resize": True, + "do_rescale": True, + "do_normalize": True, + "keep_aspect_ratio": True, + "ensure_multiple_of": 32, + "resample": 2, + "image_mean": [0.5] * 3, + "image_std": [0.5] * 3, + "size": {"height": 384, "width": 512}, + } + if any(processor.get(k) != v for k, v in expected.items()) or not math.isclose( + processor.get("rescale_factor", 0), 1 / 255, rel_tol=1e-12 + ): + raise ValueError("unsupported ZoeDepth image preprocessing") + + +def build(request, writer): + if request.dynamic_kv_cache: + raise NotImplementedError("zoedepth does not support dynamic_kv_cache") + if ( + request.task != "monocular_depth" + or request.backend not in {"trt", "trt_rtx"} + or request.precision != "fp32" + ): + raise ValueError("zoedepth supports FP32 monocular_depth on TensorRT") + if ( + request.max_batch_size != 1 + or request.tensor_parallel_size != 1 + or request.context_parallel_size != 1 + ): + raise ValueError("zoedepth supports batch=1 and no parallel sharding") + if ( + request.max_sequence_length not in {None, 1} + or request.mtp_seq_len is not None + or request.video_num_frames is not None + or request.fp32_layers + or request.quantization not in {None, "none"} + ): + raise ValueError("zoedepth does not support sequence, cache, video or quantization options") + height, width = request.image_height or 384, request.image_width or 512 + if height != 384 or width != 512: + raise ValueError("zoedepth builds the 384x512 processed-image profile") + root = Path(request.model_dir) + config = json.loads((root / "config.json").read_text()) + processor = json.loads((root / "preprocessor_config.json").read_text()) + validate(config, processor) + weights = load_file(root / "model.safetensors") + plan = build_engine(weights, config, height, width, verbose=request.verbose) + writer.set_header(family="zoedepth", task=request.task, backend=request.backend) + writer.add_bytes("engine.plan", plan) + writer.add_json( + "runtime.json", + {"schema_version": 1, "height": height, "width": width, "processor": processor}, + ) diff --git a/families/zoedepth/requirements.txt b/families/zoedepth/requirements.txt new file mode 100644 index 0000000000..97d9923cb8 --- /dev/null +++ b/families/zoedepth/requirements.txt @@ -0,0 +1,2 @@ +numpy>=1.26 +safetensors>=0.5 diff --git a/families/zoedepth/runtime/CMakeLists.txt b/families/zoedepth/runtime/CMakeLists.txt new file mode 100644 index 0000000000..09a17e43fd --- /dev/null +++ b/families/zoedepth/runtime/CMakeLists.txt @@ -0,0 +1,17 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +add_library(trtmc_model_zoedepth SHARED pipeline.cpp plugin.cpp preprocess.cpp) +target_include_directories(trtmc_model_zoedepth PRIVATE ${PROJECT_SOURCE_DIR} ${PROJECT_SOURCE_DIR}/core/runtime/include) +target_link_libraries(trtmc_model_zoedepth PRIVATE trtmc_core nlohmann_json::nlohmann_json) +target_compile_options(trtmc_model_zoedepth PRIVATE -Wall -Wextra -Wpedantic -ffp-contract=off) +set_target_properties(trtmc_model_zoedepth PROPERTIES LIBRARY_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}" BUILD_RPATH "$ORIGIN" INSTALL_RPATH "$ORIGIN") +install(TARGETS trtmc_model_zoedepth LIBRARY DESTINATION ${CMAKE_INSTALL_LIBDIR}) +if(TRTMC_BUILD_TESTS) + add_executable(zoedepth_e2e ${PROJECT_SOURCE_DIR}/families/zoedepth/tests/cpp/e2e_consumer.cpp) + target_link_libraries(zoedepth_e2e PRIVATE trtmc_runtime nlohmann_json::nlohmann_json) + set_target_properties(zoedepth_e2e PROPERTIES RUNTIME_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}") + add_executable(zoedepth_preprocess ${PROJECT_SOURCE_DIR}/families/zoedepth/tests/cpp/preprocess_consumer.cpp preprocess.cpp) + target_include_directories(zoedepth_preprocess PRIVATE ${PROJECT_SOURCE_DIR}) + target_compile_options(zoedepth_preprocess PRIVATE -ffp-contract=off) + set_target_properties(zoedepth_preprocess PROPERTIES RUNTIME_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}") +endif() diff --git a/families/zoedepth/runtime/pipeline.cpp b/families/zoedepth/runtime/pipeline.cpp new file mode 100644 index 0000000000..e512a1af2b --- /dev/null +++ b/families/zoedepth/runtime/pipeline.cpp @@ -0,0 +1,31 @@ +/* + * SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. + * SPDX-License-Identifier: Apache-2.0 + */ +#include "families/zoedepth/runtime/pipeline.h" +#include "families/zoedepth/runtime/preprocess.h" +#include +#include +#include + +namespace trtmc::zoedepth { +Pipeline::Pipeline(std::unique_ptr model) : model_(std::move(model)) { + if (!model_ || !model_->ok()) throw std::invalid_argument("zoedepth invalid engine"); +} +MonocularDepthResult Pipeline::estimate_depth(const float* pixels, int height, int width) { + auto values = preprocess(pixels, height, width); + Tensor input; input.data = values.data(); input.dtype = DType::kFloat32; + input.shape = {1, 3, 384, 512}; + const auto outputs = model_->forward({{"pixel_values", input}}); + const auto found = outputs.find("predicted_depth"); + if (found == outputs.end() || !found->second.data || found->second.dtype != DType::kFloat32 || + found->second.shape != std::vector{1, 1, 384, 512}) + throw std::runtime_error("zoedepth invalid predicted_depth output"); + const auto* depth = static_cast(found->second.data); + if (!std::all_of(depth, depth + 384 * 512, [](float x) { return std::isfinite(x); })) + throw std::runtime_error("zoedepth nonfinite engine output"); + MonocularDepthResult result; + result.depth = postprocess(depth, height, width); result.height = height; result.width = width; + return result; +} +} // namespace trtmc::zoedepth diff --git a/families/zoedepth/runtime/pipeline.h b/families/zoedepth/runtime/pipeline.h new file mode 100644 index 0000000000..d7801d4056 --- /dev/null +++ b/families/zoedepth/runtime/pipeline.h @@ -0,0 +1,17 @@ +/* + * SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. + * SPDX-License-Identifier: Apache-2.0 + */ +#pragma once +#include "trtmc/runtime/trt_module.h" +#include "trtmc/task.h" + +namespace trtmc::zoedepth { +class Pipeline final : public IMonocularDepth { + public: + explicit Pipeline(std::unique_ptr model); + MonocularDepthResult estimate_depth(const float*, std::int32_t, std::int32_t) override; + private: + std::unique_ptr model_; +}; +} // namespace trtmc::zoedepth diff --git a/families/zoedepth/runtime/plugin.cpp b/families/zoedepth/runtime/plugin.cpp new file mode 100644 index 0000000000..c3025f832d --- /dev/null +++ b/families/zoedepth/runtime/plugin.cpp @@ -0,0 +1,28 @@ +/* + * SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. + * SPDX-License-Identifier: Apache-2.0 + */ +#include "families/zoedepth/runtime/pipeline.h" +#include "trtmc/runtime/family_factory.h" +#include "trtmc/runtime/trt_backend.h" +#include +#include + +extern "C" trtmc::ITask* trtmc_create_family(const trtmc::FamilyContext& context) { + if (context.kv_cache_size_bytes != 0) + throw std::invalid_argument("zoedepth does not support --kv-cache-size"); + if (context.reader.info().task != "monocular_depth") + throw std::invalid_argument("zoedepth supports monocular_depth"); + const auto value = nlohmann::json::parse(context.reader.read_section("runtime.json")); + if (value.at("schema_version") != 1 || value.at("height") != 384 || value.at("width") != 512) + throw std::invalid_argument("zoedepth unsupported runtime geometry"); + const auto& p = value.at("processor"); + if (p.at("size") != nlohmann::json{{"height", 384}, {"width", 512}} || + p.at("do_pad") != true || p.at("keep_aspect_ratio") != true || + p.at("ensure_multiple_of") != 32 || p.at("resample") != 2 || + p.at("image_mean") != nlohmann::json::array({0.5, 0.5, 0.5}) || + p.at("image_std") != nlohmann::json::array({0.5, 0.5, 0.5})) + throw std::invalid_argument("zoedepth unsupported runtime preprocessing"); + const auto plan = context.reader.read_section("engine.plan"); + return new trtmc::zoedepth::Pipeline(context.backend.create_module(plan.data(), plan.size(), {})); +} diff --git a/families/zoedepth/runtime/preprocess.cpp b/families/zoedepth/runtime/preprocess.cpp new file mode 100644 index 0000000000..a9e49b2800 --- /dev/null +++ b/families/zoedepth/runtime/preprocess.cpp @@ -0,0 +1,100 @@ +/* + * SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. + * SPDX-License-Identifier: Apache-2.0 + */ +#include "families/zoedepth/runtime/preprocess.h" +#include +#include +#include +#include + +namespace trtmc::zoedepth { +namespace { +struct Geometry { int height, width, pad_h, pad_w; }; +Geometry geometry(int height, int width) { + if (height < 2 || width < 2 || height > 8192 || width > 8192 || + static_cast(height) * width > 16777216) + throw std::invalid_argument("zoedepth requires a nonempty RGB image within its size limit"); + return {height, width, static_cast(std::sqrt(height / 2.0) * 3), + static_cast(std::sqrt(width / 2.0) * 3)}; +} +int reflect(int index, int length) { + const int period = 2 * (length - 1); + index %= period; + if (index < 0) index += period; + return index < length ? index : period - index; +} +float cubic1(float x) { return ((-0.75F + 2) * x - (-0.75F + 3)) * x * x + 1; } +float cubic2(float x) { return ((-0.75F * x - 5 * -0.75F) * x + 8 * -0.75F) * x - 4 * -0.75F; } +std::array coefficients(float t) { + return {cubic2(t + 1), cubic1(t), cubic1(1 - t), cubic2(2 - t)}; +} +} // namespace + +std::vector preprocess(const float* pixels, int height, int width) { + if (!pixels) throw std::invalid_argument("zoedepth requires image pixels"); + const auto shape = geometry(height, width); + const auto count = static_cast(height) * width * 3; + for (std::size_t i = 0; i < count; ++i) + if (!std::isfinite(pixels[i]) || pixels[i] < 0 || pixels[i] > 1) + throw std::invalid_argument("zoedepth expects finite RGB pixels in [0,1]"); + const int padded_h = height + 2 * shape.pad_h, padded_w = width + 2 * shape.pad_w; + double scale_h = 384.0 / padded_h, scale_w = 512.0 / padded_w; + if (std::abs(1 - scale_w) < std::abs(1 - scale_h)) scale_h = scale_w; + else scale_w = scale_h; + const int output_h = static_cast(std::nearbyint(scale_h * padded_h / 32)) * 32; + const int output_w = static_cast(std::nearbyint(scale_w * padded_w / 32)) * 32; + if (output_h != 384 || output_w != 512) + throw std::invalid_argument("zoedepth image maps outside the 384x512 processed-image profile"); + std::vector result(3 * 384 * 512); + const auto sample = [&](int y, int x, int channel) { + const auto yy = reflect(y - shape.pad_h, height), xx = reflect(x - shape.pad_w, width); + return pixels[(static_cast(yy) * width + xx) * 3 + channel]; + }; + for (int c = 0; c < 3; ++c) for (int y = 0; y < 384; ++y) { + const float sy = (static_cast(padded_h - 1) / 383) * y; + const int y0 = static_cast(sy), y1 = std::min(y0 + 1, padded_h - 1); + const float fy = sy - y0; + for (int x = 0; x < 512; ++x) { + const float sx = (static_cast(padded_w - 1) / 511) * x; + const int x0 = static_cast(sx), x1 = std::min(x0 + 1, padded_w - 1); + const float fx = sx - x0; + const float a = (1 - fx) * sample(y0, x0, c) + fx * sample(y0, x1, c); + const float b = (1 - fx) * sample(y1, x0, c) + fx * sample(y1, x1, c); + const float value = (1 - fy) * a + fy * b; + result[(static_cast(c) * 384 + y) * 512 + x] = (value - 0.5F) / 0.5F; + } + } + return result; +} + +std::vector postprocess(const float* depth, int height, int width) { + if (!depth) throw std::invalid_argument("zoedepth requires a predicted depth map"); + const auto shape = geometry(height, width); + const int padded_h = height + 2 * shape.pad_h, padded_w = width + 2 * shape.pad_w; + std::vector result(static_cast(height) * width); + for (int y = 0; y < height; ++y) { + const float sy = std::fma(384.0F / padded_h, y + shape.pad_h + 0.5F, -0.5F); + const int y0 = static_cast(std::floor(sy)); + const auto cy = coefficients(sy - y0); + for (int x = 0; x < width; ++x) { + const float sx = std::fma(512.0F / padded_w, x + shape.pad_w + 0.5F, -0.5F); + const int x0 = static_cast(std::floor(sx)); + const auto cx = coefficients(sx - x0); + std::array rows{}; + for (int j = 0; j < 4; ++j) { + const int yy = std::clamp(y0 + j - 1, 0, 383); + for (int i = 0; i < 4; ++i) { + const int xx = std::clamp(x0 + i - 1, 0, 511); + rows[j] += depth[yy * 512 + xx] * cx[i]; + } + } + float value = 0; + for (int j = 0; j < 4; ++j) value += rows[j] * cy[j]; + if (!std::isfinite(value)) throw std::runtime_error("zoedepth nonfinite metric depth"); + result[static_cast(y) * width + x] = value; + } + } + return result; +} +} // namespace trtmc::zoedepth diff --git a/families/zoedepth/runtime/preprocess.h b/families/zoedepth/runtime/preprocess.h new file mode 100644 index 0000000000..d6d60103f5 --- /dev/null +++ b/families/zoedepth/runtime/preprocess.h @@ -0,0 +1,12 @@ +/* + * SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. + * SPDX-License-Identifier: Apache-2.0 + */ +#pragma once +#include +#include + +namespace trtmc::zoedepth { +std::vector preprocess(const float* pixels, std::int32_t height, std::int32_t width); +std::vector postprocess(const float* depth, std::int32_t height, std::int32_t width); +} // namespace trtmc::zoedepth diff --git a/families/zoedepth/support.py b/families/zoedepth/support.py new file mode 100644 index 0000000000..9f17be909b --- /dev/null +++ b/families/zoedepth/support.py @@ -0,0 +1,13 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +"""Ownership of BEiT-backed ZoeDepth checkpoints.""" + +from tensorrt_model_connect.model_support import family_support + +describe = family_support( + model_types=("zoedepth",), + architectures=("ZoeDepthForDepthEstimation",), + tasks=("monocular_depth",), + default_task="monocular_depth", + default_precision="fp32", +) diff --git a/families/zoedepth/tests/__init__.py b/families/zoedepth/tests/__init__.py new file mode 100644 index 0000000000..52a7a9daf0 --- /dev/null +++ b/families/zoedepth/tests/__init__.py @@ -0,0 +1,2 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 diff --git a/families/zoedepth/tests/cpp/e2e_consumer.cpp b/families/zoedepth/tests/cpp/e2e_consumer.cpp new file mode 100644 index 0000000000..fa1ae181ae --- /dev/null +++ b/families/zoedepth/tests/cpp/e2e_consumer.cpp @@ -0,0 +1,57 @@ +/* + * SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. + * SPDX-License-Identifier: Apache-2.0 + */ +#include "trtmc/runtime/family_loader.h" +#include +#include +#include +#include +#include +#include + +int main(int argc, char** argv) { + try { + if (argc != 5) throw std::invalid_argument("usage: zoedepth_e2e BUNDLE RUNTIME_ROOT INPUTS_JSON OUTPUT_DIRECTORY"); + std::ifstream input(argv[3]); const auto requests = nlohmann::json::parse(input); + auto model = trtmc::load_task(argv[1], argv[2]); + auto* task = dynamic_cast(model.get()); + if (!task) throw std::runtime_error("zoedepth does not implement IMonocularDepth"); + nlohmann::json results = nlohmann::json::array(); + std::vector first, first_pixels; + int first_h = 0, first_w = 0; + for (const auto& request : requests) { + const int h = request.at("height"), w = request.at("width"); + if (h < 2 || w < 2 || h > 8192 || w > 8192) throw std::invalid_argument("invalid fixture geometry"); + std::vector pixels(static_cast(h) * w * 3); + std::ifstream source(request.at("file").get(), std::ios::binary); + source.read(reinterpret_cast(pixels.data()), pixels.size() * sizeof(float)); + if (!source) throw std::runtime_error("cannot read RGB fixture"); + auto result = task->estimate_depth(pixels.data(), h, w); + if (result.height != h || result.width != w || result.depth.size() != static_cast(h) * w) + throw std::runtime_error("zoedepth returned invalid metric map geometry"); + if (results.empty()) { first = result.depth; first_pixels = pixels; first_h = h; first_w = w; } + const auto name = "depth-" + std::to_string(results.size()) + ".f32"; + std::ofstream output(std::filesystem::path(argv[4]) / name, std::ios::binary); + output.write(reinterpret_cast(result.depth.data()), result.depth.size() * sizeof(float)); + if (!output) throw std::runtime_error("cannot save native depth map"); + results.push_back({{"file", name}, {"height", h}, {"width", w}}); + } + for (int mode = 0; mode < 5; ++mode) { + auto pixels = first_pixels; + if (mode == 2) pixels[0] = std::numeric_limits::quiet_NaN(); + if (mode == 3) pixels[0] = -0.1F; + bool rejected = false; + try { + if (mode == 0) task->estimate_depth(nullptr, first_h, first_w); + else if (mode == 1) task->estimate_depth(pixels.data(), 0, first_w); + else if (mode == 4) { std::vector square(64 * 64 * 3); task->estimate_depth(square.data(), 64, 64); } + else task->estimate_depth(pixels.data(), first_h, first_w); + } catch (const std::exception&) { rejected = true; } + if (!rejected) throw std::runtime_error("zoedepth accepted an invalid image"); + } + if (task->estimate_depth(first_pixels.data(), first_h, first_w).depth != first) + throw std::runtime_error("zoedepth state leaked after rejected input"); + std::cout << results.dump() << '\n'; return 0; + } catch (const std::exception& error) { std::cerr << error.what() << '\n'; return 1; } +} diff --git a/families/zoedepth/tests/cpp/preprocess_consumer.cpp b/families/zoedepth/tests/cpp/preprocess_consumer.cpp new file mode 100644 index 0000000000..c889c99bbe --- /dev/null +++ b/families/zoedepth/tests/cpp/preprocess_consumer.cpp @@ -0,0 +1,30 @@ +/* + * SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. + * SPDX-License-Identifier: Apache-2.0 + */ +#include "families/zoedepth/runtime/preprocess.h" +#include +#include +#include +#include + +int main(int argc, char** argv) { + try { + if (argc != 6) throw std::invalid_argument("usage: zoedepth_preprocess MODE INPUT H W OUTPUT"); + const int h = std::stoi(argv[3]), w = std::stoi(argv[4]); + if (h < 2 || w < 2 || h > 8192 || w > 8192) + throw std::invalid_argument("invalid image geometry"); + const bool pre = std::string(argv[1]) == "pre"; + const std::size_t count = pre ? static_cast(h) * w * 3 : 384 * 512; + std::vector source(count); + std::ifstream input(argv[2], std::ios::binary); + input.read(reinterpret_cast(source.data()), count * sizeof(float)); + if (!input) throw std::runtime_error("cannot read image input"); + const auto result = pre ? trtmc::zoedepth::preprocess(source.data(), h, w) + : trtmc::zoedepth::postprocess(source.data(), h, w); + std::ofstream output(argv[5], std::ios::binary); + output.write(reinterpret_cast(result.data()), result.size() * sizeof(float)); + if (!output) throw std::runtime_error("cannot save processed image"); + return 0; + } catch (const std::exception& error) { std::cerr << error.what() << '\n'; return 1; } +} diff --git a/families/zoedepth/tests/manifests/zoedepth-nyu-kitti.json b/families/zoedepth/tests/manifests/zoedepth-nyu-kitti.json new file mode 100644 index 0000000000..38f2744fca --- /dev/null +++ b/families/zoedepth/tests/manifests/zoedepth-nyu-kitti.json @@ -0,0 +1,23 @@ +{ + "name": "zoedepth-nyu-kitti", + "family": "zoedepth", + "hf_id": "Intel/zoedepth-nyu-kitti", + "hf_revision": "f364d4c7936e91f465abba182208dd68142bf0ca", + "trust_remote_code": false, + "task": "monocular_depth", + "precision": "fp32", + "tensor_parallel_size": 1, + "max_sequence_length": 1, + "image_height": 384, + "image_width": 512, + "bundle": "zoedepth-nyu-kitti.bundle", + "testcases": [ + { + "name": "zoedepth-nyu-kitti-fp32", + "reference_precision": "fp32", + "premerge": true, + "depth_atol": 0.001, + "depth_rtol": 0.0005 + } + ] +} diff --git a/families/zoedepth/tests/math_check.py b/families/zoedepth/tests/math_check.py new file mode 100644 index 0000000000..40877c50e4 --- /dev/null +++ b/families/zoedepth/tests/math_check.py @@ -0,0 +1,98 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +"""Compare rectangular BEiT and both metric branches with upstream modules.""" + + +def check_stages(tmp_path): + import torch + import tensorrt as trt + from transformers import BeitConfig, ZoeDepthConfig, ZoeDepthForDepthEstimation + from families.zoedepth.model import build_engine + + torch.set_num_threads(8) + torch.backends.cuda.matmul.allow_tf32 = False + torch.backends.cudnn.allow_tf32 = False + torch.manual_seed(375) + backbone = BeitConfig( + image_size=64, + patch_size=16, + hidden_size=16, + num_hidden_layers=4, + num_attention_heads=2, + intermediate_size=32, + out_indices=[1, 2, 3, 4], + reshape_hidden_states=False, + use_relative_position_bias=True, + drop_path_rate=0, + ) + config = ZoeDepthConfig( + backbone_config=backbone.to_dict(), + backbone_hidden_size=16, + neck_hidden_sizes=[8, 8, 8, 8], + fusion_hidden_size=8, + bottleneck_features=8, + num_relative_features=4, + bin_embedding_dim=8, + num_attractors=[2, 2, 1, 1], + patch_transformer_hidden_size=128, + patch_transformer_intermediate_size=64, + patch_transformer_num_attention_heads=4, + num_patch_transformer_layers=4, + bin_configurations=[ + dict(name="nyu", n_bins=4, min_depth=0.001, max_depth=10.0), + dict(name="kitti", n_bins=4, min_depth=0.001, max_depth=80.0), + ], + ) + config.backbone_config._attn_implementation = "eager" + model = ZoeDepthForDepthEstimation(config).eval() + image = torch.randn(1, 3, 64, 96) + logger = trt.Logger(trt.Logger.WARNING) + runtime = trt.Runtime(logger) + for branch in (0, 1): + with torch.no_grad(): + model.metric_head.mlp_classifier.linear2.bias.copy_( + torch.tensor([2.0, -2.0]) * (1 if branch == 0 else -1) + ) + weights = { + name: value.detach().numpy().copy() for name, value in model.state_dict().items() + } + plan = build_engine(weights, config.to_dict(), 64, 96, debug=True) + engine = runtime.deserialize_cuda_engine(plan) + assert engine is not None + context = engine.create_execution_context() + tensors = {"pixel_values": image.contiguous().cuda()} + for i in range(engine.num_io_tensors): + name = engine.get_tensor_name(i) + if engine.get_tensor_mode(name) == trt.TensorIOMode.OUTPUT: + tensors[name] = torch.empty(tuple(context.get_tensor_shape(name)), device="cuda") + for name, value in tensors.items(): + assert context.set_tensor_address(name, value.data_ptr()) + assert context.execute_async_v3(torch.cuda.current_stream().cuda_stream) + torch.cuda.synchronize() + actual = {name: value.cpu() for name, value in tensors.items() if name != "pixel_values"} + with torch.inference_mode(): + taps = model.backbone(image).feature_maps + fused, bottleneck = model.neck(taps, 4, 6) + expected = model(image) + bottleneck = model.metric_head.conv2(bottleneck) + assert expected.domain_logits.argmax(-1).item() == branch + references = { + "predicted_depth": expected.predicted_depth[:, None], + "domain_logits": expected.domain_logits, + "bottleneck": bottleneck, + } + references.update({f"backbone_{i}": value for i, value in enumerate(taps)}) + references.update({f"fusion_{i}": value for i, value in enumerate(fused)}) + references["metric_" + ("nyu" if branch == 0 else "kitti")] = expected.predicted_depth[ + :, None + ] + for name, value in references.items(): + print( + "zoedepth stage", + branch, + name, + float((actual[name] - value).abs().max()), + flush=True, + ) + torch.testing.assert_close(actual[name], value, atol=5e-5, rtol=5e-5) + del tensors, context, engine diff --git a/families/zoedepth/tests/requirements.txt b/families/zoedepth/tests/requirements.txt new file mode 100644 index 0000000000..10c30cacc7 --- /dev/null +++ b/families/zoedepth/tests/requirements.txt @@ -0,0 +1,3 @@ +transformers==5.3.0 +torch>=2.6 +Pillow>=10 diff --git a/families/zoedepth/tests/test_e2e.py b/families/zoedepth/tests/test_e2e.py new file mode 100644 index 0000000000..b07033b182 --- /dev/null +++ b/families/zoedepth/tests/test_e2e.py @@ -0,0 +1,258 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +"""Pinned ZoeDepth checkpoint, native monocular-depth Task and CLI parity.""" + +import gc +import json +import os +from pathlib import Path +import subprocess +from types import SimpleNamespace + +import numpy as np +import pytest + +from tensorrt_model_connect import BuildRequest, build +from tensorrt_model_connect.model_support import load_model_metadata, resolve_family +from tools.e2e_evidence import evidence_stage, record_evidence + +MANIFEST = json.loads((Path(__file__).parent / "manifests/zoedepth-nyu-kitti.json").read_text()) + + +def pytest_generate_tests(metafunc): + if "case_name" not in metafunc.fixturenames: + return + models, cases = set(), set() + for value in metafunc.config.getoption("--e2e-model"): + models.update(value.split(",")) + file = metafunc.config.getoption("--e2e-models-file") + if file: + models.update(Path(file).read_text().splitlines()) + for value in metafunc.config.getoption("--e2e-testcase"): + cases.update(value.split(",")) + selected = bool(models or cases) + parameters = [] + for case in MANIFEST["testcases"]: + if models and not models.intersection({"zoedepth", MANIFEST["name"], case["name"]}): + continue + if cases and case["name"] not in cases: + continue + marks = [] if selected else [pytest.mark.skip(reason="select ZoeDepth E2E explicitly")] + parameters.append(pytest.param(case["name"], id=case["name"], marks=marks)) + metafunc.parametrize("case_name", parameters) + + +def checkpoint(): + if path := os.environ.get("TRTMC_ZOEDEPTH_MODEL_DIR"): + return Path(path) + from huggingface_hub import snapshot_download + + return Path( + snapshot_download( + repo_id=MANIFEST["hf_id"], revision=MANIFEST["hf_revision"], local_files_only=True + ) + ) + + +def fixtures(): + images = [] + for i, (h, w) in enumerate(((384, 512), (480, 640), (384, 512))): + y, x = np.meshgrid(np.arange(h), np.arange(w), indexing="ij") + rgb = np.stack( + [ + (3 * x + y + i * 71) % 256, + (2 * y + x // 13 + i * 23) % 256, + ((x // 17 + y // 11 + i) % 2) * 223 + 16, + ], + axis=2, + ).astype(np.uint8) + images.append(rgb) + return images + [images[0].copy()] + + +def check_preprocessing(root, runtime, tmp_path): + import torch + from transformers import ZoeDepthImageProcessor + + processor = ZoeDepthImageProcessor.from_pretrained(root) + for i, image in enumerate(fixtures()[:2]): + source = tmp_path / f"pre-source-{i}.f32" + (image.astype(np.float32) / np.float32(255)).tofile(source) + output = tmp_path / f"pre-result-{i}.f32" + subprocess.run( + [ + str(runtime / "zoedepth_preprocess"), + "pre", + str(source), + *map(str, image.shape[:2]), + str(output), + ], + check=True, + capture_output=True, + text=True, + timeout=30, + ) + expected = processor(images=image, return_tensors="pt").pixel_values.numpy() + actual = np.fromfile(output, np.float32).reshape(expected.shape) + np.testing.assert_allclose(actual, expected, atol=2e-5, rtol=2e-5) + raw = np.random.default_rng(375).uniform(0.2, 10, (1, 384, 512)).astype(np.float32) + raw.tofile(tmp_path / "post-source.f32") + for i, size in enumerate(((384, 512), (480, 640), (123, 157))): + output = tmp_path / f"post-result-{i}.f32" + subprocess.run( + [ + str(runtime / "zoedepth_preprocess"), + "post", + str(tmp_path / "post-source.f32"), + *map(str, size), + str(output), + ], + check=True, + capture_output=True, + text=True, + timeout=30, + ) + expected = processor.post_process_depth_estimation( + SimpleNamespace(predicted_depth=torch.from_numpy(raw)), source_sizes=[size] + )[0]["predicted_depth"].numpy() + actual = np.fromfile(output, np.float32).reshape(size) + np.testing.assert_allclose(actual, expected, atol=2e-5, rtol=2e-5) + + +def reference(root, images): + import torch + from transformers import ZoeDepthForDepthEstimation, ZoeDepthImageProcessor + + torch.set_num_threads(8) + torch.backends.cuda.matmul.allow_tf32 = False + torch.backends.cudnn.allow_tf32 = False + processor = ZoeDepthImageProcessor.from_pretrained(root) + model = ( + ZoeDepthForDepthEstimation.from_pretrained( + root, + dtype=torch.float32, + attn_implementation="eager", + trust_remote_code=MANIFEST["trust_remote_code"], + ) + .cuda() + .eval() + ) + expected, domains = [], [] + for image in images: + inputs = processor(images=image, return_tensors="pt").to("cuda") + assert tuple(inputs.pixel_values.shape) == (1, 3, 384, 512) + with torch.inference_mode(): + outputs = model(**inputs) + depth = processor.post_process_depth_estimation( + outputs, source_sizes=[image.shape[:2]] + )[0]["predicted_depth"] + expected.append(depth.cpu().numpy().copy()) + domains.append(outputs.domain_logits.cpu().tolist()) + del model, outputs, inputs, depth + gc.collect() + torch.cuda.empty_cache() + return expected, domains + + +def test_official_checkpoint_e2e(case_name, tmp_path): + from PIL import Image + from families.zoedepth.tests.math_check import check_stages + + case = next(c for c in MANIFEST["testcases"] if c["name"] == case_name) + assert case["reference_precision"] == "fp32" + check_stages(tmp_path) + root, runtime = checkpoint(), Path(os.environ["TRTMC_RUNTIME_ROOT"]) + assert resolve_family(load_model_metadata(root))[0] == "zoedepth" + assert (runtime / "libtrtmc_model_zoedepth.so").is_file() + check_preprocessing(root, runtime, tmp_path) + images = fixtures() + record_evidence("inputs", {"manifest": MANIFEST, "case": case}) + record_evidence( + "checkpoint", + { + "model_dir": str(root), + "hf_id": MANIFEST["hf_id"], + "hf_revision": MANIFEST["hf_revision"], + }, + ) + with evidence_stage("reference"): + expected, domains = reference(root, images) + for i, depth in enumerate(expected): + assert np.isfinite(depth).all() and float(depth.min()) > 0 and float(depth.std()) > 1e-4 + depth.tofile(tmp_path / f"reference-{i}.f32") + np.testing.assert_array_equal(expected[0], expected[-1]) + record_evidence( + "reference", + { + "domains": domains, + "files": [str(tmp_path / f"reference-{i}.f32") for i in range(len(images))], + }, + ) + bundle = tmp_path / MANIFEST["bundle"] + with evidence_stage("build"): + build( + BuildRequest( + root, + bundle, + MANIFEST["family"], + MANIFEST["task"], + MANIFEST["precision"], + tensor_parallel_size=MANIFEST["tensor_parallel_size"], + max_sequence_length=MANIFEST["max_sequence_length"], + image_height=MANIFEST["image_height"], + image_width=MANIFEST["image_width"], + ) + ) + requests = [] + for i, image in enumerate(images): + path = tmp_path / f"input-{i}.f32" + (image.astype(np.float32) / np.float32(255)).tofile(path) + requests.append({"file": str(path), "height": image.shape[0], "width": image.shape[1]}) + inputs = tmp_path / "inputs.json" + inputs.write_text(json.dumps(requests)) + with evidence_stage("native"): + command = [ + str(runtime / "zoedepth_e2e"), + str(bundle), + str(runtime), + str(inputs), + str(tmp_path), + ] + result = subprocess.run(command, check=True, capture_output=True, text=True, timeout=180) + actual = json.loads(result.stdout.strip().splitlines()[-1]) + record_evidence("commands", {"argv": command}) + assert len(actual) == len(expected) + observed = [] + with evidence_stage("compare"): + for item, depth in zip(actual, expected): + values = np.fromfile(tmp_path / item["file"], np.float32).reshape( + item["height"], item["width"] + ) + assert np.isfinite(values).all() + np.testing.assert_allclose( + values, depth, atol=case["depth_atol"], rtol=case["depth_rtol"] + ) + observed.append(values) + np.testing.assert_array_equal(observed[0], observed[-1]) + path = tmp_path / "input.png" + Image.fromarray(images[0]).save(path) + with evidence_stage("cli"): + command = [ + str(runtime / "trtmc"), + "depth", + str(bundle), + "--runtime-root", + str(runtime), + "--image", + str(path), + ] + result = subprocess.run(command, check=True, capture_output=True, text=True, timeout=180) + cli = json.loads(result.stdout.strip().splitlines()[-1]) + np.testing.assert_allclose( + np.asarray(cli["depth"]).reshape(cli["height"], cli["width"]), + expected[0], + atol=case["depth_atol"], + rtol=case["depth_rtol"], + ) + record_evidence("commands", {"argv": command}) + record_evidence("native", actual) diff --git a/families/zoedepth/tests/test_model.py b/families/zoedepth/tests/test_model.py new file mode 100644 index 0000000000..858911b581 --- /dev/null +++ b/families/zoedepth/tests/test_model.py @@ -0,0 +1,32 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +import pytest +from tensorrt_model_connect import BuildRequest +from families.zoedepth.model import build, Graph + + +def test_rejects_unsupported_precision_and_image_profile(tmp_path): + with pytest.raises(ValueError, match="FP32"): + build( + BuildRequest( + tmp_path, tmp_path / "model.bundle", "zoedepth", "monocular_depth", "fp16" + ), + None, + ) + with pytest.raises(ValueError, match="384x512"): + build( + BuildRequest( + tmp_path, + tmp_path / "model.bundle", + "zoedepth", + "monocular_depth", + "fp32", + image_height=512, + ), + None, + ) + + +def test_missing_checkpoint_weights_cannot_be_initialized(): + with pytest.raises(ValueError, match="missing backbone"): + Graph(None, {}).weight("backbone.embeddings.cls_token") diff --git a/families/zoedepth/tests/test_support.py b/families/zoedepth/tests/test_support.py new file mode 100644 index 0000000000..75a9d59801 --- /dev/null +++ b/families/zoedepth/tests/test_support.py @@ -0,0 +1,14 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +from tensorrt_model_connect.model_support import ModelMetadata, resolve_family +from families.zoedepth.support import describe + + +def test_zoedepth_owner_and_metric_task(): + metadata = ModelMetadata( + config={"model_type": "zoedepth", "architectures": ["ZoeDepthForDepthEstimation"]}, + model_index={}, + ) + family, support = resolve_family(metadata) + assert family == "zoedepth" and support.default_task == "monocular_depth" + assert describe(ModelMetadata(config={"model_type": "depth_anything"}, model_index={})) is None From cdcc3d6744250485258fa9cacc39487df823bc8f Mon Sep 17 00:00:00 2001 From: Will Guo Date: Wed, 2 Dec 2026 20:22:53 -0800 Subject: [PATCH 2/2] fix(zoedepth): match reference routing and retain depth evidence Signed-off-by: Will Guo --- families/zoedepth/README.md | 18 +++++++++++--- families/zoedepth/model.py | 8 +++++-- families/zoedepth/runtime/pipeline.cpp | 1 + families/zoedepth/runtime/pipeline.h | 3 +++ families/zoedepth/tests/math_check.py | 26 +++++++++++++------- families/zoedepth/tests/test_e2e.py | 33 ++++++++++++++++++++------ 6 files changed, 69 insertions(+), 20 deletions(-) diff --git a/families/zoedepth/README.md b/families/zoedepth/README.md index ec3f00b846..392b14cd32 100644 --- a/families/zoedepth/README.md +++ b/families/zoedepth/README.md @@ -19,7 +19,7 @@ image resolution, with the upstream bicubic resize and padding removal. Inference has no Python or PyTorch dependency. ```bash -trtmc build /path/to/zoedepth-nyu-kitti -o model.bundle \ +PYTHONPATH=core/builder:. python -m tensorrt_model_connect build /path/to/zoedepth-nyu-kitti -o model.bundle \ --family zoedepth --task monocular_depth --precision fp32 trtmc depth model.bundle --runtime-root /path/to/runtime --image image.png ``` @@ -32,8 +32,20 @@ Real checkpoint tests compare every output pixel for multiple images, different source resolutions, repeated calls, rejection recovery and CLI execution at the manifest's fixed tolerances. +From the repository root, start with the +[source build environment](../../website/docs/getting-started/source-build.md). +Install the family build and test dependencies and fetch the pinned snapshot +before running the offline test. + ```bash -PYTHONPATH=core/builder:apps/benchmark:. python -m tools.model_ci validate -PYTHONPATH=core/builder:apps/benchmark:. python -m pytest \ +python -m pip install -r families/zoedepth/requirements.txt -r families/zoedepth/tests/requirements.txt +hf download Intel/zoedepth-nyu-kitti --revision f364d4c7936e91f465abba182208dd68142bf0ca +cmake -S . -B build -DTRTMC_BUILD_TESTS=ON +cmake --build build --target trtmc trtmc_backend_trt trtmc_model_zoedepth zoedepth_preprocess zoedepth_e2e +export TRTMC_RUNTIME_ROOT="$PWD/build" +PYTHONPATH=core/builder:apps/benchmark:. HF_HUB_OFFLINE=1 python -m pytest \ families/zoedepth/tests --e2e-model zoedepth -q ``` + +An explicit `TRTMC_ZOEDEPTH_MODEL_DIR` supports local comparisons. Its +checkpoint revision is recorded as unverified. diff --git a/families/zoedepth/model.py b/families/zoedepth/model.py index a0e51d0c8b..c7d34fef7a 100644 --- a/families/zoedepth/model.py +++ b/families/zoedepth/model.py @@ -356,9 +356,11 @@ def network_outputs(g, image, config): depths = [ metric_branch(g, bottleneck, features, last, embeddings, name, config) for name in names ] + # The reference votes on FP32 softmax probabilities. Equal votes select NYU. + votes = g.softmax(logits, 1) choose_second = g.binary( - g.slice(logits, (0, 1), (1, 1)), - g.slice(logits, (0, 0), (1, 1)), + g.slice(votes, (0, 1), (1, 1)), + g.slice(votes, (0, 0), (1, 1)), trt.ElementWiseOperation.GREATER, ) choose_second = g.reshape(choose_second, (1, 1, 1, 1)) @@ -402,6 +404,8 @@ def validate(config, processor): or c.get("reshape_hidden_states", True) ): raise ValueError("unsupported ZoeDepth BEiT embedding or feature topology") + if c.get("hidden_act", "gelu") != "gelu": + raise ValueError("zoedepth requires GELU in the BEiT backbone") if c.get("layer_scale_init_value", 0.1) <= 0 or len(c.get("out_indices", [])) != 4: raise ValueError("zoedepth requires four scaled BEiT feature taps") if ( diff --git a/families/zoedepth/runtime/pipeline.cpp b/families/zoedepth/runtime/pipeline.cpp index e512a1af2b..bbbe325212 100644 --- a/families/zoedepth/runtime/pipeline.cpp +++ b/families/zoedepth/runtime/pipeline.cpp @@ -13,6 +13,7 @@ Pipeline::Pipeline(std::unique_ptr model) : model_(std::move(model)) if (!model_ || !model_->ok()) throw std::invalid_argument("zoedepth invalid engine"); } MonocularDepthResult Pipeline::estimate_depth(const float* pixels, int height, int width) { + const std::lock_guard lock(execution_); auto values = preprocess(pixels, height, width); Tensor input; input.data = values.data(); input.dtype = DType::kFloat32; input.shape = {1, 3, 384, 512}; diff --git a/families/zoedepth/runtime/pipeline.h b/families/zoedepth/runtime/pipeline.h index d7801d4056..27ea49f8d2 100644 --- a/families/zoedepth/runtime/pipeline.h +++ b/families/zoedepth/runtime/pipeline.h @@ -3,6 +3,8 @@ * SPDX-License-Identifier: Apache-2.0 */ #pragma once + +#include #include "trtmc/runtime/trt_module.h" #include "trtmc/task.h" @@ -12,6 +14,7 @@ class Pipeline final : public IMonocularDepth { explicit Pipeline(std::unique_ptr model); MonocularDepthResult estimate_depth(const float*, std::int32_t, std::int32_t) override; private: + std::mutex execution_; std::unique_ptr model_; }; } // namespace trtmc::zoedepth diff --git a/families/zoedepth/tests/math_check.py b/families/zoedepth/tests/math_check.py index 40877c50e4..ceb7f784d8 100644 --- a/families/zoedepth/tests/math_check.py +++ b/families/zoedepth/tests/math_check.py @@ -45,14 +45,20 @@ def check_stages(tmp_path): ) config.backbone_config._attn_implementation = "eager" model = ZoeDepthForDepthEstimation(config).eval() + with torch.no_grad(): + for name, parameter in model.backbone.named_parameters(): + if name.endswith(".relative_position_bias_table"): + bias = torch.linspace(-0.1, 0.1, parameter.numel()) + parameter.copy_(bias.reshape_as(parameter)) image = torch.randn(1, 3, 64, 96) logger = trt.Logger(trt.Logger.WARNING) runtime = trt.Runtime(logger) - for branch in (0, 1): + for bias, branch in (([2.0, -2.0], 0), ([-2.0, 2.0], 1), ([0.0, 2**-28], 0)): with torch.no_grad(): - model.metric_head.mlp_classifier.linear2.bias.copy_( - torch.tensor([2.0, -2.0]) * (1 if branch == 0 else -1) - ) + classifier = model.metric_head.mlp_classifier.linear2 + if bias[0] == 0.0: + classifier.weight.zero_() + classifier.bias.copy_(torch.tensor(bias)) weights = { name: value.detach().numpy().copy() for name, value in model.state_dict().items() } @@ -75,7 +81,13 @@ def check_stages(tmp_path): fused, bottleneck = model.neck(taps, 4, 6) expected = model(image) bottleneck = model.metric_head.conv2(bottleneck) - assert expected.domain_logits.argmax(-1).item() == branch + votes = expected.domain_logits.softmax(dim=-1) + assert votes.argmax(-1).item() == branch + if bias[0] == 0.0: + torch.testing.assert_close(expected.domain_logits, torch.tensor([bias]), atol=0, rtol=0) + torch.testing.assert_close(votes, torch.full_like(votes, 0.5), atol=0, rtol=0) + selected = "metric_" + ("nyu" if branch == 0 else "kitti") + torch.testing.assert_close(actual["predicted_depth"], actual[selected], atol=0, rtol=0) references = { "predicted_depth": expected.predicted_depth[:, None], "domain_logits": expected.domain_logits, @@ -83,9 +95,7 @@ def check_stages(tmp_path): } references.update({f"backbone_{i}": value for i, value in enumerate(taps)}) references.update({f"fusion_{i}": value for i, value in enumerate(fused)}) - references["metric_" + ("nyu" if branch == 0 else "kitti")] = expected.predicted_depth[ - :, None - ] + references[selected] = expected.predicted_depth[:, None] for name, value in references.items(): print( "zoedepth stage", diff --git a/families/zoedepth/tests/test_e2e.py b/families/zoedepth/tests/test_e2e.py index b07033b182..8aca732f61 100644 --- a/families/zoedepth/tests/test_e2e.py +++ b/families/zoedepth/tests/test_e2e.py @@ -44,14 +44,14 @@ def pytest_generate_tests(metafunc): def checkpoint(): if path := os.environ.get("TRTMC_ZOEDEPTH_MODEL_DIR"): - return Path(path) + return Path(path), None from huggingface_hub import snapshot_download return Path( snapshot_download( repo_id=MANIFEST["hf_id"], revision=MANIFEST["hf_revision"], local_files_only=True ) - ) + ), MANIFEST["hf_revision"] def fixtures(): @@ -154,6 +154,22 @@ def reference(root, images): return expected, domains +@pytest.fixture(autouse=True) +def restore_torch_state(): + import torch + + threads = torch.get_num_threads() + matmul_tf32 = torch.backends.cuda.matmul.allow_tf32 + cudnn_tf32 = torch.backends.cudnn.allow_tf32 + try: + with torch.random.fork_rng(): + yield + finally: + torch.set_num_threads(threads) + torch.backends.cuda.matmul.allow_tf32 = matmul_tf32 + torch.backends.cudnn.allow_tf32 = cudnn_tf32 + + def test_official_checkpoint_e2e(case_name, tmp_path): from PIL import Image from families.zoedepth.tests.math_check import check_stages @@ -161,7 +177,8 @@ def test_official_checkpoint_e2e(case_name, tmp_path): case = next(c for c in MANIFEST["testcases"] if c["name"] == case_name) assert case["reference_precision"] == "fp32" check_stages(tmp_path) - root, runtime = checkpoint(), Path(os.environ["TRTMC_RUNTIME_ROOT"]) + root, revision = checkpoint() + runtime = Path(os.environ["TRTMC_RUNTIME_ROOT"]) assert resolve_family(load_model_metadata(root))[0] == "zoedepth" assert (runtime / "libtrtmc_model_zoedepth.so").is_file() check_preprocessing(root, runtime, tmp_path) @@ -171,8 +188,9 @@ def test_official_checkpoint_e2e(case_name, tmp_path): "checkpoint", { "model_dir": str(root), - "hf_id": MANIFEST["hf_id"], - "hf_revision": MANIFEST["hf_revision"], + "hf_id": MANIFEST["hf_id"] if revision else None, + "hf_revision": revision, + "revision_verified": revision is not None, }, ) with evidence_stage("reference"): @@ -220,12 +238,14 @@ def test_official_checkpoint_e2e(case_name, tmp_path): ] result = subprocess.run(command, check=True, capture_output=True, text=True, timeout=180) actual = json.loads(result.stdout.strip().splitlines()[-1]) + actual = [{**item, "file": str(tmp_path / item["file"])} for item in actual] record_evidence("commands", {"argv": command}) + record_evidence("native", actual) assert len(actual) == len(expected) observed = [] with evidence_stage("compare"): for item, depth in zip(actual, expected): - values = np.fromfile(tmp_path / item["file"], np.float32).reshape( + values = np.fromfile(item["file"], np.float32).reshape( item["height"], item["width"] ) assert np.isfinite(values).all() @@ -255,4 +275,3 @@ def test_official_checkpoint_e2e(case_name, tmp_path): rtol=case["depth_rtol"], ) record_evidence("commands", {"argv": command}) - record_evidence("native", actual)