diff --git a/families/vit_mae/__init__.py b/families/vit_mae/__init__.py new file mode 100644 index 0000000000..9b316888e1 --- /dev/null +++ b/families/vit_mae/__init__.py @@ -0,0 +1,4 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +"""ViT-MAE visible image patch features with reproducible masking.""" diff --git a/families/vit_mae/model.py b/families/vit_mae/model.py new file mode 100644 index 0000000000..8ad716902d --- /dev/null +++ b/families/vit_mae/model.py @@ -0,0 +1,217 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +"""ViT-MAE encoder with the checkpoint mask ratio and explicit visible-patch indices.""" + +import json +from pathlib import Path + +import numpy as np +from safetensors import safe_open +import tensorrt as trt + + +def geometry(config): + if config.get("model_type") != "vit_mae": + raise ValueError("vit_mae requires model_type=vit_mae") + for key in ("hidden_size", "num_attention_heads", "num_hidden_layers", "intermediate_size", "image_size", "patch_size", "num_channels"): + if type(config.get(key)) is not int or config[key] <= 0: + raise ValueError(f"vit_mae requires positive integer {key}") + if config["hidden_size"] % config["num_attention_heads"] or config["image_size"] % config["patch_size"]: + raise ValueError("vit_mae head and patch geometry must divide their respective dimensions") + if config.get("hidden_act", "gelu") != "gelu" or config["num_channels"] != 3: + raise NotImplementedError("vit_mae requires RGB patches and exact GELU") + patches = (config["image_size"] // config["patch_size"]) ** 2 + ratio = config.get("mask_ratio", 0.75) + if not isinstance(ratio, (float, int)) or not 0 <= ratio < 1 or int(patches * (1 - ratio)) <= 0: + raise ValueError("vit_mae requires a mask ratio retaining at least one patch") + return patches, int(patches * (1 - ratio)) + + +def required_shapes(config): + patches, _ = geometry(config) + width, inner, patch = config["hidden_size"], config["intermediate_size"], config["patch_size"] + required = {"vit.embeddings.cls_token": (1, 1, width), + "vit.embeddings.position_embeddings": (1, patches + 1, width), + "vit.embeddings.patch_embeddings.projection.weight": (width, 3, patch, patch), + "vit.embeddings.patch_embeddings.projection.bias": (width,), + "vit.layernorm.weight": (width,), "vit.layernorm.bias": (width,)} + for layer in range(config["num_hidden_layers"]): + prefix = f"vit.encoder.layer.{layer}." + for norm in ("layernorm_before", "layernorm_after"): + required[prefix + norm + ".weight"] = (width,) + required[prefix + norm + ".bias"] = (width,) + for projection in ("attention.attention.query", "attention.attention.key", "attention.attention.value", "attention.output.dense"): + required[prefix + projection + ".weight"] = (width, width) + if projection == "attention.output.dense" or config.get("qkv_bias", True): + required[prefix + projection + ".bias"] = (width,) + for name, shape in (("intermediate.dense.weight", (inner, width)), ("intermediate.dense.bias", (inner,)), + ("output.dense.weight", (width, inner)), ("output.dense.bias", (width,))): + required[prefix + name] = shape + return required + + +def load_weights(root, config): + required, weights = required_shapes(config), {} + with safe_open(str(root / "model.safetensors"), framework="numpy") as source: + keys = set(source.keys()) + for key, shape in required.items(): + if key not in keys or tuple(source.get_slice(key).get_shape()) != shape: + raise ValueError(f"vit_mae missing or invalid checkpoint tensor: {key}, expected {shape}") + weights[key] = source.get_tensor(key).astype(np.float32) + return weights + + +class Graph: + def __init__(self, network, config, weights, capacity): + self.n, self.c, self.w, self.capacity = network, config, weights, capacity + self.patches, self.kept = geometry(config) + self.heads, self.dim = config["num_attention_heads"], config["hidden_size"] // config["num_attention_heads"] + self.constants = [] + + def constant(self, value, dtype=np.float32): + value = np.ascontiguousarray(value, dtype=dtype) + self.constants.append(value) + return self.n.add_constant(value.shape, trt.Weights(value)).get_output(0) + + def binary(self, x, y, operation=trt.ElementWiseOperation.SUM): + return self.n.add_elementwise(x, y, operation).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 linear(self, x, name): + x = self.n.add_matrix_multiply(x, trt.MatrixOperation.NONE, + self.constant(self.w[name + ".weight"].T), trt.MatrixOperation.NONE).get_output(0) + if name + ".bias" in self.w: + x = self.binary(x, self.constant(self.w[name + ".bias"].reshape(1, -1))) + return x + + def norm(self, x, name): + layer = self.n.add_normalization(x, self.constant(self.w[name + ".weight"].reshape(1, -1)), + self.constant(self.w[name + ".bias"].reshape(1, -1)), 1 << 1) + layer.epsilon = self.c["layer_norm_eps"] + return layer.get_output(0) + + def build(self): + width, size, patch = self.c["hidden_size"], self.c["image_size"], self.c["patch_size"] + length = self.kept + 1 + pixels = self.n.add_input("pixel_values", trt.float32, (1, 3, size, size)) + visible = self.n.add_input("visible_indices", trt.int32, (self.kept,)) + prefix = "vit.embeddings.patch_embeddings.projection" + convolution = self.n.add_convolution_nd(pixels, width, (patch, patch), + trt.Weights(self.w[prefix + ".weight"]), trt.Weights(self.w[prefix + ".bias"])) + convolution.stride_nd = (patch, patch) + x = self.reshape(convolution.get_output(0), (width, self.patches), (1, 0)) + x = self.binary(x, self.constant(self.w["vit.embeddings.position_embeddings"][0, 1:])) + x = self.n.add_gather(x, visible, 0).get_output(0) + cls = self.w["vit.embeddings.cls_token"].reshape(1, width) + self.w["vit.embeddings.position_embeddings"][0, :1] + tokens = self.n.add_concatenation([self.constant(cls), x]) + tokens.axis = 0 + x = tokens.get_output(0) + for layer in range(self.c["num_hidden_layers"]): + prefix = f"vit.encoder.layer.{layer}" + normalized = self.norm(x, prefix + ".layernorm_before") + query, key, value = [self.reshape(self.linear(normalized, prefix + ".attention.attention." + name), + (length, self.heads, self.dim), (1, 0, 2)) for name in ("query", "key", "value")] + scores = self.n.add_matrix_multiply(query, trt.MatrixOperation.NONE, key, trt.MatrixOperation.TRANSPOSE).get_output(0) + scores = self.binary(scores, self.constant([[[self.dim ** -0.5]]]), trt.ElementWiseOperation.PROD) + probabilities = self.n.add_softmax(scores) + probabilities.axes = 1 << 2 + 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 = (1, 0, 2) + merged.reshape_dims = (length, width) + x = self.binary(self.linear(merged.get_output(0), prefix + ".attention.output.dense"), x) + intermediate = self.linear(self.norm(x, prefix + ".layernorm_after"), prefix + ".intermediate.dense") + intermediate = self.n.add_activation(intermediate, trt.ActivationType.GELU_ERF).get_output(0) + x = self.binary(self.linear(intermediate, prefix + ".output.dense"), x) + x = self.norm(x, "vit.layernorm") + x.name = "last_hidden_state" + self.n.mark_output(x) + + +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, geometry(config)[1] + 1) + graph.build() + plan = builder.build_serialized_network(network, options) + if plan is None: + raise RuntimeError("vit_mae TensorRT encoder build failed") + return bytes(plan) + + +def _normalization(processor, name): + raw = processor.get(name) + if raw is None: + raw = 0.5 + values = [raw] * 3 if type(raw) in (int, float) else raw + fp32_max = float(np.finfo(np.float32).max) + if ( + not isinstance(values, list) or len(values) != 3 + or any(type(value) not in (int, float) or not abs(value) <= fp32_max for value in values) + ): + raise ValueError(f"vit_mae processor {name} requires three finite float32 channels") + with np.errstate(under="ignore"): + channels = np.asarray(values, dtype=np.float32) + if name == "image_std" and (channels == 0).any(): + raise ValueError("vit_mae processor image_std must be nonzero in float32") + return channels.tolist() + + +def build(request, writer): + if request.dynamic_kv_cache: + raise NotImplementedError("vit_mae does not support dynamic_kv_cache") + if request.task != "image_to_token_features" or request.precision != "fp32" or request.backend != "trt": + raise ValueError("vit_mae requires image_to_token_features, 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), + ("image_height", request.image_height, None), ("image_width", request.image_width, 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"vit_mae does not support {field}") + if request.quantization not in (None, "none"): + raise NotImplementedError("vit_mae does not support quantization") + root = Path(request.model_dir) + config = json.loads((root / "config.json").read_text()) + patches, kept = geometry(config) + processor = json.loads((root / "preprocessor_config.json").read_text()) + if not processor.get("do_resize", True) or not processor.get("do_normalize", True) or processor.get("resample", 2) != 2: + raise NotImplementedError("vit_mae requires its bilinear resize and channel normalization") + if processor.get("do_rescale", True) is not True or processor.get("rescale_factor", 1 / 255) != 1 / 255: + raise NotImplementedError("vit_mae requires rescaling pixels by 1/255") + size = processor.get("size") + if size is None: + size = 224 + if type(size) is int: + size = {"height": size, "width": size} + if not isinstance(size, dict) or any( + type(size.get(axis)) is not int or size[axis] != config["image_size"] + for axis in ("height", "width") + ): + raise ValueError("vit_mae processor size disagrees with checkpoint patches") + mean = _normalization(processor, "image_mean") + std = _normalization(processor, "image_std") + pixels = np.array([[0], [1]], dtype=np.float32) + with np.errstate(over="ignore"): + endpoints = (pixels - np.asarray(mean, dtype=np.float32)) / np.asarray(std, dtype=np.float32) + if not np.isfinite(endpoints).all(): + raise ValueError("vit_mae normalization must cover the pixel range in float32") + writer.set_header(family="vit_mae", task=request.task, backend=request.backend) + writer.add_bytes("model.plan", compile_engine(config, load_weights(root, config), request.verbose)) + writer.add_json("runtime.json", {"schema_version": 1, "image_size": config["image_size"], + "patch_size": config["patch_size"], "patches": patches, "kept": kept, "hidden_size": config["hidden_size"], + "image_mean": mean, "image_std": std, "resample": 2}) diff --git a/families/vit_mae/requirements.txt b/families/vit_mae/requirements.txt new file mode 100644 index 0000000000..c70b6cf852 --- /dev/null +++ b/families/vit_mae/requirements.txt @@ -0,0 +1 @@ +transformers>=5.3.0 diff --git a/families/vit_mae/runtime/CMakeLists.txt b/families/vit_mae/runtime/CMakeLists.txt new file mode 100644 index 0000000000..b6c8c2a1c5 --- /dev/null +++ b/families/vit_mae/runtime/CMakeLists.txt @@ -0,0 +1,21 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +add_library(trtmc_model_vit_mae SHARED pipeline.cpp plugin.cpp image_preprocess.cpp) +target_include_directories(trtmc_model_vit_mae PRIVATE + ${PROJECT_SOURCE_DIR} ${PROJECT_SOURCE_DIR}/core/runtime/include) +target_include_directories(trtmc_model_vit_mae SYSTEM PRIVATE ${TRTMC_CUDA_INCLUDE_DIR}) +target_link_libraries(trtmc_model_vit_mae PRIVATE + trtmc_core nlohmann_json::nlohmann_json ${TRTMC_CUDART_LIBRARY}) +target_compile_options(trtmc_model_vit_mae PRIVATE -Wall -Wextra -Wpedantic) +set_target_properties(trtmc_model_vit_mae PROPERTIES + LIBRARY_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}" + BUILD_RPATH "\$ORIGIN" INSTALL_RPATH "\$ORIGIN") +install(TARGETS trtmc_model_vit_mae LIBRARY DESTINATION ${CMAKE_INSTALL_LIBDIR}) + +if(TRTMC_BUILD_TESTS) + add_executable(vit_mae_e2e ${PROJECT_SOURCE_DIR}/families/vit_mae/tests/cpp/e2e_consumer.cpp image_preprocess.cpp) + target_include_directories(vit_mae_e2e PRIVATE ${PROJECT_SOURCE_DIR}) + target_link_libraries(vit_mae_e2e PRIVATE trtmc_c trtmc_core nlohmann_json::nlohmann_json) + set_target_properties(vit_mae_e2e PROPERTIES RUNTIME_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}") +endif() diff --git a/families/vit_mae/runtime/image_preprocess.cpp b/families/vit_mae/runtime/image_preprocess.cpp new file mode 100644 index 0000000000..db8f3f5074 --- /dev/null +++ b/families/vit_mae/runtime/image_preprocess.cpp @@ -0,0 +1,183 @@ +/* + * SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. + * SPDX-License-Identifier: Apache-2.0 + */ + +#include "families/vit_mae/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. +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; +} + +std::vector make_pillow_plan(std::int32_t input_size, std::int32_t output_size) { + const double scale = static_cast(input_size) / output_size; + const double filter_scale = std::max(scale, 1.0); + 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 = static_cast(std::max(0.0, center - filter_scale + 0.5)); + const auto end = static_cast( + std::min(static_cast(input_size), center + filter_scale + 0.5)); + if (end <= first) + throw std::runtime_error("vit_mae 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 = + pillow_bilinear((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("vit_mae 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("vit_mae 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::size_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_axis(const std::vector& source, std::int32_t input_h, + std::int32_t input_w, std::int32_t output_size, + bool vertical) { + const auto plan = make_pillow_plan(vertical ? input_h : input_w, output_size); + const auto output_h = vertical ? output_size : input_h; + const auto output_w = vertical ? input_w : output_size; + const auto stride = vertical ? static_cast(input_w) * 3U : 3U; + std::vector result(static_cast(output_h) * output_w * 3U); + for (std::int32_t y = 0; y < output_h; ++y) { + for (std::int32_t x = 0; x < output_w; ++x) { + const auto& span = plan[vertical ? y : x]; + const auto offset = vertical ? static_cast(x) * 3U + : static_cast(y) * input_w * 3U; + const auto target = (static_cast(y) * output_w + x) * 3U; + for (std::size_t channel = 0; channel < 3; ++channel) + result[target + channel] = + apply_pillow_span(source.data() + offset + channel, stride, span); + } + } + return result; +} + +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) { + 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)); + }); + // Pillow rounds each pass to bytes, so its choice of the first axis matters. + const auto shrink_y = static_cast(input_h) - output_h; + const auto shrink_x = static_cast(input_w) - output_w; + if (shrink_y <= 0 || shrink_y <= 2 * shrink_x) { + const auto horizontal = resize_axis(input, input_h, input_w, output_w, false); + return resize_axis(horizontal, input_h, output_w, output_h, true); + } + const auto vertical = resize_axis(input, input_h, input_w, output_h, true); + return resize_axis(vertical, output_h, input_w, output_w, false); +} + +} // namespace + +void validate_vit_mae_preprocess(const VitMaePreprocessConfig& config) { + if (config.input_image_h <= 0 || config.input_image_w <= 0) + throw std::invalid_argument("vit_mae input dimensions must be positive"); + if (config.image_mean.size() != 3 || config.image_std.size() != 3) + throw std::invalid_argument("vit_mae image mean/std must contain three channels"); + for (std::size_t channel = 0; channel < config.image_mean.size(); ++channel) { + const auto mean = config.image_mean[channel]; + const auto deviation = config.image_std[channel]; + if (!std::isfinite(mean)) + throw std::invalid_argument("vit_mae image mean must be finite"); + if (!std::isfinite(deviation) || deviation == 0.0F) + throw std::invalid_argument("vit_mae image std must be finite and nonzero"); + if (!std::isfinite(-mean / deviation) || !std::isfinite((1.0F - mean) / deviation)) + throw std::invalid_argument( + "vit_mae normalization must cover the pixel range in float32"); + } + if (config.resample != VitMaeResample::kBilinear) + throw std::invalid_argument("vit_mae resample must be bilinear (2)"); +} + +std::vector preprocess_vit_mae_image(const float* image_pixels, std::int32_t image_height, + std::int32_t image_width, + const VitMaePreprocessConfig& config) { + if (image_pixels == nullptr || image_height <= 0 || image_width <= 0) + throw std::invalid_argument("vit_mae source image must be non-empty"); + validate_vit_mae_preprocess(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); + + 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) * 3U; + 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] = (static_cast(resized[source + channel]) / 255.0F - + config.image_mean[channel]) / + config.image_std[channel]; + } + } + } + return pixel_values; +} + +} // namespace trtmc diff --git a/families/vit_mae/runtime/image_preprocess.h b/families/vit_mae/runtime/image_preprocess.h new file mode 100644 index 0000000000..eb9a04dcd3 --- /dev/null +++ b/families/vit_mae/runtime/image_preprocess.h @@ -0,0 +1,33 @@ +/* + * 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 VitMaeResample : std::int32_t { kBilinear = 2, kBicubic = 3 }; + +struct VitMaePreprocessConfig { + std::int32_t input_image_h{224}; + std::int32_t input_image_w{224}; + VitMaeResample resample{VitMaeResample::kBilinear}; + std::vector image_mean{0.5F, 0.5F, 0.5F}; + std::vector image_std{0.5F, 0.5F, 0.5F}; +}; + +void validate_vit_mae_preprocess(const VitMaePreprocessConfig& config); + +// ViT-MAE 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_vit_mae_image(const float* image_pixels, std::int32_t image_height, + std::int32_t image_width, + const VitMaePreprocessConfig& config); + +} // namespace trtmc diff --git a/families/vit_mae/runtime/pipeline.cpp b/families/vit_mae/runtime/pipeline.cpp new file mode 100644 index 0000000000..bff5261100 --- /dev/null +++ b/families/vit_mae/runtime/pipeline.cpp @@ -0,0 +1,114 @@ +/* + * SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. + * SPDX-License-Identifier: Apache-2.0 + */ + +#include "families/vit_mae/runtime/pipeline.h" + +#include +#include +#include +#include +#include +#include + +namespace trtmc::vit_mae { +namespace { +const internal::ConfigField kFields[] = { + {"mask_seed", internal::ConfigKind::I64, internal::ConfigValue{std::int64_t{0}}, + "Unsigned 32-bit MT19937 seed controlling the visible patch subset and order."}, +}; +Span fields() { + return {kFields, 1}; +} +} // namespace + +Pipeline::Pipeline(std::unique_ptr module, Config config) + : module_(std::move(module)), config_(std::move(config)) { + validate_vit_mae_preprocess(config_.preprocess); + const auto size = config_.preprocess.input_image_h; + if (!module_ || !module_->ok() || size <= 0 || config_.preprocess.input_image_w != size || + config_.patch_size <= 0 || size % config_.patch_size || config_.patches <= 0 || + static_cast(size / config_.patch_size) * (size / config_.patch_size) != + config_.patches || + config_.hidden_size <= 0 || config_.kept <= 0 || config_.kept > config_.patches) + throw std::invalid_argument("vit_mae invalid masked encoder geometry"); +} + +std::vector Pipeline::task_bindings() { + return {internal::bind(*this, fields())}; +} + +internal::ImageTokenFeaturesResult +Pipeline::run(const internal::ImageToTokenFeaturesRequest& request, internal::ConfigView config) { + internal::validate_config(fields(), config); + const auto seed = internal::config_get(config, fields(), "mask_seed").value(); + if (seed < 0 || seed > std::numeric_limits::max()) + throw std::invalid_argument("vit_mae mask_seed must be an unsigned 32-bit integer"); + const auto& image = request.image; + if (image.format != internal::ImageFormat::Float32 || !image.data || image.channels != 3 || + image.height == 0 || image.width == 0 || + image.height > std::numeric_limits::max() || + image.width > std::numeric_limits::max() || + static_cast(image.height) > + std::numeric_limits::max() / image.width / 3 / sizeof(float) || + image.byte_size != static_cast(image.height) * image.width * 3 * sizeof(float)) + throw std::invalid_argument("vit_mae requires contiguous float32 RGB input"); + const auto* source = static_cast(image.data); + if (!std::all_of(source, source + image.byte_size / sizeof(float), [](float value) { + return std::isfinite(value) && value >= 0.0F && value <= 1.0F; + })) + throw std::invalid_argument("vit_mae requires finite RGB pixels in [0,1]"); + auto pixels = preprocess_vit_mae_image(source, image.height, image.width, config_.preprocess); + std::mt19937 generator(static_cast(seed)); + std::vector scores(config_.patches); + for (auto& score : scores) + score = generator(); + std::vector visible(config_.patches); + std::iota(visible.begin(), visible.end(), 0); + std::stable_sort(visible.begin(), visible.end(), + [&](auto left, auto right) { return scores[left] < scores[right]; }); + visible.resize(config_.kept); + Tensor pixel_tensor; + pixel_tensor.data = pixels.data(); + pixel_tensor.dtype = DType::kFloat32; + pixel_tensor.shape = {1, 3, config_.preprocess.input_image_h, config_.preprocess.input_image_w}; + Tensor index_tensor; + index_tensor.data = visible.data(); + index_tensor.dtype = DType::kInt32; + index_tensor.shape = {config_.kept}; + const auto outputs = + module_->forward({{"pixel_values", pixel_tensor}, {"visible_indices", index_tensor}}); + const auto found = outputs.find("last_hidden_state"); + if (found == outputs.end() || !found->second.data || found->second.dtype != DType::kFloat32 || + found->second.shape != std::vector{config_.kept + 1, config_.hidden_size}) + throw std::runtime_error("vit_mae invalid masked encoder output"); + const auto* values = static_cast(found->second.data); + internal::ImageTokenFeaturesResult result; + result.features.rows = config_.kept + 1; + result.features.columns = config_.hidden_size; + result.features.values.assign(values, values + found->second.numel()); + if (!std::all_of(result.features.values.begin(), result.features.values.end(), + [](float value) { return std::isfinite(value); })) + throw std::runtime_error("vit_mae nonfinite encoder output"); + const auto grid = config_.preprocess.input_image_h / config_.patch_size; + result.grid_rows = result.grid_columns = grid; + internal::ImageFeatureToken cls; + cls.role = internal::ImageFeatureTokenRole::Class; + result.tokens.push_back(cls); + for (const auto index : visible) { + internal::ImageFeatureToken token; + token.role = internal::ImageFeatureTokenRole::Patch; + token.grid_row = index / grid; + token.grid_column = index % grid; + // The processor resizes the full source independently in each axis. + token.x_min = static_cast(token.grid_column) / grid; + token.x_max = static_cast(token.grid_column + 1) / grid; + token.y_min = static_cast(token.grid_row) / grid; + token.y_max = static_cast(token.grid_row + 1) / grid; + result.tokens.push_back(token); + } + return result; +} + +} // namespace trtmc::vit_mae diff --git a/families/vit_mae/runtime/pipeline.h b/families/vit_mae/runtime/pipeline.h new file mode 100644 index 0000000000..0d7561d9dd --- /dev/null +++ b/families/vit_mae/runtime/pipeline.h @@ -0,0 +1,36 @@ +/* + * SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. + * SPDX-License-Identifier: Apache-2.0 + */ + +#pragma once + +#include "families/vit_mae/runtime/image_preprocess.h" +#include "trtmc/internal/features.h" +#include "trtmc/internal/model.h" +#include "trtmc/runtime/trt_module.h" + +namespace trtmc::vit_mae { + +struct Config { + VitMaePreprocessConfig preprocess; + std::int32_t patch_size{16}; + std::int32_t patches{196}; + std::int32_t kept{49}; + std::int32_t hidden_size{768}; +}; + +class Pipeline final : public internal::IModel, public internal::IImageToTokenFeatures { + public: + Pipeline(std::unique_ptr module, Config config); + const char* task() const noexcept override { return "image_to_token_features"; } + std::vector task_bindings() override; + internal::ImageTokenFeaturesResult run(const internal::ImageToTokenFeaturesRequest& request, + internal::ConfigView config) override; + + private: + std::unique_ptr module_; + Config config_; +}; + +} // namespace trtmc::vit_mae diff --git a/families/vit_mae/runtime/plugin.cpp b/families/vit_mae/runtime/plugin.cpp new file mode 100644 index 0000000000..f40f2f21af --- /dev/null +++ b/families/vit_mae/runtime/plugin.cpp @@ -0,0 +1,43 @@ +/* + * SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. + * SPDX-License-Identifier: Apache-2.0 + */ + +#include "families/vit_mae/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) { + namespace mae = trtmc::vit_mae; + if (context.kv_cache_size_bytes != 0) + throw std::invalid_argument("vit_mae does not support --kv-cache-size"); + if (context.reader.info().task != "image_to_token_features") + throw std::invalid_argument("vit_mae requires image_to_token_features"); + auto section = [&](const char* name) { + const auto* found = context.reader.find_section(name); + if (!found || found->length == 0) + throw std::runtime_error(std::string("vit_mae 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()); + const auto& version = json.at("schema_version"); + if (!version.is_number_integer() || version != 1) + throw std::invalid_argument("vit_mae unsupported runtime schema"); + mae::Config config; + config.preprocess.input_image_h = config.preprocess.input_image_w = json.at("image_size"); + config.preprocess.image_mean = json.at("image_mean").get>(); + config.preprocess.image_std = json.at("image_std").get>(); + config.preprocess.resample = static_cast(json.at("resample").get()); + config.patch_size = json.at("patch_size"); + config.patches = json.at("patches"); + config.kept = json.at("kept"); + config.hidden_size = json.at("hidden_size"); + trtmc::validate_vit_mae_preprocess(config.preprocess); + const auto plan = section("model.plan"); + return new mae::Pipeline(context.backend.create_module(plan.data(), plan.size(), {}), + std::move(config)); +} diff --git a/families/vit_mae/support.py b/families/vit_mae/support.py new file mode 100644 index 0000000000..5339a38252 --- /dev/null +++ b/families/vit_mae/support.py @@ -0,0 +1,9 @@ +# 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=("vit_mae",), tasks=("image_to_token_features",), + default_task="image_to_token_features", default_precision="fp32", +) diff --git a/families/vit_mae/tests/__init__.py b/families/vit_mae/tests/__init__.py new file mode 100644 index 0000000000..52a7a9daf0 --- /dev/null +++ b/families/vit_mae/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/vit_mae/tests/cpp/e2e_consumer.cpp b/families/vit_mae/tests/cpp/e2e_consumer.cpp new file mode 100644 index 0000000000..f4f4693435 --- /dev/null +++ b/families/vit_mae/tests/cpp/e2e_consumer.cpp @@ -0,0 +1,132 @@ +/* + * SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. + * SPDX-License-Identifier: Apache-2.0 + */ + +#include "families/vit_mae/runtime/image_preprocess.h" +#include "trtmc/bundle.h" +#include "trtmc/features.hpp" + +#include +#include +#include +#include +#include +#include + +int main(int argc, char** argv) { + try { + if (argc != 5) + throw std::invalid_argument( + "usage: vit_mae_e2e BUNDLE RUNTIME_ROOT REQUESTS_JSON OUTPUT_DIRECTORY"); + std::ifstream input(argv[3]); + const auto requests = nlohmann::json::parse(input); + trtmc::LoadOptions options; + options.runtime_root = argv[2]; + auto model = trtmc::Model::load(argv[1], options); + auto task = model.task(); + const trtmc::BundleReader bundle(argv[1]); + const auto data = bundle.read_section("runtime.json"); + const auto metadata = nlohmann::json::parse(data.begin(), data.end()); + trtmc::VitMaePreprocessConfig preprocess; + preprocess.input_image_h = preprocess.input_image_w = metadata.at("image_size"); + preprocess.image_mean = metadata.at("image_mean").get>(); + preprocess.image_std = metadata.at("image_std").get>(); + preprocess.resample = + static_cast(metadata.at("resample").get()); + auto bicubic = preprocess; + bicubic.resample = trtmc::VitMaeResample::kBicubic; + bool rejected_bicubic = false; + try { + trtmc::validate_vit_mae_preprocess(bicubic); + } catch (const std::invalid_argument& error) { + rejected_bicubic = + std::string_view(error.what()) == "vit_mae resample must be bilinear (2)"; + } + if (!rejected_bicubic) + throw std::runtime_error("ViT-MAE accepted bicubic bundle metadata"); + const auto dimension = [](const nlohmann::json& value) { + if (!value.is_number_integer()) + throw std::invalid_argument("ViT-MAE fixture dimensions must be integers"); + const auto size = value.get(); + if (size == 0 || size > std::numeric_limits::max()) + throw std::invalid_argument("ViT-MAE fixture dimension is out of range"); + return static_cast(size); + }; + nlohmann::json results = nlohmann::json::array(); + for (const auto& request : requests) { + auto pixels = request.at("pixels").get>(); + const auto height = dimension(request.at("height")); + const auto width = dimension(request.at("width")); + if (height > std::numeric_limits::max() / width / 3U || + pixels.size() != static_cast(height) * width * 3U) + throw std::invalid_argument( + "ViT-MAE fixture pixel count disagrees with its dimensions"); + const auto normalized = + trtmc::preprocess_vit_mae_image(pixels.data(), height, width, preprocess); + std::ofstream boundary(std::string(argv[4]) + "/pixels-" + + std::to_string(results.size()) + ".f32", + std::ios::binary); + boundary.write(reinterpret_cast(normalized.data()), + normalized.size() * sizeof(float)); + if (!boundary) + throw std::runtime_error("cannot save ViT-MAE preprocessing boundary"); + trtmc::ImageInput image({pixels.data(), pixels.size()}, height, width); + trtmc::Config config{{"mask_seed", request.at("mask_seed").get()}}; + auto result = task.run({image}, config); + const auto matrix = result.features(); + nlohmann::json tokens = nlohmann::json::array(); + for (const auto& token : result.tokens()) + tokens.push_back( + {{"role", token.role == TRTMC_IMAGE_TOKEN_CLASS ? "class" : "patch"}, + {"grid_row", token.grid_row}, + {"grid_column", token.grid_column}, + {"box", {token.x_min, token.y_min, token.x_max, token.y_max}}}); + results.push_back( + {{"features", std::vector(matrix.values.begin(), matrix.values.end())}, + {"shape", {matrix.rows, matrix.columns}}, + {"grid", {result.grid_rows(), result.grid_columns()}}, + {"tokens", tokens}}); + } + const auto& first = requests.at(0); + auto pixels = first.at("pixels").get>(); + const auto height = first.at("height").get(); + const auto width = first.at("width").get(); + for (int mode = 0; mode < 5; ++mode) { + auto corrupted = pixels; + trtmc::Config config; + if (mode == 0) + config.add("mask_seed", std::int64_t{-1}); + if (mode == 1) + config.add("mask_seed", std::int64_t{4294967296LL}); + if (mode == 2) + corrupted[0] = std::numeric_limits::quiet_NaN(); + if (mode == 3) + config.add("unknown", std::int64_t{0}); + trtmc::ImageInput image({corrupted.data(), corrupted.size()}, mode == 4 ? 0U : height, + width); + bool rejected = false; + try { + task.run({image}, config); + } catch (const trtmc::Error& error) { + const auto expected = mode == 3 ? TRTMC_INVALID_CONFIG : TRTMC_INVALID_ARGUMENT; + if (error.code() != expected) + throw; + rejected = true; + } + if (!rejected) + throw std::runtime_error("ViT-MAE accepted an invalid image or mask request"); + } + trtmc::ImageInput image({pixels.data(), pixels.size()}, height, width); + auto recovered = task.run({image}); + const auto values = recovered.features().values; + if (std::vector(values.begin(), values.end()) != + results.at(0).at("features").get>()) + throw std::runtime_error("ViT-MAE mask 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/vit_mae/tests/encoder_check.py b/families/vit_mae/tests/encoder_check.py new file mode 100644 index 0000000000..73d85f64af --- /dev/null +++ b/families/vit_mae/tests/encoder_check.py @@ -0,0 +1,40 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +"""Check all masked encoder values and visible-patch ordering against upstream.""" + + +def check_encoder(): + import numpy as np + import tensorrt as trt + import torch + from transformers import ViTMAEConfig, ViTMAEModel + from families.vit_mae.model import compile_engine + + torch.backends.cuda.matmul.allow_tf32 = False + torch.backends.cudnn.allow_tf32 = False + torch.manual_seed(2040) + config = ViTMAEConfig(hidden_size=32, num_attention_heads=4, num_hidden_layers=2, intermediate_size=48, + image_size=16, patch_size=4, mask_ratio=0.75, attn_implementation="eager") + model = ViTMAEModel(config).eval() + weights = {"vit." + name: value.numpy() for name, value in model.state_dict().items()} + runtime = trt.Runtime(trt.Logger(trt.Logger.WARNING)) + engine = runtime.deserialize_cuda_engine(compile_engine(config.to_dict(), weights)) + assert engine is not None + context = engine.create_execution_context() + model.cuda() + for seed in (0, 19, 4294967295, 0): + scores = np.random.RandomState(seed).randint(0, 2**32, size=16, dtype=np.uint32) + order = np.argsort(scores, kind="stable") + ranks = np.argsort(order).astype(np.float32) + pixels = torch.from_numpy(np.random.default_rng(seed).normal(0, 0.5, (1, 3, 16, 16)).astype(np.float32)).cuda() + visible = torch.tensor(order[:4].copy(), dtype=torch.int32, device="cuda") + actual = torch.empty(5, 32, device="cuda") + for name, tensor in {"pixel_values": pixels, "visible_indices": visible, "last_hidden_state": actual}.items(): + assert context.set_tensor_address(name, tensor.data_ptr()) + assert context.execute_async_v3(torch.cuda.current_stream().cuda_stream) + torch.cuda.synchronize() + with torch.inference_mode(): + output = model(pixels, noise=torch.from_numpy(ranks[None]).cuda()) + assert output.ids_restore[0].argsort()[:4].tolist() == order[:4].tolist() + torch.testing.assert_close(actual, output.last_hidden_state[0], atol=5e-5, rtol=5e-5) diff --git a/families/vit_mae/tests/manifests/vit-mae-base.json b/families/vit_mae/tests/manifests/vit-mae-base.json new file mode 100644 index 0000000000..1023e05ef8 --- /dev/null +++ b/families/vit_mae/tests/manifests/vit-mae-base.json @@ -0,0 +1,21 @@ +{ + "name": "vit-mae-base", + "hf_id": "facebook/vit-mae-base", + "hf_revision": "25b184bea5538bf5c4c852c79d221195fdd2778d", + "bundle": "vit-mae-base.bundle", + "family": "vit_mae", + "task": "image_to_token_features", + "precision": "fp32", + "tensor_parallel_size": 1, + "testcases": [ + { + "name": "vit-mae-base-masked-patches", + "premerge": true, + "reference_precision": "fp32", + "max_abs_error": 0.0005, + "fixture_seed": 2041, + "image_shapes": [[181, 293], [257, 149]], + "mask_seeds": [0, 19] + } + ] +} diff --git a/families/vit_mae/tests/requirements.txt b/families/vit_mae/tests/requirements.txt new file mode 100644 index 0000000000..b89d11c103 --- /dev/null +++ b/families/vit_mae/tests/requirements.txt @@ -0,0 +1,2 @@ +# The native processor follows this reference's separable resize pass order. +Pillow==13.0.0 diff --git a/families/vit_mae/tests/test_e2e.py b/families/vit_mae/tests/test_e2e.py new file mode 100644 index 0000000000..7910f80e34 --- /dev/null +++ b/families/vit_mae/tests/test_e2e.py @@ -0,0 +1,140 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +"""Pinned ViT-MAE checkpoint -> TensorRT bundle -> native Task -> masked image patch features.""" + +import json +import os +from pathlib import Path +import subprocess + +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 + +ROOT = Path(__file__).parent +MANIFEST = json.loads((ROOT / "manifests/vit-mae-base.json").read_text()) + + +def pytest_generate_tests(metafunc): + if "case_name" not in metafunc.fixturenames: + return + model_filters = set() + for value in metafunc.config.getoption("--e2e-model"): + model_filters.update(value.split(",")) + models_file = metafunc.config.getoption("--e2e-models-file") + if models_file: + model_filters.update(Path(models_file).read_text().splitlines()) + case_filters = set() + for value in metafunc.config.getoption("--e2e-testcase"): + case_filters.update(value.split(",")) + enabled = bool(model_filters or case_filters) + parameters = [] + for case in MANIFEST["testcases"]: + if model_filters and not model_filters.intersection({"vit_mae", MANIFEST["name"], case["name"]}): + continue + if case_filters and case["name"] not in case_filters: + continue + marks = [] if enabled else [pytest.mark.skip(reason="select ViT-MAE E2E explicitly")] + parameters.append(pytest.param(case["name"], marks=marks)) + metafunc.parametrize("case_name", parameters) + + +def _checkpoint(): + path = os.environ.get("TRTMC_VIT_MAE_MODEL_DIR") + if path: + 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 _reference(model_dir, inputs): + import numpy as np + import torch + from transformers import AutoImageProcessor, ViTMAEModel + + torch.backends.cuda.matmul.allow_tf32 = False + torch.backends.cudnn.allow_tf32 = False + processor = AutoImageProcessor.from_pretrained(model_dir, use_fast=False, trust_remote_code=False) + model = ViTMAEModel.from_pretrained(model_dir, dtype=torch.float32, trust_remote_code=False, + attn_implementation="eager").cuda().eval() + patches = (model.config.image_size // model.config.patch_size) ** 2 + grid = model.config.image_size // model.config.patch_size + expected = [] + for image, seed in inputs: + scores = np.random.RandomState(seed).randint(0, 2**32, size=patches, dtype=np.uint32) + order = np.argsort(scores, kind="stable") + ranks = np.argsort(order).astype(np.float32) + pixels = processor(images=image, return_tensors="pt").pixel_values.cuda() + with torch.inference_mode(): + output = model(pixels, noise=torch.from_numpy(ranks[None]).cuda()) + features = output.last_hidden_state[0].cpu().numpy() + visible = output.ids_restore[0].argsort()[:features.shape[0] - 1].tolist() + assert visible == order[:features.shape[0] - 1].tolist() + tokens = [{"role": "class", "grid_row": 0, "grid_column": 0, "box": [0, 0, 0, 0]}] + for index in visible: + row, column = divmod(index, grid) + tokens.append({"role": "patch", "grid_row": row, "grid_column": column, + "box": [column / grid, row / grid, (column + 1) / grid, (row + 1) / grid]}) + expected.append({"features": features, "tokens": tokens, "grid": [grid, grid], + "pixel_values": pixels.cpu().numpy()}) + return expected + + +def test_official_checkpoint_e2e(case_name, tmp_path): + case = next(case for case in MANIFEST["testcases"] if case["name"] == case_name) + import numpy as np + from families.vit_mae.tests.encoder_check import check_encoder + + assert case["reference_precision"] == "fp32" + check_encoder() + model_dir = _checkpoint() + assert resolve_family(load_model_metadata(model_dir))[0] == "vit_mae" + runtime = Path(os.environ["TRTMC_RUNTIME_ROOT"]) + consumer = runtime / "vit_mae_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"]] + first_seed, second_seed = case["mask_seeds"] + inputs = [(images[0], first_seed), (images[1], second_seed), (images[0], first_seed), (images[0], second_seed)] + record_evidence("inputs", {"manifest": MANIFEST, "case": case}) + record_evidence("checkpoint", {"model_dir": str(model_dir), "hf_id": MANIFEST["hf_id"], + "hf_revision": MANIFEST["hf_revision"]}) + with evidence_stage("reference"): + expected = _reference(model_dir, inputs) + assert not np.array_equal(expected[0]["features"], expected[1]["features"]) + assert expected[0]["tokens"] != expected[3]["tokens"] + record_evidence("reference", expected) + bundle = tmp_path / MANIFEST["bundle"] + with evidence_stage("build"): + build(BuildRequest(model_dir, 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], "mask_seed": seed, + "pixels": (image.astype(np.float32) / 255).reshape(-1).tolist()} for image, seed in inputs])) + with evidence_stage("native"): + command = [str(consumer), str(bundle), str(runtime), str(requests), str(tmp_path)] + result = subprocess.run(command, check=True, text=True, capture_output=True, timeout=600) + record_evidence("commands", {"argv": command}) + actual = json.loads(result.stdout.strip().splitlines()[-1]) + record_evidence("native", actual) + with evidence_stage("compare"): + assert len(actual) == len(expected) + for index, (native, reference) in enumerate(zip(actual, expected)): + pixels = np.fromfile(tmp_path / f"pixels-{index}.f32", dtype=np.float32) + np.testing.assert_allclose(pixels.reshape(reference["pixel_values"].shape), + reference["pixel_values"], atol=2e-6, rtol=0) + assert native["shape"] == list(reference["features"].shape) + assert native["grid"] == reference["grid"] + np.testing.assert_allclose(np.asarray(native["features"]).reshape(native["shape"]), + reference["features"], atol=case["max_abs_error"], rtol=0) + assert len(native["tokens"]) == len(reference["tokens"]) + for token, wanted in zip(native["tokens"], reference["tokens"]): + for field in ("role", "grid_row", "grid_column"): + assert token[field] == wanted[field] + np.testing.assert_allclose(token["box"], wanted["box"], atol=1e-7, rtol=0) + assert actual[0] == actual[2] diff --git a/families/vit_mae/tests/test_model.py b/families/vit_mae/tests/test_model.py new file mode 100644 index 0000000000..6b88fde91c --- /dev/null +++ b/families/vit_mae/tests/test_model.py @@ -0,0 +1,98 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +from dataclasses import replace +import json + +import pytest + +from tensorrt_model_connect import BuildRequest +from families.vit_mae.model import build, geometry, load_weights + + +def test_masked_patch_geometry(): + from transformers import ViTMAEConfig + + config = ViTMAEConfig().to_dict() + assert geometry(config) == (196, 49) + with pytest.raises(ValueError, match="mask ratio"): + geometry({**config, "mask_ratio": 1.0}) + with pytest.raises(ValueError, match="divide"): + geometry({**config, "patch_size": 15}) + + +def test_checkpoint_requires_patch_projection(tmp_path): + from safetensors.torch import save_file + from transformers import ViTMAEConfig, ViTMAEModel + + config = ViTMAEConfig(hidden_size=32, num_attention_heads=4, num_hidden_layers=1, intermediate_size=48, + image_size=16, patch_size=4) + weights = {"vit." + name: value for name, value in ViTMAEModel(config).state_dict().items()} + del weights["vit.embeddings.patch_embeddings.projection.bias"] + save_file(weights, tmp_path / "model.safetensors") + with pytest.raises(ValueError, match="projection.bias"): + load_weights(tmp_path, config.to_dict()) + + +def test_unsupported_profiles_fail_before_weights(tmp_path): + request = BuildRequest(tmp_path, tmp_path / "out.bundle", "vit_mae", "image_to_token_features", "fp32") + for update in ({"precision": "bf16"}, {"task": "classification"}, {"tensor_parallel_size": 2}, + {"max_batch_size": 2}, {"dynamic_kv_cache": True}, {"quantization": "fp8"}, + {"max_sequence_length": 128}, {"image_height": 448}): + with pytest.raises((ValueError, NotImplementedError)): + build(replace(request, **update), None) + + +@pytest.mark.parametrize("processor", [{"do_rescale": False}, {"rescale_factor": 0.5}]) +def test_rejects_incompatible_rescaling_before_loading_weights(tmp_path, processor): + from transformers import ViTMAEConfig + + ViTMAEConfig().save_pretrained(tmp_path) + (tmp_path / "preprocessor_config.json").write_text(json.dumps(processor)) + request = BuildRequest(tmp_path, tmp_path / "out.bundle", "vit_mae", "image_to_token_features", "fp32") + with pytest.raises(NotImplementedError, match="rescaling pixels"): + build(request, None) + + +@pytest.mark.parametrize( + ("processor", "message"), + [ + ({"size": {"height": 224, "width": 192}}, "processor size"), + ({"size": {"height": 224}}, "processor size"), + ({"image_std": [0.5, 0.0, 0.5]}, "image_std"), + ({"image_std": 1e-100}, "image_std"), + ({"image_std": 1e-39}, "normalization must cover the pixel range"), + ({"image_mean": [0.5, 0.5]}, "image_mean"), + ({"image_mean": 1e40}, "image_mean"), + ], +) +def test_rejects_invalid_processor_metadata_before_build(tmp_path, processor, message): + from transformers import ViTMAEConfig + + ViTMAEConfig().save_pretrained(tmp_path) + (tmp_path / "preprocessor_config.json").write_text(json.dumps(processor)) + request = BuildRequest(tmp_path, tmp_path / "out.bundle", "vit_mae", "image_to_token_features", "fp32") + with pytest.raises(ValueError, match=message): + build(request, None) + + +@pytest.mark.parametrize("size", [None, 224, {"height": 224, "width": 224}]) +def test_square_processor_metadata_serializes_three_channels(tmp_path, monkeypatch, size): + from unittest.mock import Mock + + from transformers import ViTMAEConfig + + from families.vit_mae import model + + ViTMAEConfig().save_pretrained(tmp_path) + (tmp_path / "preprocessor_config.json").write_text(json.dumps({"size": size, "image_std": 0.25})) + request = BuildRequest(tmp_path, tmp_path / "out.bundle", "vit_mae", "image_to_token_features", "fp32") + writer = Mock() + monkeypatch.setattr(model, "load_weights", Mock(return_value={})) + monkeypatch.setattr(model, "compile_engine", Mock(return_value=b"plan")) + build(request, writer) + name, metadata = writer.add_json.call_args.args + assert name == "runtime.json" + assert metadata["image_size"] == 224 + assert metadata["image_mean"] == [0.5] * 3 + assert metadata["image_std"] == [0.25] * 3 diff --git a/families/vit_mae/tests/test_support.py b/families/vit_mae/tests/test_support.py new file mode 100644 index 0000000000..f8be3798be --- /dev/null +++ b/families/vit_mae/tests/test_support.py @@ -0,0 +1,13 @@ +# 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.vit_mae.support import describe + + +def test_vit_mae_owner(): + metadata = ModelMetadata(config={"model_type": "vit_mae", "architectures": ["ViTMAEForPreTraining"]}, model_index={}) + family, support = resolve_family(metadata) + assert family == "vit_mae" + assert support.default_task == "image_to_token_features" + assert describe(ModelMetadata(config={"model_type": "vit"}, model_index={})) is None