From 153cbab518ff3bb5908850ad3dc433df1cfa14a2 Mon Sep 17 00:00:00 2001 From: Will Guo Date: Thu, 12 Nov 2026 22:47:05 -0800 Subject: [PATCH 1/2] feat(pvt): add native pyramid classification Signed-off-by: Will Guo --- families/pvt/__init__.py | 4 + families/pvt/model.py | 194 +++++++++++++++++ families/pvt/requirements.txt | 2 + families/pvt/runtime/CMakeLists.txt | 27 +++ families/pvt/runtime/image_preprocess.cpp | 197 ++++++++++++++++++ families/pvt/runtime/image_preprocess.h | 31 +++ families/pvt/runtime/pipeline.cpp | 51 +++++ families/pvt/runtime/pipeline.h | 25 +++ families/pvt/runtime/plugin.cpp | 34 +++ families/pvt/support.py | 7 + families/pvt/tests/__init__.py | 2 + families/pvt/tests/cpp/e2e_consumer.cpp | 69 ++++++ .../pvt/tests/cpp/test_image_preprocess.cpp | 170 +++++++++++++++ families/pvt/tests/manifests/pvt-tiny.json | 22 ++ families/pvt/tests/test_e2e.py | 111 ++++++++++ families/pvt/tests/test_model.py | 28 +++ families/pvt/tests/test_support.py | 14 ++ 17 files changed, 988 insertions(+) create mode 100644 families/pvt/__init__.py create mode 100644 families/pvt/model.py create mode 100644 families/pvt/requirements.txt create mode 100644 families/pvt/runtime/CMakeLists.txt create mode 100644 families/pvt/runtime/image_preprocess.cpp create mode 100644 families/pvt/runtime/image_preprocess.h create mode 100644 families/pvt/runtime/pipeline.cpp create mode 100644 families/pvt/runtime/pipeline.h create mode 100644 families/pvt/runtime/plugin.cpp create mode 100644 families/pvt/support.py create mode 100644 families/pvt/tests/__init__.py create mode 100644 families/pvt/tests/cpp/e2e_consumer.cpp create mode 100644 families/pvt/tests/cpp/test_image_preprocess.cpp create mode 100644 families/pvt/tests/manifests/pvt-tiny.json create mode 100644 families/pvt/tests/test_e2e.py create mode 100644 families/pvt/tests/test_model.py create mode 100644 families/pvt/tests/test_support.py diff --git a/families/pvt/__init__.py b/families/pvt/__init__.py new file mode 100644 index 0000000000..3f25d0e948 --- /dev/null +++ b/families/pvt/__init__.py @@ -0,0 +1,4 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +"""Pyramid Vision Transformer image classification.""" diff --git a/families/pvt/model.py b/families/pvt/model.py new file mode 100644 index 0000000000..6c62ae2bf1 --- /dev/null +++ b/families/pvt/model.py @@ -0,0 +1,194 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +"""PVT patch stages, spatial-reduction attention, and classification in TensorRT.""" + +from __future__ import annotations + +import json +from pathlib import Path + +import numpy as np +from safetensors.numpy import load_file +import tensorrt as trt + + +def validate_config(config): + if config.get("model_type") != "pvt": + raise ValueError("pvt requires model_type=pvt") + if config.get("num_channels", 3) != 3 or config.get("hidden_act", "gelu") != "gelu": + raise NotImplementedError("pvt requires RGB input and exact GELU") + stages = config["num_encoder_blocks"] + for name in ("hidden_sizes", "depths", "num_attention_heads", "sequence_reduction_ratios", + "patch_sizes", "strides", "mlp_ratios"): + if len(config[name]) != stages or any(value <= 0 for value in config[name]): + raise ValueError(f"pvt {name} must contain one positive value per stage") + if config["patch_sizes"] != config["strides"]: + raise NotImplementedError("pvt requires matching patch sizes and strides") + if config["sequence_reduction_ratios"][-1] != 1: + raise ValueError("pvt class-token stage cannot spatially reduce its sequence") + for hidden, heads in zip(config["hidden_sizes"], config["num_attention_heads"]): + if hidden % heads: + raise ValueError("pvt attention heads must divide the stage width") + return config + + +class Graph: + def __init__(self, network, config, weights): + self.n, self.c, self.w = network, config, weights + self.constants = [] + + def constant(self, value): + value = np.ascontiguousarray(value, dtype=np.float32) + self.constants.append(value) + return self.n.add_constant(value.shape, trt.Weights(value)).get_output(0) + + def reshape(self, x, shape, transpose=None): + layer = self.n.add_shuffle(x) + layer.reshape_dims = shape + if transpose is not None: + layer.second_transpose = transpose + return layer.get_output(0) + + def add(self, x, y): + return self.n.add_elementwise(x, y, trt.ElementWiseOperation.SUM).get_output(0) + + def linear(self, x, name): + weight = self.w[name + ".weight"] + rank = len(x.shape) + rhs = self.constant(weight.T.reshape((1,) * (rank - 2) + tuple(weight.T.shape))) + result = self.n.add_matrix_multiply(x, trt.MatrixOperation.NONE, + rhs, trt.MatrixOperation.NONE).get_output(0) + if name + ".bias" in self.w: + result = self.add(result, self.constant(self.w[name + ".bias"].reshape((1,) * (rank - 1) + (-1,)))) + return result + + def norm(self, x, name): + rank = len(x.shape) + shape = (1,) * (rank - 1) + (-1,) + layer = self.n.add_normalization(x, self.constant(self.w[name + ".weight"].reshape(shape)), + self.constant(self.w[name + ".bias"].reshape(shape)), 1 << (rank - 1)) + layer.epsilon = self.c["layer_norm_eps"] + return layer.get_output(0) + + def conv(self, x, name, stride): + weight = self.w[name + ".weight"] + layer = self.n.add_convolution_nd(x, weight.shape[0], tuple(weight.shape[-2:]), + trt.Weights(weight), trt.Weights(self.w[name + ".bias"])) + layer.stride_nd = (stride, stride) + return layer.get_output(0) + + def to_tokens(self, x): + batch, channels, height, width = x.shape + layer = self.n.add_shuffle(x) + layer.first_transpose = (0, 2, 3, 1) + layer.reshape_dims = (batch, height * width, channels) + return layer.get_output(0) + + def attention(self, x, name, heads, reduction, height, width): + tokens, channels = x.shape[1:] + dim = channels // heads + query = self.reshape(self.linear(x, name + ".self.query"), (1, tokens, heads, dim), (0, 2, 1, 3)) + source = x + if reduction > 1: + spatial = self.reshape(x, (1, height, width, channels), (0, 3, 1, 2)) + source = self.to_tokens(self.conv(spatial, name + ".self.sequence_reduction", reduction)) + source = self.norm(source, name + ".self.layer_norm") + keys = source.shape[1] + key = self.reshape(self.linear(source, name + ".self.key"), (1, keys, heads, dim), (0, 2, 1, 3)) + value = self.reshape(self.linear(source, name + ".self.value"), (1, keys, heads, dim), (0, 2, 1, 3)) + scores = self.n.add_matrix_multiply(query, trt.MatrixOperation.NONE, + key, trt.MatrixOperation.TRANSPOSE).get_output(0) + scores = self.n.add_elementwise(scores, self.constant([[[[dim ** 0.5]]]]), + trt.ElementWiseOperation.DIV).get_output(0) + probabilities = self.n.add_softmax(scores) + probabilities.axes = 1 << 3 + context = self.n.add_matrix_multiply(probabilities.get_output(0), trt.MatrixOperation.NONE, + value, trt.MatrixOperation.NONE).get_output(0) + merged = self.n.add_shuffle(context) + merged.first_transpose = (0, 2, 1, 3) + merged.reshape_dims = (1, tokens, channels) + return self.linear(merged.get_output(0), name + ".output.dense") + + def build(self): + size = self.c["image_size"] + x = self.n.add_input("pixel_values", trt.float32, (1, 3, size, size)) + for stage in range(self.c["num_encoder_blocks"]): + embedding = f"pvt.encoder.patch_embeddings.{stage}" + x = self.conv(x, embedding + ".projection", self.c["patch_sizes"][stage]) + height, width = x.shape[-2:] + channels = x.shape[1] + x = self.norm(self.to_tokens(x), embedding + ".layer_norm") + if stage + 1 == self.c["num_encoder_blocks"]: + concat = self.n.add_concatenation([self.constant(self.w[embedding + ".cls_token"]), x]) + concat.axis = 1 + x = concat.get_output(0) + positions = self.w[embedding + ".position_embeddings"] + if tuple(x.shape) != positions.shape: + raise ValueError("pvt input resolution does not match checkpoint position embeddings") + x = self.add(x, self.constant(positions)) + for layer in range(self.c["depths"][stage]): + prefix = f"pvt.encoder.block.{stage}.{layer}" + normalized = self.norm(x, prefix + ".layer_norm_1") + x = self.add(x, self.attention(normalized, prefix + ".attention", + self.c["num_attention_heads"][stage], self.c["sequence_reduction_ratios"][stage], height, width)) + hidden = self.linear(self.norm(x, prefix + ".layer_norm_2"), prefix + ".mlp.dense1") + hidden = self.n.add_activation(hidden, trt.ActivationType.GELU_ERF).get_output(0) + x = self.add(x, self.linear(hidden, prefix + ".mlp.dense2")) + if stage + 1 < self.c["num_encoder_blocks"]: + x = self.reshape(x, (1, height, width, channels), (0, 3, 1, 2)) + x = self.norm(x, "pvt.encoder.layer_norm") + cls = self.n.add_slice(x, (0, 0, 0), (1, 1, x.shape[-1]), (1, 1, 1)).get_output(0) + logits = self.linear(self.reshape(cls, (1, cls.shape[-1])), "classifier") + logits.name = "logits" + self.n.mark_output(logits) + + +def compile_engine(config, weights, 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, config, weights) + graph.build() + plan = builder.build_serialized_network(network, options) + if plan is None: + raise RuntimeError("pvt TensorRT classifier build failed") + return bytes(plan) + + +def build(request, writer): + if request.dynamic_kv_cache: + raise NotImplementedError("pvt does not support dynamic_kv_cache") + if request.task != "classification" or request.precision != "fp32" or request.backend != "trt": + raise ValueError("pvt requires classification, precision=fp32, backend=trt") + for field, value, default in ( + ("max_batch_size", request.max_batch_size, 1), ("tensor_parallel_size", request.tensor_parallel_size, 1), + ("context_parallel_size", request.context_parallel_size, 1), + ("max_sequence_length", request.max_sequence_length, None), + ("video_num_frames", request.video_num_frames, None), ("mtp_seq_len", request.mtp_seq_len, None), + ("fp32_layers", request.fp32_layers, ()), + ): + if value != default: + raise NotImplementedError(f"pvt does not support {field}") + if request.quantization not in (None, "none"): + raise NotImplementedError("pvt does not support quantization") + root = Path(request.model_dir) + config = validate_config(json.loads((root / "config.json").read_text())) + size = config["image_size"] + if request.image_height not in (None, size) or request.image_width not in (None, size): + raise ValueError("pvt image dimensions are fixed by the checkpoint") + processor = json.loads((root / "preprocessor_config.json").read_text()) + if not all(processor.get(name, True) for name in ("do_resize", "do_rescale", "do_normalize")): + raise NotImplementedError("pvt requires resize, rescale, and normalization") + if processor.get("rescale_factor", 1 / 255) != 1 / 255 or processor.get("resample", 3) not in (2, 3): + raise NotImplementedError("pvt unsupported image rescaling or resampling") + weights = load_file(str(root / "model.safetensors")) + writer.set_header(family="pvt", task=request.task, backend=request.backend) + writer.add_bytes("classifier.plan", compile_engine(config, weights, request.verbose)) + writer.add_json("runtime.json", {"schema_version": 1, "image_size": size, + "num_classes": int(weights["classifier.weight"].shape[0]), + "resample": processor.get("resample", 3), "image_mean": processor["image_mean"], + "image_std": processor["image_std"]}) diff --git a/families/pvt/requirements.txt b/families/pvt/requirements.txt new file mode 100644 index 0000000000..5891e78dd9 --- /dev/null +++ b/families/pvt/requirements.txt @@ -0,0 +1,2 @@ +torch>=2.6 +Pillow>=10 diff --git a/families/pvt/runtime/CMakeLists.txt b/families/pvt/runtime/CMakeLists.txt new file mode 100644 index 0000000000..d0f74ad82e --- /dev/null +++ b/families/pvt/runtime/CMakeLists.txt @@ -0,0 +1,27 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +add_library(trtmc_model_pvt SHARED pipeline.cpp plugin.cpp image_preprocess.cpp) +target_include_directories(trtmc_model_pvt PRIVATE + ${PROJECT_SOURCE_DIR} ${PROJECT_SOURCE_DIR}/core/runtime/include) +target_include_directories(trtmc_model_pvt SYSTEM PRIVATE ${TRTMC_CUDA_INCLUDE_DIR}) +target_link_libraries(trtmc_model_pvt PRIVATE + trtmc_core nlohmann_json::nlohmann_json ${TRTMC_CUDART_LIBRARY}) +target_compile_options(trtmc_model_pvt PRIVATE -Wall -Wextra -Wpedantic) +set_target_properties(trtmc_model_pvt PROPERTIES + LIBRARY_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}" + BUILD_RPATH "\$ORIGIN" INSTALL_RPATH "\$ORIGIN") +install(TARGETS trtmc_model_pvt LIBRARY DESTINATION ${CMAKE_INSTALL_LIBDIR}) + +if(TRTMC_BUILD_TESTS) + add_executable(test_pvt_preprocess ${PROJECT_SOURCE_DIR}/families/pvt/tests/cpp/test_image_preprocess.cpp) + target_include_directories(test_pvt_preprocess PRIVATE ${PROJECT_SOURCE_DIR}) + target_link_libraries(test_pvt_preprocess PRIVATE trtmc_model_pvt) + add_test(NAME pvt_preprocess COMMAND test_pvt_preprocess) + + add_executable(pvt_e2e ${PROJECT_SOURCE_DIR}/families/pvt/tests/cpp/e2e_consumer.cpp) + target_include_directories(pvt_e2e PRIVATE + ${PROJECT_SOURCE_DIR} ${PROJECT_SOURCE_DIR}/core/runtime/include) + target_link_libraries(pvt_e2e PRIVATE trtmc_runtime trtmc_core trtmc_model_pvt nlohmann_json::nlohmann_json) + set_target_properties(pvt_e2e PROPERTIES RUNTIME_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}") +endif() diff --git a/families/pvt/runtime/image_preprocess.cpp b/families/pvt/runtime/image_preprocess.cpp new file mode 100644 index 0000000000..fc5beaef47 --- /dev/null +++ b/families/pvt/runtime/image_preprocess.cpp @@ -0,0 +1,197 @@ +/* + * SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. + * SPDX-License-Identifier: Apache-2.0 + */ + +#include "families/pvt/runtime/image_preprocess.h" + +#include +#include +#include +#include +#include +#include +#include + +namespace trtmc { + +namespace { + +// Pillow's resampler, reproduced coefficient for coefficient. The reference +// processor resamples with PIL, and a float resize or a differently +// normalised kernel lands a few least-significant bits away on every pixel. +// +// The processor selects bilinear or bicubic interpolation. Their kernels +// and support radii feed the same separable coefficient calculation. +constexpr std::int32_t kPillowPrecisionBits = 22; +constexpr std::int64_t kPillowScale = std::int64_t{1} << kPillowPrecisionBits; +constexpr std::int64_t kPillowRounding = std::int64_t{1} << (kPillowPrecisionBits - 1); + +struct PillowSpan { + std::int32_t first{0}; + std::vector weights; +}; + +double pillow_bilinear(double value) { + value = std::abs(value); + return value < 1.0 ? 1.0 - value : 0.0; +} + +double pillow_bicubic(double value) { + constexpr double kA = -0.5; + value = std::abs(value); + if (value < 1.0) + return ((kA + 2.0) * value - (kA + 3.0)) * value * value + 1.0; + if (value < 2.0) + return ((kA * value - 5.0 * kA) * value + 8.0 * kA) * value - 4.0 * kA; + return 0.0; +} + +double filter_support(PvtResample resample) { + return resample == PvtResample::kBicubic ? 2.0 : 1.0; +} + +double apply_filter(PvtResample resample, double value) { + return resample == PvtResample::kBicubic ? pillow_bicubic(value) : pillow_bilinear(value); +} + +std::vector make_pillow_plan(std::int32_t input_size, std::int32_t output_size, + PvtResample resample) { + const double scale = static_cast(input_size) / output_size; + const double filter_scale = std::max(scale, 1.0); + const double support = filter_support(resample) * filter_scale; + const double inverse_filter_scale = 1.0 / filter_scale; + std::vector plan(static_cast(output_size)); + for (std::int32_t output_index = 0; output_index < output_size; ++output_index) { + const double center = (static_cast(output_index) + 0.5) * scale; + const auto first = + std::max(0, static_cast(center - support + 0.5)); + const auto end = + std::min(input_size, static_cast(center + support + 0.5)); + if (end <= first) + throw std::runtime_error("pvt Pillow resize produced empty support"); + + auto& span = plan[static_cast(output_index)]; + span.first = first; + std::vector floating(static_cast(end - first)); + double total = 0.0; + for (std::int32_t index = first; index < end; ++index) { + const double weight = apply_filter( + resample, (static_cast(index) - center + 0.5) * inverse_filter_scale); + floating[static_cast(index - first)] = weight; + total += weight; + } + if (!std::isfinite(total) || total == 0.0) + throw std::runtime_error("pvt Pillow resize has invalid coefficients"); + span.weights.reserve(floating.size()); + for (double weight : floating) { + const double scaled = weight / total * static_cast(kPillowScale); + if (!std::isfinite(scaled) || + scaled < static_cast(std::numeric_limits::min()) || + scaled > static_cast(std::numeric_limits::max())) { + throw std::runtime_error("pvt Pillow resize coefficient overflowed"); + } + span.weights.push_back( + static_cast(scaled < 0.0 ? scaled - 0.5 : scaled + 0.5)); + } + } + return plan; +} + +std::uint8_t apply_pillow_span(const std::uint8_t* source, std::int32_t stride, + const PillowSpan& span) { + std::int64_t sum = kPillowRounding; + for (std::size_t index = 0; index < span.weights.size(); ++index) { + sum += static_cast( + source[(span.first + static_cast(index)) * stride]) * + span.weights[index]; + } + if (sum <= 0) + return 0; + return static_cast(std::min(sum >> kPillowPrecisionBits, 255)); +} + +std::vector resize_pillow(const float* source, std::int32_t input_h, std::int32_t input_w, + std::int32_t output_h, std::int32_t output_w, + PvtResample resample) { + std::vector input(static_cast(input_h) * input_w * 3U); + std::transform(source, source + input.size(), input.begin(), [](float value) { + return static_cast(std::lround(std::clamp(value, 0.0F, 1.0F) * 255.0F)); + }); + + const auto horizontal_plan = make_pillow_plan(input_w, output_w, resample); + std::vector horizontal(static_cast(input_h) * output_w * 3U); + for (std::int32_t y = 0; y < input_h; ++y) { + for (std::int32_t x = 0; x < output_w; ++x) { + const auto& span = horizontal_plan[static_cast(x)]; + for (std::int32_t channel = 0; channel < 3; ++channel) { + const auto source_offset = static_cast(y) * input_w * 3U + channel; + const auto target = (static_cast(y) * output_w + x) * 3U + channel; + horizontal[target] = apply_pillow_span(input.data() + source_offset, 3, span); + } + } + } + + const auto vertical_plan = make_pillow_plan(input_h, output_h, resample); + std::vector output(static_cast(output_h) * output_w * 3U); + for (std::int32_t y = 0; y < output_h; ++y) { + const auto& span = vertical_plan[static_cast(y)]; + for (std::int32_t x = 0; x < output_w; ++x) { + for (std::int32_t channel = 0; channel < 3; ++channel) { + const auto source_offset = static_cast(x) * 3U + channel; + const auto target = (static_cast(y) * output_w + x) * 3U + channel; + output[target] = static_cast(apply_pillow_span( + horizontal.data() + source_offset, output_w * 3, span)) / + 255.0F; + } + } + } + return output; +} + +void validate(const PvtPreprocessConfig& config) { + if (config.input_image_h <= 0 || config.input_image_w <= 0) + throw std::invalid_argument("pvt input dimensions must be positive"); + if (config.image_mean.size() != 3 || config.image_std.size() != 3) + throw std::invalid_argument("pvt image mean/std must contain three channels"); + for (float value : config.image_std) { + if (value == 0.0F) + throw std::invalid_argument("pvt image std must be non-zero"); + } + if (config.resample != PvtResample::kBilinear && config.resample != PvtResample::kBicubic) + throw std::invalid_argument("pvt supports bilinear and bicubic resize only"); +} + +} // namespace + +std::vector preprocess_pvt_image(const float* image_pixels, std::int32_t image_height, + std::int32_t image_width, + const PvtPreprocessConfig& config) { + if (image_pixels == nullptr || image_height <= 0 || image_width <= 0) + throw std::invalid_argument("pvt source image must be non-empty"); + validate(config); + + // Straight to the target in both axes. There is no shortest-edge rule and + // no crop to follow it: every pixel of the original is represented, + // squashed. Preserving the aspect ratio here would feed the tower a + // different image than the reference saw. + const auto resized = resize_pillow(image_pixels, image_height, image_width, + config.input_image_h, config.input_image_w, config.resample); + + const auto plane = static_cast(config.input_image_h) * config.input_image_w; + std::vector pixel_values(3U * plane); + for (std::int32_t y = 0; y < config.input_image_h; ++y) { + for (std::int32_t x = 0; x < config.input_image_w; ++x) { + const auto source = static_cast((y * config.input_image_w + x) * 3); + for (std::int32_t c = 0; c < 3; ++c) { + const auto channel = static_cast(c); + pixel_values[channel * plane + static_cast(y) * config.input_image_w + + x] = (resized[source + channel] - config.image_mean[channel]) / + config.image_std[channel]; + } + } + } + return pixel_values; +} + +} // namespace trtmc diff --git a/families/pvt/runtime/image_preprocess.h b/families/pvt/runtime/image_preprocess.h new file mode 100644 index 0000000000..7d0aff28e5 --- /dev/null +++ b/families/pvt/runtime/image_preprocess.h @@ -0,0 +1,31 @@ +/* + * SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. + * SPDX-License-Identifier: Apache-2.0 + */ + +#pragma once + +#include +#include + +namespace trtmc { + +// Pillow's filter numbers, as a preprocessor config spells them. +enum class PvtResample : std::int32_t { kBilinear = 2, kBicubic = 3 }; + +struct PvtPreprocessConfig { + std::int32_t input_image_h{224}; + std::int32_t input_image_w{224}; + PvtResample resample{PvtResample::kBilinear}; + std::vector image_mean{0.5F, 0.5F, 0.5F}; + std::vector image_std{0.5F, 0.5F, 0.5F}; +}; + +// PVT squashes the whole image onto the square: no aspect-ratio preservation +// and no centre crop. Exposed so the unit test can pin both the framing and +// the choice of filter without running an engine. +std::vector preprocess_pvt_image(const float* image_pixels, std::int32_t image_height, + std::int32_t image_width, + const PvtPreprocessConfig& config); + +} // namespace trtmc diff --git a/families/pvt/runtime/pipeline.cpp b/families/pvt/runtime/pipeline.cpp new file mode 100644 index 0000000000..580ecca5ac --- /dev/null +++ b/families/pvt/runtime/pipeline.cpp @@ -0,0 +1,51 @@ +/* + * SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. + * SPDX-License-Identifier: Apache-2.0 + */ + +#include "families/pvt/runtime/pipeline.h" + +#include +#include +#include + +namespace trtmc::pvt { + +Pipeline::Pipeline(std::unique_ptr classifier, PvtPreprocessConfig preprocess, + std::int32_t classes) + : classifier_(std::move(classifier)), preprocess_(std::move(preprocess)), classes_(classes) { + if (!classifier_ || !classifier_->ok() || classes_ <= 0) + throw std::invalid_argument("pvt requires a loaded classifier and positive class count"); +} + +ClassificationResult Pipeline::classify(const float* pixels, std::int32_t height, std::int32_t width) { + if (!pixels || height <= 0 || width <= 0) + throw std::invalid_argument("pvt source image must be nonempty"); + const auto count = static_cast(height) * width * 3; + if (!std::all_of(pixels, pixels + count, [](float value) { return std::isfinite(value); })) + throw std::invalid_argument("pvt source image must contain finite RGB values"); + auto input = preprocess_pvt_image(pixels, height, width, preprocess_); + Tensor tensor; + tensor.data = input.data(); + tensor.shape = {1, 3, preprocess_.input_image_h, preprocess_.input_image_w}; + tensor.dtype = DType::kFloat32; + const auto outputs = classifier_->forward({{"pixel_values", tensor}}); + const auto found = outputs.find("logits"); + if (found == outputs.end() || found->second.dtype != DType::kFloat32 || + found->second.shape != std::vector{1, classes_} || !found->second.data) + throw std::runtime_error("pvt classifier returned invalid logits"); + const auto* values = static_cast(found->second.data); + ClassificationResult result; + result.logits.assign(values, values + classes_); + if (!std::all_of(result.logits.begin(), result.logits.end(), [](float value) { return std::isfinite(value); })) + throw std::runtime_error("pvt classifier returned nonfinite logits"); + const auto top = std::max_element(result.logits.begin(), result.logits.end()); + result.top_class = static_cast(top - result.logits.begin()); + double sum = 0; + for (const auto value : result.logits) + sum += std::exp(static_cast(value) - *top); + result.top_score = static_cast(1 / sum); + return result; +} + +} // namespace trtmc::pvt diff --git a/families/pvt/runtime/pipeline.h b/families/pvt/runtime/pipeline.h new file mode 100644 index 0000000000..b734809e93 --- /dev/null +++ b/families/pvt/runtime/pipeline.h @@ -0,0 +1,25 @@ +/* + * SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. + * SPDX-License-Identifier: Apache-2.0 + */ + +#pragma once + +#include "families/pvt/runtime/image_preprocess.h" +#include "trtmc/runtime/trt_module.h" +#include "trtmc/task.h" + +namespace trtmc::pvt { + +class Pipeline final : public IImageClassification { + public: + Pipeline(std::unique_ptr classifier, PvtPreprocessConfig preprocess, std::int32_t classes); + ClassificationResult classify(const float* pixels, std::int32_t height, std::int32_t width) override; + + private: + std::unique_ptr classifier_; + PvtPreprocessConfig preprocess_; + std::int32_t classes_; +}; + +} // namespace trtmc::pvt diff --git a/families/pvt/runtime/plugin.cpp b/families/pvt/runtime/plugin.cpp new file mode 100644 index 0000000000..ffb3fbce41 --- /dev/null +++ b/families/pvt/runtime/plugin.cpp @@ -0,0 +1,34 @@ +/* + * SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. + * SPDX-License-Identifier: Apache-2.0 + */ + +#include "families/pvt/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("pvt does not support --kv-cache-size"); + auto section = [&](const char* name) { + const auto* found = context.reader.find_section(name); + if (!found || found->length == 0) + throw std::runtime_error(std::string("pvt missing section: ") + name); + return context.reader.read_section(name); + }; + const auto data = section("runtime.json"); + const auto json = nlohmann::json::parse(data.begin(), data.end()); + if (json.at("schema_version").get() != 1) + throw std::invalid_argument("pvt unsupported runtime schema"); + trtmc::PvtPreprocessConfig preprocess; + preprocess.input_image_h = preprocess.input_image_w = json.at("image_size"); + preprocess.resample = static_cast(json.at("resample").get()); + preprocess.image_mean = json.at("image_mean").get>(); + preprocess.image_std = json.at("image_std").get>(); + const auto plan = section("classifier.plan"); + return new trtmc::pvt::Pipeline(context.backend.create_module(plan.data(), plan.size(), {}), + std::move(preprocess), json.at("num_classes")); +} diff --git a/families/pvt/support.py b/families/pvt/support.py new file mode 100644 index 0000000000..acb269cccd --- /dev/null +++ b/families/pvt/support.py @@ -0,0 +1,7 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +from tensorrt_model_connect.model_support import family_support + +describe = family_support(model_types=("pvt",), tasks=("classification",), + default_task="classification", default_precision="fp32") diff --git a/families/pvt/tests/__init__.py b/families/pvt/tests/__init__.py new file mode 100644 index 0000000000..52a7a9daf0 --- /dev/null +++ b/families/pvt/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/pvt/tests/cpp/e2e_consumer.cpp b/families/pvt/tests/cpp/e2e_consumer.cpp new file mode 100644 index 0000000000..3fbaae1453 --- /dev/null +++ b/families/pvt/tests/cpp/e2e_consumer.cpp @@ -0,0 +1,69 @@ +/* + * SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. + * SPDX-License-Identifier: Apache-2.0 + */ + +#include "families/pvt/runtime/image_preprocess.h" +#include "trtmc/bundle.h" +#include "trtmc/runtime/family_loader.h" + +#include +#include +#include +#include + +int main(int argc, char** argv) { + try { + if (argc != 5) + throw std::invalid_argument("usage: pvt_e2e BUNDLE RUNTIME_ROOT REQUESTS_JSON OUTPUT_DIRECTORY"); + std::ifstream input(argv[3]); + const auto requests = nlohmann::json::parse(input); + const trtmc::BundleReader bundle(argv[1]); + const auto data = bundle.read_section("runtime.json"); + const auto json = nlohmann::json::parse(data.begin(), data.end()); + trtmc::PvtPreprocessConfig preprocess; + preprocess.input_image_h = preprocess.input_image_w = json.at("image_size"); + preprocess.image_mean = json.at("image_mean").get>(); + preprocess.image_std = json.at("image_std").get>(); + preprocess.resample = static_cast(json.at("resample").get()); + auto model = trtmc::load_task(bundle, argv[2]); + auto* task = dynamic_cast(model.get()); + if (!task || std::string(task->task()) != "classification") + throw std::runtime_error("PVT does not expose the abstract image classification Task"); + nlohmann::json results = nlohmann::json::array(); + std::size_t index = 0; + for (const auto& request : requests) { + auto pixels = request.at("pixels").get>(); + const auto height = request.at("height").get(); + const auto width = request.at("width").get(); + if (height <= 0 || width <= 0 || pixels.size() != static_cast(height) * width * 3) + throw std::invalid_argument("PVT test request has invalid image storage"); + const auto normalized = trtmc::preprocess_pvt_image(pixels.data(), height, width, preprocess); + std::ofstream output(std::string(argv[4]) + "/preprocess-" + std::to_string(index++) + ".bin", std::ios::binary); + output.write(reinterpret_cast(normalized.data()), normalized.size() * sizeof(float)); + if (!output) + throw std::runtime_error("PVT could not save preprocessing boundary"); + const auto result = task->classify(pixels.data(), height, width); + results.push_back({{"logits", result.logits}, {"top_class", result.top_class}, + {"top_score", result.top_score}}); + } + bool rejected = false; + try { + task->classify(nullptr, 0, 0); + } catch (const std::invalid_argument&) { + rejected = true; + } + if (!rejected) + throw std::runtime_error("PVT accepted an empty image"); + const auto& first = requests.at(0); + const auto pixels = first.at("pixels").get>(); + const auto retry = task->classify(pixels.data(), first.at("height"), first.at("width")); + if (retry.logits != results.at(0).at("logits").get>()) + throw std::runtime_error("PVT state leaked after a rejected request"); + std::cout << results.dump() << '\n'; + return 0; + } catch (const std::exception& error) { + std::cerr << error.what() << '\n'; + return 1; + } +} diff --git a/families/pvt/tests/cpp/test_image_preprocess.cpp b/families/pvt/tests/cpp/test_image_preprocess.cpp new file mode 100644 index 0000000000..39464e7a86 --- /dev/null +++ b/families/pvt/tests/cpp/test_image_preprocess.cpp @@ -0,0 +1,170 @@ +/* + * SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. + * SPDX-License-Identifier: Apache-2.0 + */ + +#include "families/pvt/runtime/image_preprocess.h" + +#include +#include +#include +#include + +namespace { + +int g_failures = 0; + +void check(bool condition, const char* name) { + if (!condition) { + std::cerr << "FAIL: " << name << '\n'; + ++g_failures; + } +} + +void check_close(float actual, float expected, float tolerance, const char* name) { + if (std::fabs(actual - expected) > tolerance) { + std::cerr << "FAIL: " << name << " actual=" << actual << " expected=" << expected << '\n'; + ++g_failures; + } +} + +trtmc::PvtPreprocessConfig base_config(std::int32_t side) { + trtmc::PvtPreprocessConfig config; + config.input_image_h = side; + config.input_image_w = side; + config.resample = trtmc::PvtResample::kBilinear; + return config; +} + +std::vector half_and_half(std::int32_t height, std::int32_t width, float left, float right) { + std::vector pixels(static_cast(height) * width * 3U); + for (std::int32_t y = 0; y < height; ++y) { + for (std::int32_t x = 0; x < width; ++x) { + const float value = x < width / 2 ? left : right; + for (std::int32_t c = 0; c < 3; ++c) + pixels[(static_cast(y) * width + x) * 3U + c] = value; + } + } + return pixels; +} + +void test_a_wide_image_is_squashed_not_cropped() { + // PVT squashes the whole image onto the square: no aspect-ratio rule and + // no crop. A 64x256 source is four times wider than tall, and the colour + // boundary must stay in the middle of the output. Scaling the short edge + // and cropping - which is what CLIP and DINOv2 do - would throw away + // three quarters of the width. + const auto config = base_config(32); + const auto pixels = half_and_half(64, 256, 0.0F, 1.0F); + const auto out = trtmc::preprocess_pvt_image(pixels.data(), 64, 256, config); + check(out.size() == 3U * 32U * 32U, "output is CHW at the configured size"); + + const auto at = [&](std::int32_t c, std::int32_t y, std::int32_t x) { + return out[static_cast(c) * 32U * 32U + static_cast(y) * 32U + x]; + }; + // mean 0.5, std 0.5: a 0.0 pixel becomes -1 and a 1.0 pixel becomes +1. + check_close(at(0, 16, 2), -1.0F, 1e-3F, "the left edge survives the squash"); + check_close(at(0, 16, 29), 1.0F, 1e-3F, "the right edge survives the squash"); + check(at(0, 16, 14) < 0.0F && at(0, 16, 17) > 0.0F, "the boundary stays at the centre"); +} + +void test_bilinear_and_bicubic_are_different_filters() { + // This is the rule that separates PVT from the other image families here: + // it resamples BILINEAR where they resample bicubic. The two are close on + // a flat field and visibly different across an edge, because only the + // cubic kernel overshoots. Measured on the whole model, swapping them + // moves the logits by 0.376 and changes the top-5, so the seam must not + // treat them as interchangeable. + auto bilinear = base_config(16); + auto bicubic = base_config(16); + bicubic.resample = trtmc::PvtResample::kBicubic; + + const auto pixels = half_and_half(64, 64, 0.0F, 1.0F); + const auto a = trtmc::preprocess_pvt_image(pixels.data(), 64, 64, bilinear); + const auto b = trtmc::preprocess_pvt_image(pixels.data(), 64, 64, bicubic); + check(a.size() == b.size(), "both filters produce the same shape"); + + float worst = 0.0F; + for (std::size_t index = 0; index < a.size(); ++index) + worst = std::max(worst, std::fabs(a[index] - b[index])); + check(worst > 1e-3F, "bilinear and bicubic are not the same filter"); + + // Only the cubic kernel has negative lobes, so only it can overshoot past + // the input range. The bilinear output is a convex combination and cannot. + float bilinear_max = -1e9F; + for (float value : a) + bilinear_max = std::max(bilinear_max, value); + check(bilinear_max <= 1.0F + 1e-4F, "bilinear never overshoots its input range"); +} + +void test_a_flat_image_is_unchanged_by_either_filter() { + // Both kernels are normalised to sum to one, so a constant field resizes + // to the same constant. This catches a mis-normalised weight table, which + // would otherwise show up only as a slight overall brightness shift. + for (auto resample : {trtmc::PvtResample::kBilinear, trtmc::PvtResample::kBicubic}) { + auto config = base_config(8); + config.resample = resample; + config.image_mean = {0.0F, 0.0F, 0.0F}; + config.image_std = {1.0F, 1.0F, 1.0F}; + std::vector pixels(static_cast(40) * 40 * 3U, 0.6F); + const auto out = trtmc::preprocess_pvt_image(pixels.data(), 40, 40, config); + for (float value : out) + check_close(value, 0.6F, 3e-3F, "a flat field survives the resize"); + } +} + +void test_normalisation_is_per_channel() { + auto config = base_config(4); + config.image_mean = {0.0F, 0.5F, 1.0F}; + config.image_std = {1.0F, 0.5F, 2.0F}; + std::vector pixels(3U * 4U * 4U, 1.0F); + const auto out = trtmc::preprocess_pvt_image(pixels.data(), 4, 4, config); + const auto plane = static_cast(16); + check_close(out[0], 1.0F, 1e-5F, "channel 0 uses its own mean and deviation"); + check_close(out[plane], 1.0F, 1e-5F, "channel 1 uses its own mean and deviation"); + check_close(out[2 * plane], 0.0F, 1e-5F, "channel 2 uses its own mean and deviation"); +} + +void test_invalid_input_is_refused() { + auto config = base_config(4); + bool threw = false; + try { + trtmc::preprocess_pvt_image(nullptr, 4, 4, config); + } catch (const std::invalid_argument&) { + threw = true; + } + check(threw, "a null image is refused"); + + threw = false; + config.image_std = {1.0F, 0.0F, 1.0F}; + std::vector pixels(3U * 4U * 4U, 0.5F); + try { + trtmc::preprocess_pvt_image(pixels.data(), 4, 4, config); + } catch (const std::invalid_argument&) { + threw = true; + } + check(threw, "a zero standard deviation is refused"); + + threw = false; + config = base_config(4); + config.resample = static_cast(0); // NEAREST + try { + trtmc::preprocess_pvt_image(pixels.data(), 4, 4, config); + } catch (const std::invalid_argument&) { + threw = true; + } + check(threw, "an unsupported filter is refused rather than approximated"); +} + +} // namespace + +int main() { + test_a_wide_image_is_squashed_not_cropped(); + test_bilinear_and_bicubic_are_different_filters(); + test_a_flat_image_is_unchanged_by_either_filter(); + test_normalisation_is_per_channel(); + test_invalid_input_is_refused(); + if (g_failures == 0) + std::cout << "pvt image preprocess: all checks passed\n"; + return g_failures == 0 ? 0 : 1; +} diff --git a/families/pvt/tests/manifests/pvt-tiny.json b/families/pvt/tests/manifests/pvt-tiny.json new file mode 100644 index 0000000000..0b98522876 --- /dev/null +++ b/families/pvt/tests/manifests/pvt-tiny.json @@ -0,0 +1,22 @@ +{ + "name": "pvt-tiny", + "hf_id": "Zetatech/pvt-tiny-224", + "hf_revision": "6a44ba96dda6a6f3e2b6913682acfa0071482e83", + "bundle": "pvt-tiny.bundle", + "family": "pvt", + "task": "classification", + "precision": "fp32", + "tensor_parallel_size": 1, + "testcases": [ + { + "name": "pvt-tiny-asymmetric-images", + "premerge": true, + "reference_precision": "fp32", + "fixture_seed": 2026, + "image_shapes": [[37, 83], [67, 45]], + "max_preprocess_abs_error": 0.000001, + "max_logits_abs_error": 0.0003, + "max_probability_abs_error": 0.00001 + } + ] +} diff --git a/families/pvt/tests/test_e2e.py b/families/pvt/tests/test_e2e.py new file mode 100644 index 0000000000..487c41dbcb --- /dev/null +++ b/families/pvt/tests/test_e2e.py @@ -0,0 +1,111 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +"""PVT processor, spatial-reduction graph, and native classification Task parity.""" + +import json +import os +from pathlib import Path +import subprocess + +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/pvt-tiny.json").read_text()) + + +def pytest_generate_tests(metafunc): + if "case" not in metafunc.fixturenames: + return + models = set() + for value in metafunc.config.getoption("--e2e-model"): + models.update(value.split(",")) + models_file = metafunc.config.getoption("--e2e-models-file") + if models_file: + models.update(Path(models_file).read_text().splitlines()) + cases = set() + for value in metafunc.config.getoption("--e2e-testcase"): + cases.update(value.split(",")) + parameters = [] + for case in MANIFEST["testcases"]: + if models and not models.intersection({"pvt", MANIFEST["name"], case["name"]}): + continue + if cases and case["name"] not in cases: + continue + marks = [] if models or cases else [pytest.mark.skip(reason="select PVT E2E explicitly")] + parameters.append(pytest.param(case, id=case["name"], marks=marks)) + metafunc.parametrize("case", parameters) + + +def _checkpoint(): + explicit = os.environ.get("TRTMC_PVT_MODEL_DIR") + if explicit: + return Path(explicit) + from huggingface_hub import snapshot_download + return Path(snapshot_download(repo_id=MANIFEST["hf_id"], revision=MANIFEST["hf_revision"], + local_files_only=True)) + + +def test_official_checkpoint_e2e(case, tmp_path): + import torch + from transformers import PvtForImageClassification, PvtImageProcessor + + assert case["reference_precision"] == "fp32" + torch.backends.cuda.matmul.allow_tf32 = False + torch.backends.cudnn.allow_tf32 = False + root = _checkpoint() + assert resolve_family(load_model_metadata(root))[0] == MANIFEST["family"] + runtime = Path(os.environ["TRTMC_RUNTIME_ROOT"]) + assert (runtime / "libtrtmc_model_pvt.so").is_file() + consumer = runtime / "pvt_e2e" + assert consumer.is_file() + generator = np.random.default_rng(case["fixture_seed"]) + images = [generator.integers(0, 256, size=(height, width, 3), dtype=np.uint8) + for height, width in case["image_shapes"]] + images.append(images[0]) + record_evidence("inputs", {"manifest": MANIFEST, "case": case, "images": images}) + record_evidence("checkpoint", {"model_dir": str(root), "hf_id": MANIFEST["hf_id"], + "hf_revision": MANIFEST["hf_revision"]}) + with evidence_stage("reference"): + processor = PvtImageProcessor.from_pretrained(root, local_files_only=True) + model = PvtForImageClassification.from_pretrained(root, dtype=torch.float32, + trust_remote_code=False).cuda().eval() + reference = [] + for image in images: + inputs = processor(images=image, return_tensors="pt") + with torch.inference_mode(): + logits = model(**{name: tensor.cuda() for name, tensor in inputs.items()}).logits[0] + reference.append({"pixel_values": inputs.pixel_values.numpy(), + "logits": logits.cpu().numpy(), "top_class": int(logits.argmax()), + "top_score": float(logits.softmax(dim=-1).max())}) + assert not np.array_equal(reference[0]["logits"], reference[1]["logits"]) + record_evidence("reference", reference) + 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"])) + requests = tmp_path / "requests.json" + requests.write_text(json.dumps([{"height": image.shape[0], "width": image.shape[1], + "pixels": (image.astype(np.float32) / 255).reshape(-1).tolist()} for image in images])) + with evidence_stage("native"): + command = [str(consumer), str(bundle), str(runtime), str(requests), str(tmp_path)] + completed = subprocess.run(command, check=True, text=True, capture_output=True, timeout=300) + record_evidence("commands", {"argv": command}) + actual = json.loads(completed.stdout.strip().splitlines()[-1]) + record_evidence("native", actual) + with evidence_stage("compare"): + assert len(actual) == len(reference) + for index, (result, expected) in enumerate(zip(actual, reference)): + pixels = np.fromfile(tmp_path / f"preprocess-{index}.bin", dtype=np.float32).reshape(1, 3, 224, 224) + np.testing.assert_allclose(pixels, expected["pixel_values"], rtol=0, + atol=case["max_preprocess_abs_error"]) + logits = np.asarray(result["logits"], dtype=np.float32) + assert logits.shape == (1000,) and np.isfinite(logits).all() + np.testing.assert_allclose(logits, expected["logits"], rtol=0, atol=case["max_logits_abs_error"]) + assert result["top_class"] == expected["top_class"] + assert abs(result["top_score"] - expected["top_score"]) <= case["max_probability_abs_error"] + assert actual[0] == actual[2] diff --git a/families/pvt/tests/test_model.py b/families/pvt/tests/test_model.py new file mode 100644 index 0000000000..ddf6990739 --- /dev/null +++ b/families/pvt/tests/test_model.py @@ -0,0 +1,28 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +from dataclasses import replace + +import pytest + +from tensorrt_model_connect import BuildRequest +from families.pvt.model import build, validate_config + + +def test_class_token_stage_retains_its_full_sequence(): + config = {"model_type": "pvt", "num_encoder_blocks": 4, "hidden_sizes": [64,128,320,512], + "depths": [2,2,2,2], "num_attention_heads": [1,2,5,8], + "sequence_reduction_ratios": [8,4,2,1], "patch_sizes": [4,2,2,2], + "strides": [4,2,2,2], "mlp_ratios": [8,8,4,4]} + validate_config(config) + with pytest.raises(ValueError, match="class-token"): + validate_config({**config, "sequence_reduction_ratios": [8,4,2,2]}) + + +def test_unsupported_profiles_fail_before_checkpoint_access(tmp_path): + request = BuildRequest(tmp_path, tmp_path / "out.bundle", "pvt", "classification", "fp32") + for update in ({"precision": "fp16"}, {"task": "embedding"}, {"tensor_parallel_size": 2}, + {"max_batch_size": 2}, {"max_sequence_length": 32}, + {"dynamic_kv_cache": True}, {"quantization": "fp8"}): + with pytest.raises((ValueError, NotImplementedError)): + build(replace(request, **update), None) diff --git a/families/pvt/tests/test_support.py b/families/pvt/tests/test_support.py new file mode 100644 index 0000000000..3901ad2936 --- /dev/null +++ b/families/pvt/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.pvt.support import describe + + +def test_pvt_classification_owner(): + metadata = ModelMetadata(config={"model_type": "pvt", "architectures": ["PvtForImageClassification"]}, + model_index={}) + family, support = resolve_family(metadata) + assert family == "pvt" + assert support.default_task == "classification" + assert describe(ModelMetadata(config={"model_type": "pvt_v2"}, model_index={})) is None From 7fa6602b78cf1dad317db64b13175c956d9fb720 Mon Sep 17 00:00:00 2001 From: Will Guo Date: Wed, 2 Dec 2026 20:22:56 -0800 Subject: [PATCH 2/2] fix(pvt): broadcast scalar normalization and retain E2E evidence Signed-off-by: Will Guo --- families/pvt/model.py | 15 ++++++++++++-- .../pvt/tests/cpp/test_image_preprocess.cpp | 20 +++++++++---------- families/pvt/tests/test_e2e.py | 9 +++++---- 3 files changed, 27 insertions(+), 17 deletions(-) diff --git a/families/pvt/model.py b/families/pvt/model.py index 6c62ae2bf1..2db78ed9e0 100644 --- a/families/pvt/model.py +++ b/families/pvt/model.py @@ -185,10 +185,21 @@ def build(request, writer): raise NotImplementedError("pvt requires resize, rescale, and normalization") if processor.get("rescale_factor", 1 / 255) != 1 / 255 or processor.get("resample", 3) not in (2, 3): raise NotImplementedError("pvt unsupported image rescaling or resampling") + normalization = {} + for name in ("image_mean", "image_std"): + value = processor[name] + values = [value] * 3 if type(value) in (int, float) else value + if ( + not isinstance(values, list) + or len(values) != 3 + or any(type(channel) not in (int, float) or not np.isfinite(channel) for channel in values) + or (name == "image_std" and min(values) <= 0) + ): + raise ValueError(f"pvt requires valid {name} for three channels") + normalization[name] = values weights = load_file(str(root / "model.safetensors")) writer.set_header(family="pvt", task=request.task, backend=request.backend) writer.add_bytes("classifier.plan", compile_engine(config, weights, request.verbose)) writer.add_json("runtime.json", {"schema_version": 1, "image_size": size, "num_classes": int(weights["classifier.weight"].shape[0]), - "resample": processor.get("resample", 3), "image_mean": processor["image_mean"], - "image_std": processor["image_std"]}) + "resample": processor.get("resample", 3), **normalization}) diff --git a/families/pvt/tests/cpp/test_image_preprocess.cpp b/families/pvt/tests/cpp/test_image_preprocess.cpp index 39464e7a86..f012d4626c 100644 --- a/families/pvt/tests/cpp/test_image_preprocess.cpp +++ b/families/pvt/tests/cpp/test_image_preprocess.cpp @@ -22,7 +22,7 @@ void check(bool condition, const char* name) { } void check_close(float actual, float expected, float tolerance, const char* name) { - if (std::fabs(actual - expected) > tolerance) { + if (!std::isfinite(actual) || std::fabs(actual - expected) > tolerance) { std::cerr << "FAIL: " << name << " actual=" << actual << " expected=" << expected << '\n'; ++g_failures; } @@ -36,11 +36,11 @@ trtmc::PvtPreprocessConfig base_config(std::int32_t side) { return config; } -std::vector half_and_half(std::int32_t height, std::int32_t width, float left, float right) { +std::vector vertical_bands(std::int32_t height, std::int32_t width, std::int32_t boundary) { std::vector pixels(static_cast(height) * width * 3U); for (std::int32_t y = 0; y < height; ++y) { for (std::int32_t x = 0; x < width; ++x) { - const float value = x < width / 2 ? left : right; + const float value = x < boundary ? 0.0F : 1.0F; for (std::int32_t c = 0; c < 3; ++c) pixels[(static_cast(y) * width + x) * 3U + c] = value; } @@ -49,13 +49,10 @@ std::vector half_and_half(std::int32_t height, std::int32_t width, float } void test_a_wide_image_is_squashed_not_cropped() { - // PVT squashes the whole image onto the square: no aspect-ratio rule and - // no crop. A 64x256 source is four times wider than tall, and the colour - // boundary must stay in the middle of the output. Scaling the short edge - // and cropping - which is what CLIP and DINOv2 do - would throw away - // three quarters of the width. + // Squashing a 64x256 image to 32x32 puts the boundary at column 8. + // Scaling the short edge and center-cropping would discard the black band. const auto config = base_config(32); - const auto pixels = half_and_half(64, 256, 0.0F, 1.0F); + const auto pixels = vertical_bands(64, 256, 64); const auto out = trtmc::preprocess_pvt_image(pixels.data(), 64, 256, config); check(out.size() == 3U * 32U * 32U, "output is CHW at the configured size"); @@ -65,7 +62,8 @@ void test_a_wide_image_is_squashed_not_cropped() { // mean 0.5, std 0.5: a 0.0 pixel becomes -1 and a 1.0 pixel becomes +1. check_close(at(0, 16, 2), -1.0F, 1e-3F, "the left edge survives the squash"); check_close(at(0, 16, 29), 1.0F, 1e-3F, "the right edge survives the squash"); - check(at(0, 16, 14) < 0.0F && at(0, 16, 17) > 0.0F, "the boundary stays at the centre"); + check_close(at(0, 16, 6), -1.0F, 1e-3F, "the black band spans about one quarter"); + check_close(at(0, 16, 10), 1.0F, 1e-3F, "the boundary stays off center"); } void test_bilinear_and_bicubic_are_different_filters() { @@ -79,7 +77,7 @@ void test_bilinear_and_bicubic_are_different_filters() { auto bicubic = base_config(16); bicubic.resample = trtmc::PvtResample::kBicubic; - const auto pixels = half_and_half(64, 64, 0.0F, 1.0F); + const auto pixels = vertical_bands(64, 64, 32); const auto a = trtmc::preprocess_pvt_image(pixels.data(), 64, 64, bilinear); const auto b = trtmc::preprocess_pvt_image(pixels.data(), 64, 64, bicubic); check(a.size() == b.size(), "both filters produce the same shape"); diff --git a/families/pvt/tests/test_e2e.py b/families/pvt/tests/test_e2e.py index 487c41dbcb..3f747f2764 100644 --- a/families/pvt/tests/test_e2e.py +++ b/families/pvt/tests/test_e2e.py @@ -19,7 +19,7 @@ def pytest_generate_tests(metafunc): - if "case" not in metafunc.fixturenames: + if "case_name" not in metafunc.fixturenames: return models = set() for value in metafunc.config.getoption("--e2e-model"): @@ -37,8 +37,8 @@ def pytest_generate_tests(metafunc): if cases and case["name"] not in cases: continue marks = [] if models or cases else [pytest.mark.skip(reason="select PVT E2E explicitly")] - parameters.append(pytest.param(case, id=case["name"], marks=marks)) - metafunc.parametrize("case", parameters) + parameters.append(pytest.param(case["name"], marks=marks)) + metafunc.parametrize("case_name", parameters) def _checkpoint(): @@ -50,7 +50,8 @@ def _checkpoint(): local_files_only=True)) -def test_official_checkpoint_e2e(case, tmp_path): +def test_official_checkpoint_e2e(case_name, tmp_path): + case = next(case for case in MANIFEST["testcases"] if case["name"] == case_name) import torch from transformers import PvtForImageClassification, PvtImageProcessor