diff --git a/ASSET_LICENSES.md b/ASSET_LICENSES.md index 1cf7523817..1362a58e17 100644 --- a/ASSET_LICENSES.md +++ b/ASSET_LICENSES.md @@ -74,6 +74,7 @@ and saved losslessly as PNG (its pixels equal Pillow's decode of the Byte-identical copies of that PNG are stored at: +- `families/mask2former/tests/data/test_img.png` - `families/minicpmv4_7/tests/data/test_img.png` `families/timm_resnet/tests/data/test_img_car.jpeg` is a crop of the same diff --git a/families/mask2former/NOTICE b/families/mask2former/NOTICE new file mode 100644 index 0000000000..99c2f8dfa4 --- /dev/null +++ b/families/mask2former/NOTICE @@ -0,0 +1,34 @@ +The 8-bit bilinear resampling in runtime/image_ops.cpp (coefficient computation, fixed-point normalization, +pass order and accumulation) is adapted from Pillow 13.0.0, src/libImaging/Resample.c: +https://github.com/python-pillow/Pillow/blob/13.0.0/src/libImaging/Resample.c + +The Python Imaging Library (PIL) is + + Copyright (c) 1997-2011 by Secret Labs AB + Copyright (c) 1995-2011 by Fredrik Lundh and contributors + +Pillow is the friendly PIL fork. It is + + Copyright (c) 2010 by Jeffrey 'Alex' Clark and contributors + +Like PIL, Pillow is licensed under the open source MIT-CMU License: + +By obtaining, using, and/or copying this software and/or its associated +documentation, you agree that you have read, understood, and will comply +with the following terms and conditions: + +Permission to use, copy, modify and distribute this software and its +documentation for any purpose and without fee is hereby granted, +provided that the above copyright notice appears in all copies, and that +both that copyright notice and this permission notice appear in supporting +documentation, and that the name of Secret Labs AB or the author not be +used in advertising or publicity pertaining to distribution of the software +without specific, written prior permission. + +SECRET LABS AB AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS +SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. +IN NO EVENT SHALL SECRET LABS AB OR THE AUTHOR BE LIABLE FOR ANY SPECIAL, +INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM +LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE +OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR +PERFORMANCE OF THIS SOFTWARE. diff --git a/families/mask2former/README.md b/families/mask2former/README.md new file mode 100644 index 0000000000..f5765bdd91 --- /dev/null +++ b/families/mask2former/README.md @@ -0,0 +1,73 @@ +# Mask2Former + +This family builds `Mask2FormerForUniversalSegmentation` checkpoints with a Swin backbone, validated on +`facebook/mask2former-swin-large-ade-semantic` (Swin-L, 216 M parameters, 150 ADE20K classes), and serves them through +the `image_to_semantic_segmentation` Task (`IModel` + `IImageToSemanticSegmentation`). The CLI command is `segment`. + +## What runs where + +- **Engine** (one TensorRT plan, float32, strongly typed, batch 1, static 384 x 384 input): Swin backbone, the pixel + decoder (six multi-scale deformable-attention layers written with TensorRT grid sample, one FPN level, mask + projection), the nine masked-attention decoder layers, the class probabilities and the semantic scores: the einsum of + the class probabilities (no-object class removed) with the sigmoid of the final mask logits after a bilinear resize to + 384 x 384. Its only output is `semantic_scores` with shape (1, classes, 384, 384). +- **Runtime** (`runtime/`): the checkpoint processor's preprocessing (Pillow-exact 8-bit bilinear resize to the + processor size, rescale, normalization), the engine run, then the bilinear resize of the scores to the original image + size (as `torch.nn.functional.interpolate`, `align_corners=False`) and the argmax over classes. + +The result carries one class ID per pixel at the original resolution, the class IDs `0..N-1` and the checkpoint's +`id2label` names. The vocabulary ID stays empty (the checkpoint declares none), no ignore or background label is +claimed, and the score maps are not returned: the Task accepts only logit or probability maps, and these sums of +class probability times mask probability over the queries are neither. There are no runtime Config fields. + +Inputs: contiguous RGB, 8-bit or float32 in `[0, 1]`. Float32 values are quantized to the nearest 8-bit value, which +recovers the exact bytes of an 8-bit image decoded as `value / 255` (the CLI's image loader); the checkpoint's +processor resizes 8-bit images. + +## Supported checkpoints + +The builder reads `config.json` and `preprocessor_config.json` and accepts only what the graph reproduces: a Swin +backbone with four stages and all four outputs, stage resolutions that are whole multiples of the window size (no +padding), the post-norm decoder with ReLU, `feature_size == hidden_dim`, one extra FPN level, and a processor with a +fixed `{"height", "width"}` size, bilinear resampling, rescaling and normalization. Anything else is rejected with an +error that names the setting. Weights must be float32 as released. + +The preprocessing follows `Mask2FormerImageProcessor`, the processor class the checkpoint's +`preprocessor_config.json` names, which resizes with PIL. Transformers' `AutoImageProcessor` may instead select the +torchvision-based fast processor, whose antialiased resize gives slightly different pixels. + +No model weights are included in this repository. The validated checkpoint carries no license file and its Hugging +Face license field is `other`; users obtain it separately under its publisher's terms. + +Build options: `precision=fp32` only (the checkpoint is float32), `backend=trt`, batch size 1, no quantization, +parallelism or KV cache; `image_height` / `image_width` may only repeat the processor size. + +## Not supported + +- FP16 / BF16 builds, quantization and batch sizes above 1. +- Instance and panoptic segmentation (the reference's other post-processors), and the per-class score maps. +- Swin windows that need padding (for example window 7 at a 384 x 384 input) and processors that resize by the + shortest edge. + +## Validate + +```sh +cmake --build build --target trtmc trtmc_backend_trt trtmc_c trtmc_model_mask2former test_mask2former_task_contract +ctest --test-dir build --output-on-failure -R '^mask2former_task_contract$' +TRTMC_NATIVE_BUILD_DIR=build python -m pytest families/mask2former/tests -m "not gpu and not trt" \ + --ignore=families/mask2former/tests/test_e2e.py -q +TRTMC_BINARY=build/trtmc TRTMC_RUNTIME_ROOT=build TRTMC_NATIVE_BUILD_DIR=build \ + python -m pytest families/mask2former/tests/test_e2e.py --e2e-testcase mask2former-swin-large-ade-semantic -q +``` + +The CTest target also builds the C and C++ SDK consumers and `mask2former_image_ops_tool`, which +`tests/test_image_ops.py` uses to compare the runtime's image operations with Pillow (bit-exact resize), the +checkpoint's image processor (bit-exact pixel values) and torch (resize and argmax). + +The E2E builds the bundle from the cached checkpoint and compares the label maps with the Transformers reference: +`Mask2FormerImageProcessor` and `Mask2FormerForUniversalSegmentation` in float32 on the GPU with TF32 disabled, +post-processed by `post_process_semantic_segmentation` at the original image size. The test image is a PNG, so the +CLI's image loader, the two SDK consumers and the reference read identical 8-bit pixels (JPEG decoders differ: on the +JPEG this PNG was decoded from, the CLI's loader and PIL differ by up to 3 in 4.7 % of the values). Every label map +must reach the pixel accuracy and mean IoU in `tests/thresholds/`; on a B300 all three maps equal the reference on +every pixel. diff --git a/families/mask2former/__init__.py b/families/mask2former/__init__.py new file mode 100644 index 0000000000..e48a621e4f --- /dev/null +++ b/families/mask2former/__init__.py @@ -0,0 +1,4 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +"""Mask2Former model family.""" diff --git a/families/mask2former/config.py b/families/mask2former/config.py new file mode 100644 index 0000000000..dbe3d1b29d --- /dev/null +++ b/families/mask2former/config.py @@ -0,0 +1,356 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +"""The Mask2Former checkpoint configuration this family builds, read and checked in one place. + +Only the structure the graph reproduces is accepted: a Swin backbone whose stage resolutions are whole multiples of +its window size, the post-norm masked-attention decoder, one extra FPN level and a fixed-size image processor. Any +other value is rejected here instead of being silently built into a different graph. +""" + +from __future__ import annotations + +import json +import math +import re +from dataclasses import dataclass +from pathlib import Path + +import numpy as np + +# The reference semantic post-processor resizes the mask logits to this size before it combines them with the class +# probabilities, whatever the preprocessed image size (Mask2FormerImageProcessor.post_process_semantic_segmentation). +SEMANTIC_SCORE_SIZE = 384 +# PIL's bilinear filter, the processor's `resample` value. +_PIL_BILINEAR = 2 +# Fixed structure of the pixel decoder and the transformer module. +FEATURE_LEVELS = 3 +ENCODER_POINTS = 4 +GROUP_NORM_GROUPS = 32 +NORM_EPS = 1e-5 + + +@dataclass(frozen=True) +class Mask2FormerConfig: + image_height: int + image_width: int + image_mean: tuple[float, float, float] + image_std: tuple[float, float, float] + rescale_factor: float + patch_size: int + embed_dim: int + depths: tuple[int, ...] + num_heads: tuple[int, ...] + window_size: int + mlp_ratio: float + backbone_eps: float + feature_size: int + mask_feature_size: int + hidden_dim: int + num_attention_heads: int + encoder_layers: int + encoder_feedforward_dim: int + decoder_layers: int + dim_feedforward: int + num_queries: int + labels: tuple[str, ...] + + @property + def num_labels(self) -> int: + return len(self.labels) + + @property + def stage_channels(self) -> tuple[int, ...]: + return tuple(self.embed_dim * 2**stage for stage in range(len(self.depths))) + + @property + def stage_resolutions(self) -> tuple[tuple[int, int], ...]: + height = self.image_height // self.patch_size + width = self.image_width // self.patch_size + return tuple((height >> stage, width >> stage) for stage in range(len(self.depths))) + + +def _unique_keys(pairs: list[tuple[str, object]]) -> dict: + result = {} + for key, value in pairs: + if key in result: + raise ValueError(f"repeats the key {key!r}") + result[key] = value + return result + + +def _read_json(path: Path) -> dict: + if not path.is_file(): + raise FileNotFoundError(f"mask2former checkpoint is missing {path.name}: {path}") + try: + value = json.loads(path.read_text(encoding="utf-8"), object_pairs_hook=_unique_keys) + except ValueError as error: + raise ValueError(f"mask2former {path.name} is not valid JSON: {error}") from error + if not isinstance(value, dict): + raise ValueError(f"mask2former {path.name} must be a JSON object") + return value + + +def _require(condition: bool, message: str) -> None: + if not condition: + raise NotImplementedError(f"mask2former does not support this checkpoint: {message}") + + +def _is_int(value) -> bool: + return isinstance(value, int) and not isinstance(value, bool) + + +def _is_finite_number(value) -> bool: + """A JSON number (not a boolean) that converts to a finite float.""" + + if not isinstance(value, (int, float)) or isinstance(value, bool): + return False + try: + return math.isfinite(value) + except OverflowError: + return False + + +def _int_value(value, name: str) -> int: + if not _is_int(value): + raise ValueError(f"mask2former {name} must be an integer, got {value!r}") + return value + + +def _positive_int(value, name: str) -> int: + if not _is_int(value) or value <= 0: + raise ValueError(f"mask2former {name} must be a positive integer, got {value!r}") + return value + + +def _positive_float32(value, name: str) -> float: + """A positive finite number that stays positive and finite as the float32 the engine stores.""" + + if not _is_finite_number(value) or value <= 0: + raise ValueError(f"mask2former {name} must be a positive number, got {value!r}") + with np.errstate(over="ignore", under="ignore"): + stored = np.float32(value) + if not (np.isfinite(stored) and stored > 0): + raise ValueError(f"mask2former {name} {value!r} does not fit a positive float32") + return float(value) + + +def _int_list(value, name: str) -> tuple[int, ...]: + if not isinstance(value, list) or not value: + raise ValueError(f"mask2former {name} must be a non-empty list") + return tuple(_positive_int(item, name) for item in value) + + +def _channel_values(value, name: str) -> tuple[float, float, float]: + if not isinstance(value, list) or len(value) != 3: + raise ValueError(f"mask2former {name} must hold three numbers") + if not all(_is_finite_number(item) for item in value): + raise ValueError(f"mask2former {name} must hold three finite numbers, got {value!r}") + return tuple(float(item) for item in value) + + +def _require_finite_normalization( + rescale_factor: float, mean: tuple[float, ...], std: tuple[float, ...] +) -> None: + """Normalize every 8-bit value the way the runtime does and require finite float32 results. + + The runtime stores the mean and std as float32 and refuses values beyond its range, rescales in float64, casts + to float32 and normalizes in float32 (image_ops.cpp); a finite but tiny std, a huge mean or a huge rescale factor + would otherwise feed infinities to the engine. + """ + + limit = float(np.finfo(np.float32).max) + for name, values in (("image_mean", mean), ("image_std", std)): + if any(abs(value) > limit for value in values): + raise ValueError(f"mask2former {name} {list(values)!r} does not fit float32") + with np.errstate(over="ignore", under="ignore", divide="ignore", invalid="ignore"): + rescaled = (np.arange(256, dtype=np.float64) * rescale_factor).astype(np.float32) + for channel in range(3): + normalized = (rescaled - np.float32(mean[channel])) / np.float32(std[channel]) + if not np.all(np.isfinite(normalized)): + raise ValueError( + f"mask2former rescale_factor {rescale_factor!r}, image_mean {mean[channel]!r} and image_std " + f"{std[channel]!r} do not normalize 8-bit values to finite float32 values" + ) + + +_CLASS_INDEX = re.compile(r"0|[1-9][0-9]*") + + +def _labels(config: dict) -> tuple[str, ...]: + id2label = config.get("id2label") + if not isinstance(id2label, dict) or not id2label: + raise ValueError("mask2former config.json must name its classes in id2label") + # Only canonical decimal keys: int() would also read "00", "+1" or " 1" and merge two entries into one index. + if not all(_CLASS_INDEX.fullmatch(key) for key in id2label): + raise ValueError( + f"mask2former id2label keys must be canonical class indices, got {sorted(id2label)!r}" + ) + indexed = {int(key): value for key, value in id2label.items()} + if sorted(indexed) != list(range(len(indexed))): + raise ValueError("mask2former id2label must cover the class indices 0..N-1") + labels = tuple(indexed[index] for index in range(len(indexed))) + if any(not isinstance(label, str) or not label for label in labels): + raise ValueError("mask2former id2label values must be non-empty strings") + return labels + + +def _backbone(config: dict) -> dict: + _require(not config.get("use_timm_backbone"), "a timm backbone") + _require(not config.get("backbone"), "a named backbone instead of backbone_config") + backbone = config.get("backbone_config") + if not isinstance(backbone, dict): + raise ValueError("mask2former config.json must carry a backbone_config object") + _require(backbone.get("model_type") == "swin", f"backbone {backbone.get('model_type')!r}") + num_channels = _int_value(backbone.get("num_channels", 3), "backbone num_channels") + _require(num_channels == 3, "a backbone that does not read RGB") + _require(not backbone.get("use_absolute_embeddings", False), "absolute position embeddings") + _require( + backbone.get("hidden_act", "gelu") == "gelu", f"activation {backbone.get('hidden_act')!r}" + ) + _require(backbone.get("qkv_bias", True) is True, "attention projections without bias") + return backbone + + +def load(model_dir: Path) -> Mask2FormerConfig: + """Read config.json and preprocessor_config.json of one checkpoint directory.""" + + model_dir = Path(model_dir) + config = _read_json(model_dir / "config.json") + processor = _read_json(model_dir / "preprocessor_config.json") + _require(config.get("model_type") == "mask2former", f"model_type {config.get('model_type')!r}") + _require( + "Mask2FormerForUniversalSegmentation" in (config.get("architectures") or []), + f"architectures {config.get('architectures')!r}", + ) + + backbone = _backbone(config) + depths = _int_list(backbone.get("depths"), "backbone depths") + num_heads = _int_list(backbone.get("num_heads"), "backbone num_heads") + _require(len(depths) == 4 and len(num_heads) == 4, "a backbone without four stages") + _require( + backbone.get("out_features") == ["stage1", "stage2", "stage3", "stage4"], + f"backbone out_features {backbone.get('out_features')!r}", + ) + patch_size = _positive_int(backbone.get("patch_size"), "backbone patch_size") + embed_dim = _positive_int(backbone.get("embed_dim"), "backbone embed_dim") + window_size = _positive_int(backbone.get("window_size"), "backbone window_size") + for stage, heads in enumerate(num_heads): + _require( + (embed_dim * 2**stage) % heads == 0, + f"stage {stage + 1} width not divisible by its heads", + ) + mlp_ratio = backbone.get("mlp_ratio", 4.0) + if not _is_finite_number(mlp_ratio) or mlp_ratio <= 0: + raise ValueError( + f"mask2former backbone mlp_ratio must be a positive number, got {mlp_ratio!r}" + ) + mlp_width = float(mlp_ratio) * embed_dim + _require(mlp_width == int(mlp_width), f"mlp_ratio {mlp_ratio!r}") + backbone_eps = _positive_float32( + backbone.get("layer_norm_eps", 1e-5), "backbone layer_norm_eps" + ) + + _require(config.get("pre_norm") is False, "the pre-norm decoder") + _require( + config.get("activation_function") == "relu", + f"activation {config.get('activation_function')!r}", + ) + _require(config.get("enforce_input_projection", False) is False, "decoder input projections") + feature_size = _positive_int(config.get("feature_size"), "feature_size") + hidden_dim = _positive_int(config.get("hidden_dim"), "hidden_dim") + mask_feature_size = _positive_int(config.get("mask_feature_size"), "mask_feature_size") + # The transformer module projects the pixel-decoder levels only when their width differs from its own. + _require(feature_size == hidden_dim, "decoder input projections (feature_size != hidden_dim)") + _require( + feature_size % GROUP_NORM_GROUPS == 0, "a pixel-decoder width not divisible by 32 groups" + ) + num_attention_heads = _positive_int(config.get("num_attention_heads"), "num_attention_heads") + _require( + feature_size % num_attention_heads == 0 and hidden_dim % num_attention_heads == 0, + "attention widths not divisible by num_attention_heads", + ) + strides = _int_list(config.get("feature_strides"), "feature_strides") + _require( + strides == tuple(patch_size * 2**stage for stage in range(4)), + f"feature_strides {list(strides)} for patch size {patch_size}", + ) + common_stride = _positive_int(config.get("common_stride"), "common_stride") + # The pixel decoder adds log2(min transformer stride) - log2(common stride) FPN levels; the graph owns one. + _require(strides[-FEATURE_LEVELS] == 2 * common_stride, f"common_stride {common_stride}") + + _require(processor.get("do_resize") is True, "a processor that does not resize") + _require(processor.get("do_rescale") is True, "a processor that does not rescale") + _require(processor.get("do_normalize") is True, "a processor that does not normalize") + resample = _int_value(processor.get("resample", _PIL_BILINEAR), "processor resample") + _require(resample == _PIL_BILINEAR, "a resampling filter other than bilinear") + _require(processor.get("pad_size") is None, "a processor pad size") + size = processor.get("size") + _require( + isinstance(size, dict) and set(size) == {"height", "width"}, + f"processor size {size!r}; only a fixed height and width", + ) + image_height = _positive_int(size["height"], "processor height") + image_width = _positive_int(size["width"], "processor width") + size_divisor = _int_value(processor.get("size_divisor", 32), "processor size_divisor") + _require(size_divisor >= 0, f"size_divisor {size_divisor!r}") + if size_divisor: + _require( + image_height % size_divisor == 0 and image_width % size_divisor == 0, + "a processor size the size divisor would change", + ) + downsampling = patch_size * 2 ** (len(depths) - 1) + _require( + image_height % downsampling == 0 and image_width % downsampling == 0, + f"a {image_height}x{image_width} input that the backbone pads", + ) + for stage, (height, width) in enumerate( + (image_height // patch_size >> stage, image_width // patch_size >> stage) + for stage in range(len(depths)) + ): + _require( + height % window_size == 0 and width % window_size == 0, + f"stage {stage + 1} resolution {height}x{width} is not a multiple of window {window_size}", + ) + rescale_factor = processor.get("rescale_factor") + if ( + not isinstance(rescale_factor, float) + or not math.isfinite(rescale_factor) + or rescale_factor <= 0.0 + ): + raise ValueError( + f"mask2former rescale_factor must be a positive float, got {rescale_factor!r}" + ) + image_mean = _channel_values(processor.get("image_mean"), "image_mean") + image_std = _channel_values(processor.get("image_std"), "image_std") + if any(value == 0.0 for value in image_std): + raise ValueError("mask2former image_std must not contain zero") + _require_finite_normalization(rescale_factor, image_mean, image_std) + + labels = _labels(config) + return Mask2FormerConfig( + image_height=image_height, + image_width=image_width, + image_mean=image_mean, + image_std=image_std, + rescale_factor=rescale_factor, + patch_size=patch_size, + embed_dim=embed_dim, + depths=depths, + num_heads=num_heads, + window_size=window_size, + mlp_ratio=float(mlp_ratio), + backbone_eps=backbone_eps, + feature_size=feature_size, + mask_feature_size=mask_feature_size, + hidden_dim=hidden_dim, + num_attention_heads=num_attention_heads, + encoder_layers=_positive_int(config.get("encoder_layers"), "encoder_layers"), + encoder_feedforward_dim=_positive_int( + config.get("encoder_feedforward_dim"), "encoder_feedforward_dim" + ), + decoder_layers=_positive_int(config.get("decoder_layers"), "decoder_layers"), + dim_feedforward=_positive_int(config.get("dim_feedforward"), "dim_feedforward"), + num_queries=_positive_int(config.get("num_queries"), "num_queries"), + labels=labels, + ) diff --git a/families/mask2former/graph.py b/families/mask2former/graph.py new file mode 100644 index 0000000000..5440b6a909 --- /dev/null +++ b/families/mask2former/graph.py @@ -0,0 +1,273 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +"""TensorRT graph vocabulary owned by the Mask2Former family. + +The network is strongly typed and every activation is float32; shapes are static, so every helper works on +concrete dimensions. +""" + +from __future__ import annotations + +import numpy as np +import tensorrt as trt + + +def _check(layer, what: str): + if layer is None: + raise RuntimeError(f"TensorRT rejected the Mask2Former {what}") + return layer + + +def shape(tensor) -> tuple[int, ...]: + return tuple(int(value) for value in tensor.shape) + + +def constant(network, values, dtype=np.float32): + array = np.ascontiguousarray(np.asarray(values, dtype=dtype)) + layer = _check(network.add_constant(array.shape, trt.Weights(array)), "constant") + return layer.get_output(0) + + +def scalar_like(network, value: float, rank: int): + return constant(network, np.full((1,) * rank, value, dtype=np.float32)) + + +def elementwise(network, left, right, operation): + return _check( + network.add_elementwise(left, right, operation), "elementwise operation" + ).get_output(0) + + +def add(network, left, right): + return elementwise(network, left, right, trt.ElementWiseOperation.SUM) + + +def sub(network, left, right): + return elementwise(network, left, right, trt.ElementWiseOperation.SUB) + + +def mul(network, left, right): + return elementwise(network, left, right, trt.ElementWiseOperation.PROD) + + +def div(network, left, right): + return elementwise(network, left, right, trt.ElementWiseOperation.DIV) + + +def activation(network, tensor, kind): + return _check(network.add_activation(tensor, kind), "activation").get_output(0) + + +def relu(network, tensor): + return activation(network, tensor, trt.ActivationType.RELU) + + +def sigmoid(network, tensor): + return activation(network, tensor, trt.ActivationType.SIGMOID) + + +def gelu(network, tensor): + """Exact GELU, as torch writes it: 0.5 * x * (1 + erf(x / sqrt(2))).""" + + rank = len(shape(tensor)) + scaled = mul(network, tensor, scalar_like(network, float(1.0 / np.sqrt(2.0)), rank)) + error = _check(network.add_unary(scaled, trt.UnaryOperation.ERF), "GELU erf").get_output(0) + shifted = add(network, error, scalar_like(network, 1.0, rank)) + half = mul(network, tensor, scalar_like(network, 0.5, rank)) + return mul(network, half, shifted) + + +def shuffle(network, tensor, *, reshape=None, transpose=None, first_transpose=None): + layer = _check(network.add_shuffle(tensor), "shuffle") + if first_transpose is not None: + layer.first_transpose = trt.Permutation(first_transpose) + if reshape is not None: + layer.reshape_dims = trt.Dims(tuple(int(value) for value in reshape)) + if transpose is not None: + layer.second_transpose = trt.Permutation(transpose) + return layer.get_output(0) + + +def reshape(network, tensor, dims): + return shuffle(network, tensor, reshape=dims) + + +def transpose(network, tensor, permutation): + return shuffle(network, tensor, first_transpose=permutation) + + +def slice_static(network, tensor, start, size, stride=None): + stride = stride or (1,) * len(start) + layer = _check( + network.add_slice( + tensor, trt.Dims(tuple(start)), trt.Dims(tuple(size)), trt.Dims(tuple(stride)) + ), + "slice", + ) + return layer.get_output(0) + + +def concat(network, tensors, axis: int): + layer = _check(network.add_concatenation(list(tensors)), "concatenation") + layer.axis = axis + return layer.get_output(0) + + +def softmax(network, tensor, axis: int): + layer = _check(network.add_softmax(tensor), "softmax") + layer.axes = 1 << axis + return layer.get_output(0) + + +def matmul(network, left, right, *, transpose_left=False, transpose_right=False): + layer = network.add_matrix_multiply( + left, + trt.MatrixOperation.TRANSPOSE if transpose_left else trt.MatrixOperation.NONE, + right, + trt.MatrixOperation.TRANSPOSE if transpose_right else trt.MatrixOperation.NONE, + ) + return _check(layer, "matrix multiply").get_output(0) + + +def linear(network, tensor, weight, bias=None): + """torch.nn.Linear on the last axis: tensor @ weight.T + bias.""" + + rank = len(shape(tensor)) + matrix = np.ascontiguousarray(np.asarray(weight, dtype=np.float32).T) + if shape(tensor)[-1] != matrix.shape[0]: + raise ValueError( + f"linear input width {shape(tensor)[-1]} does not match weight {matrix.shape}" + ) + output = matmul( + network, tensor, constant(network, matrix.reshape((1,) * (rank - 2) + matrix.shape)) + ) + if bias is None: + return output + return add( + network, + output, + constant(network, np.asarray(bias, dtype=np.float32).reshape((1,) * (rank - 1) + (-1,))), + ) + + +def layer_norm(network, tensor, gamma, beta, eps: float): + """torch.nn.LayerNorm over the last axis.""" + + rank = len(shape(tensor)) + dims = (1,) * (rank - 1) + (shape(tensor)[-1],) + scale = constant(network, np.asarray(gamma, dtype=np.float32).reshape(dims)) + bias = constant(network, np.asarray(beta, dtype=np.float32).reshape(dims)) + layer = _check(network.add_normalization_v2(tensor, scale, bias, 1 << (rank - 1)), "layer norm") + layer.epsilon = float(eps) + return layer.get_output(0) + + +def group_norm(network, tensor, gamma, beta, groups: int, eps: float): + """torch.nn.GroupNorm on an NCHW tensor: statistics per group, affine per channel.""" + + batch, channels, height, width = shape(tensor) + grouped = reshape(network, tensor, (batch, groups, (channels // groups) * height * width)) + axis = 1 << 2 + mean = _check( + network.add_reduce(grouped, trt.ReduceOperation.AVG, axis, True), "group mean" + ).get_output(0) + centred = sub(network, grouped, mean) + variance = _check( + network.add_reduce(mul(network, centred, centred), trt.ReduceOperation.AVG, axis, True), + "group variance", + ).get_output(0) + deviation = _check( + network.add_unary( + add(network, variance, scalar_like(network, eps, 3)), trt.UnaryOperation.SQRT + ), + "group deviation", + ).get_output(0) + normed = reshape(network, div(network, centred, deviation), (batch, channels, height, width)) + scale = constant(network, np.asarray(gamma, dtype=np.float32).reshape(1, channels, 1, 1)) + bias = constant(network, np.asarray(beta, dtype=np.float32).reshape(1, channels, 1, 1)) + return add(network, mul(network, normed, scale), bias) + + +def conv2d(network, tensor, weight, bias=None, *, stride=1, padding=0): + weight = np.ascontiguousarray(np.asarray(weight, dtype=np.float32)) + out_channels, _, kernel_h, kernel_w = weight.shape + layer = _check( + network.add_convolution_nd( + tensor, + int(out_channels), + (int(kernel_h), int(kernel_w)), + trt.Weights(weight), + trt.Weights(np.ascontiguousarray(np.asarray(bias, dtype=np.float32))) + if bias is not None + else trt.Weights(), + ), + "convolution", + ) + layer.stride_nd = (int(stride), int(stride)) + layer.padding_nd = (int(padding), int(padding)) + return layer.get_output(0) + + +def resize_bilinear(network, tensor, height: int, width: int): + """torch.nn.functional.interpolate(mode="bilinear", align_corners=False), without antialiasing.""" + + dims = shape(tensor) + layer = _check(network.add_resize(tensor), "resize") + layer.shape = dims[:-2] + (int(height), int(width)) + layer.resize_mode = trt.InterpolationMode.LINEAR + layer.coordinate_transformation = trt.ResizeCoordinateTransformation.HALF_PIXEL + layer.exclude_outside = False + return layer.get_output(0) + + +def tokens_from_nchw(network, tensor): + """(1, C, H, W) -> (1, H*W, C), row-major over H then W.""" + + batch, channels, height, width = shape(tensor) + return shuffle(network, tensor, reshape=(batch, channels, height * width), transpose=(0, 2, 1)) + + +def nchw_from_tokens(network, tensor, height: int, width: int): + """(1, H*W, C) -> (1, C, H, W).""" + + batch, _, channels = shape(tensor) + return shuffle( + network, tensor, first_transpose=(0, 2, 1), reshape=(batch, channels, height, width) + ) + + +def split_heads(network, tensor, heads: int): + """(B, N, heads*D) -> (B, heads, N, D).""" + + batch, tokens, width = shape(tensor) + return shuffle( + network, tensor, reshape=(batch, tokens, heads, width // heads), transpose=(0, 2, 1, 3) + ) + + +def merge_heads(network, tensor): + """(B, heads, N, D) -> (B, N, heads*D).""" + + batch, heads, tokens, width = shape(tensor) + return shuffle( + network, tensor, first_transpose=(0, 2, 1, 3), reshape=(batch, tokens, heads * width) + ) + + +def roll(network, tensor, shifts, axes): + """torch.roll: a positive shift moves elements towards higher indices.""" + + for shift, axis in zip(shifts, axes): + dims = list(shape(tensor)) + extent = dims[axis] + offset = (-shift) % extent + if offset == 0: + continue + pieces = [] + for start, size in ((offset, extent - offset), (0, offset)): + begin, sizes = [0] * len(dims), list(dims) + begin[axis], sizes[axis] = start, size + pieces.append(slice_static(network, tensor, begin, sizes)) + tensor = concat(network, pieces, axis) + return tensor diff --git a/families/mask2former/model.py b/families/mask2former/model.py new file mode 100644 index 0000000000..0a19951870 --- /dev/null +++ b/families/mask2former/model.py @@ -0,0 +1,112 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +"""Build a Mask2Former semantic-segmentation bundle. + +One float32 engine maps the preprocessed image to the semantic scores the reference post-processor computes before +its final resize: Swin backbone, pixel decoder, masked-attention decoder, class probabilities and the einsum with the +sigmoid of the resized mask logits. The native runtime owns the image preprocessing, the final bilinear resize to +the original image size and the argmax. +""" + +from __future__ import annotations + +from pathlib import Path + +import tensorrt as trt + +from . import config as config_module +from . import weights as weights_module +from .config import SEMANTIC_SCORE_SIZE, Mask2FormerConfig +from .pixel_decoder import build_pixel_decoder +from .swin import build_backbone +from .transformer_decoder import build_semantic_scores + +_TASK = "image_to_semantic_segmentation" + + +def _build_engine(weights, config: Mask2FormerConfig, *, verbose: bool) -> bytes: + logger = trt.Logger(trt.Logger.VERBOSE if verbose else trt.Logger.WARNING) + builder = trt.Builder(logger) + network = builder.create_network(1 << int(trt.NetworkDefinitionCreationFlag.STRONGLY_TYPED)) + pixels = network.add_input( + "pixel_values", trt.float32, (1, 3, config.image_height, config.image_width) + ) + features = build_backbone(network, pixels, weights, config) + multi_scale, mask_features = build_pixel_decoder(network, features, weights, config) + scores = build_semantic_scores(network, multi_scale, mask_features, weights, config) + scores.name = "semantic_scores" + network.mark_output(scores) + + builder_config = builder.create_builder_config() + builder_config.builder_optimization_level = 3 + # The checkpoint is float32 and so is the reference; TF32 would round every matrix product to 10 mantissa bits. + builder_config.clear_flag(trt.BuilderFlag.TF32) + plan = builder.build_serialized_network(network, builder_config) + if plan is None: + raise RuntimeError("mask2former engine build failed") + return bytes(plan) + + +def build(request, writer) -> None: + """Build one Mask2Former bundle for `image_to_semantic_segmentation`.""" + + if request.task != _TASK: + raise ValueError(f"mask2former supports only task={_TASK}") + if request.backend != "trt": + raise ValueError("mask2former supports only backend=trt") + precision = str(request.precision).lower() + if precision != "fp32": + raise ValueError( + f"mask2former builds the float32 checkpoint at fp32 only, got precision={precision}" + ) + if request.quantization not in {None, "none"}: + raise NotImplementedError("mask2former does not support quantization") + if request.fp32_layers: + raise NotImplementedError("mask2former does not support mixed-precision layers") + if request.max_batch_size != 1: + raise NotImplementedError("mask2former builds one image per run (max_batch_size=1)") + if request.tensor_parallel_size != 1: + raise NotImplementedError("mask2former does not support tensor parallelism") + if request.context_parallel_size != 1: + raise NotImplementedError("mask2former does not support context parallelism") + if request.dynamic_kv_cache: + raise NotImplementedError("mask2former does not support dynamic_kv_cache") + if request.video_num_frames is not None: + raise NotImplementedError("mask2former does not support video_num_frames") + if request.max_sequence_length not in {None, 1}: + raise NotImplementedError("mask2former has no sequence length to configure") + if request.mtp_seq_len is not None: + raise NotImplementedError("mask2former does not support MTP speculative decoding") + + model_dir = Path(request.model_dir) + config = config_module.load(model_dir) + for value, expected, name in ( + (request.image_height, config.image_height, "image_height"), + (request.image_width, config.image_width, "image_width"), + ): + if value is not None and value != expected: + raise NotImplementedError( + f"mask2former builds at its processor size {config.image_height}x{config.image_width}; " + f"{name}={value} is not supported" + ) + plan = _build_engine( + weights_module.load(model_dir, config), config, verbose=bool(request.verbose) + ) + + writer.set_header(family="mask2former", task=request.task, backend=request.backend) + writer.add_bytes("engine.plan", plan) + writer.add_json( + "runtime.json", + { + "input_height": config.image_height, + "input_width": config.image_width, + "score_height": SEMANTIC_SCORE_SIZE, + "score_width": SEMANTIC_SCORE_SIZE, + "num_classes": config.num_labels, + "rescale_factor": config.rescale_factor, + "image_mean": list(config.image_mean), + "image_std": list(config.image_std), + "labels": list(config.labels), + }, + ) diff --git a/families/mask2former/pixel_decoder.py b/families/mask2former/pixel_decoder.py new file mode 100644 index 0000000000..0c40886cd3 --- /dev/null +++ b/families/mask2former/pixel_decoder.py @@ -0,0 +1,257 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +"""The Mask2Former pixel decoder: a multi-scale deformable-attention encoder over the three coarsest backbone levels, +one FPN level on the finest one, and the mask-feature projection (`Mask2FormerPixelDecoder.forward`). + +Multi-scale deformable attention is written with TensorRT's grid sample. `SampleMode.FILL` is torch's +`padding_mode="zeros"`; the query and the sampling offsets read the hidden states plus the position embeddings, while +the values read the plain hidden states. Nothing is padded, so every level's valid ratio is one and the reference +points are the normalized cell centres of each token's own level, repeated for every level. +""" + +from __future__ import annotations + +import numpy as np +import tensorrt as trt + +from . import graph as g +from .config import ENCODER_POINTS, FEATURE_LEVELS, GROUP_NORM_GROUPS, NORM_EPS, Mask2FormerConfig + +_PREFIX = "model.pixel_level_module.decoder" +_TEMPERATURE = 10000.0 +_SINE_EPS = 1e-6 + + +def sine_position_embedding(height: int, width: int, features: int) -> np.ndarray: + """`Mask2FormerSinePositionEmbedding(normalize=True)` without a mask: (height * width, 2 * features). + + Rows are the flattened (y, x) positions; the y half comes first, and each half interleaves sin of the even and + cos of the odd channels. + """ + + scale = 2.0 * np.pi + y_embed = np.arange(1, height + 1, dtype=np.float64) / (height + _SINE_EPS) * scale + x_embed = np.arange(1, width + 1, dtype=np.float64) / (width + _SINE_EPS) * scale + dim_t = _TEMPERATURE ** (2.0 * np.floor(np.arange(features, dtype=np.float64) / 2.0) / features) + + def encode(values: np.ndarray) -> np.ndarray: + raw = values[:, None] / dim_t + return np.stack((np.sin(raw[:, 0::2]), np.cos(raw[:, 1::2])), axis=2).reshape( + len(values), features + ) + + pos_y = np.repeat(encode(y_embed)[:, None, :], width, axis=1) + pos_x = np.repeat(encode(x_embed)[None, :, :], height, axis=0) + return ( + np.concatenate((pos_y, pos_x), axis=2) + .reshape(height * width, 2 * features) + .astype(np.float32) + ) + + +def reference_points(shapes) -> np.ndarray: + """Normalized cell centres in (x, y) order for every token of every level: (tokens, 2), float32 as torch.""" + + pieces = [] + for height, width in shapes: + ref_y = (np.arange(height, dtype=np.float32) + np.float32(0.5)) / np.float32(height) + ref_x = (np.arange(width, dtype=np.float32) + np.float32(0.5)) / np.float32(width) + grid_y, grid_x = np.meshgrid(ref_y, ref_x, indexing="ij") + pieces.append(np.stack((grid_x.reshape(-1), grid_y.reshape(-1)), axis=-1)) + return np.concatenate(pieces, axis=0).astype(np.float32) + + +def _deformable_attention(network, hidden, posed, reference, weights, prefix, shapes, heads): + """One multi-scale deformable self-attention over the flattened levels: hidden is (1, tokens, width).""" + + _, tokens, width = g.shape(hidden) + levels = len(shapes) + head_dim = width // heads + points = ENCODER_POINTS + + value = g.linear( + network, + hidden, + weights[f"{prefix}.value_proj.weight"], + weights[f"{prefix}.value_proj.bias"], + ) + offsets = g.linear( + network, + posed, + weights[f"{prefix}.sampling_offsets.weight"], + weights[f"{prefix}.sampling_offsets.bias"], + ) + offsets = g.reshape(network, offsets, (tokens, heads, levels, points, 2)) + scores = g.linear( + network, + posed, + weights[f"{prefix}.attention_weights.weight"], + weights[f"{prefix}.attention_weights.bias"], + ) + # One softmax across every level and point of a head. + scores = g.softmax(network, g.reshape(network, scores, (tokens, heads, levels * points)), 2) + + # location = reference + offset / (W, H) of the sampled level; grid = 2 * location - 1. + normalizer = np.asarray([[width_l, height_l] for height_l, width_l in shapes], dtype=np.float32) + scaled = g.div(network, offsets, g.constant(network, normalizer.reshape(1, 1, levels, 1, 2))) + location = g.add(network, g.constant(network, reference.reshape(tokens, 1, 1, 1, 2)), scaled) + grid = g.sub( + network, + g.mul(network, location, g.scalar_like(network, 2.0, 5)), + g.scalar_like(network, 1.0, 5), + ) + + sampled = [] + start = 0 + for level, (height_l, width_l) in enumerate(shapes): + count = height_l * width_l + piece = g.slice_static(network, value, (0, start, 0), (1, count, width)) + # (count, heads, head_dim) -> (heads, head_dim, H, W) + piece = g.shuffle(network, piece, reshape=(count, heads, head_dim), transpose=(1, 2, 0)) + piece = g.reshape(network, piece, (heads, head_dim, height_l, width_l)) + level_grid = g.slice_static( + network, grid, (0, 0, level, 0, 0), (tokens, heads, 1, points, 2) + ) + level_grid = g.shuffle( + network, level_grid, reshape=(tokens, heads, points, 2), transpose=(1, 0, 2, 3) + ) + layer = network.add_grid_sample(piece, level_grid) + if layer is None: + raise RuntimeError("TensorRT rejected the Mask2Former grid sample") + layer.interpolation_mode = trt.InterpolationMode.LINEAR + layer.sample_mode = trt.SampleMode.FILL + layer.align_corners = False + sampled.append(layer.get_output(0)) # (heads, head_dim, tokens, points) + start += count + + joined = g.concat( + network, sampled, 3 + ) # (heads, head_dim, tokens, levels * points), level-major + weights_by_head = g.shuffle( + network, scores, first_transpose=(1, 0, 2), reshape=(heads, 1, tokens, levels * points) + ) + reduced = network.add_reduce( + g.mul(network, joined, weights_by_head), trt.ReduceOperation.SUM, 1 << 3, False + ) + if reduced is None: + raise RuntimeError("TensorRT rejected the Mask2Former sampling reduction") + output = g.shuffle( + network, reduced.get_output(0), reshape=(1, width, tokens), transpose=(0, 2, 1) + ) + return g.linear( + network, + output, + weights[f"{prefix}.output_proj.weight"], + weights[f"{prefix}.output_proj.bias"], + ) + + +def _encoder_layer(network, hidden, position, reference, weights, prefix, shapes, heads): + posed = g.add(network, hidden, position) + attended = _deformable_attention( + network, hidden, posed, reference, weights, f"{prefix}.self_attn", shapes, heads + ) + hidden = g.layer_norm( + network, + g.add(network, hidden, attended), + weights[f"{prefix}.self_attn_layer_norm.weight"], + weights[f"{prefix}.self_attn_layer_norm.bias"], + NORM_EPS, + ) + inner = g.relu( + network, + g.linear(network, hidden, weights[f"{prefix}.fc1.weight"], weights[f"{prefix}.fc1.bias"]), + ) + inner = g.linear(network, inner, weights[f"{prefix}.fc2.weight"], weights[f"{prefix}.fc2.bias"]) + return g.layer_norm( + network, + g.add(network, hidden, inner), + weights[f"{prefix}.final_layer_norm.weight"], + weights[f"{prefix}.final_layer_norm.bias"], + NORM_EPS, + ) + + +def build_pixel_decoder(network, features, weights, config: Mask2FormerConfig): + """Return the three multi-scale feature maps (coarsest first) and the mask features, all (1, C, H, W).""" + + width = config.feature_size + levels = features[::-1][:FEATURE_LEVELS] + shapes = [tuple(g.shape(level)[2:]) for level in levels] + projected = [] + for index, level in enumerate(levels): + base = f"{_PREFIX}.input_projections.{index}" + projected.append( + g.group_norm( + network, + g.conv2d(network, level, weights[f"{base}.0.weight"], weights[f"{base}.0.bias"]), + weights[f"{base}.1.weight"], + weights[f"{base}.1.bias"], + GROUP_NORM_GROUPS, + NORM_EPS, + ) + ) + hidden = g.concat(network, [g.tokens_from_nchw(network, level) for level in projected], 1) + + level_embed = np.asarray(weights[f"{_PREFIX}.level_embed"], dtype=np.float32) + if level_embed.shape != (FEATURE_LEVELS, width): + raise ValueError(f"mask2former pixel-decoder level_embed has shape {level_embed.shape}") + position = np.concatenate( + [ + sine_position_embedding(height, width_l, width // 2) + level_embed[index][None, :] + for index, (height, width_l) in enumerate(shapes) + ], + axis=0, + ) + position = g.constant(network, position[None]) + reference = reference_points(shapes) + for layer in range(config.encoder_layers): + hidden = _encoder_layer( + network, + hidden, + position, + reference, + weights, + f"{_PREFIX}.encoder.layers.{layer}", + shapes, + config.num_attention_heads, + ) + + outputs = [] + start = 0 + for height, width_l in shapes: + count = height * width_l + piece = g.slice_static(network, hidden, (0, start, 0), (1, count, width)) + outputs.append(g.nchw_from_tokens(network, piece, height, width_l)) + start += count + + finest = features[0] + lateral = g.group_norm( + network, + g.conv2d(network, finest, weights[f"{_PREFIX}.adapter_1.0.weight"]), + weights[f"{_PREFIX}.adapter_1.1.weight"], + weights[f"{_PREFIX}.adapter_1.1.bias"], + GROUP_NORM_GROUPS, + NORM_EPS, + ) + height, width_l = g.shape(finest)[2:] + fpn = g.add(network, lateral, g.resize_bilinear(network, outputs[-1], height, width_l)) + fpn = g.relu( + network, + g.group_norm( + network, + g.conv2d(network, fpn, weights[f"{_PREFIX}.layer_1.0.weight"], padding=1), + weights[f"{_PREFIX}.layer_1.1.weight"], + weights[f"{_PREFIX}.layer_1.1.bias"], + GROUP_NORM_GROUPS, + NORM_EPS, + ), + ) + mask_features = g.conv2d( + network, + fpn, + weights[f"{_PREFIX}.mask_projection.weight"], + weights[f"{_PREFIX}.mask_projection.bias"], + ) + return outputs, mask_features diff --git a/families/mask2former/requirements.txt b/families/mask2former/requirements.txt new file mode 100644 index 0000000000..b67cc9bf99 --- /dev/null +++ b/families/mask2former/requirements.txt @@ -0,0 +1,9 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +# The runtime reproduces Pillow 13's bilinear resize, which the reference image processor runs. +Pillow==13.0.0 +# The reference model class requires scipy when it is constructed (its training loss). +scipy==1.18.1 +# scipy alone resolves numpy past the range the CI image installs. +numpy>=1.24,<2.5 diff --git a/families/mask2former/runtime/CMakeLists.txt b/families/mask2former/runtime/CMakeLists.txt new file mode 100644 index 0000000000..ada2914c15 --- /dev/null +++ b/families/mask2former/runtime/CMakeLists.txt @@ -0,0 +1,82 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +add_library(trtmc_model_mask2former SHARED + image_ops.cpp + pipeline.cpp + plugin.cpp +) +target_include_directories(trtmc_model_mask2former PRIVATE + ${PROJECT_SOURCE_DIR} + ${PROJECT_SOURCE_DIR}/core/runtime/include +) +target_include_directories(trtmc_model_mask2former SYSTEM PRIVATE + ${TRTMC_CUDA_INCLUDE_DIR} +) +target_link_libraries(trtmc_model_mask2former PRIVATE + trtmc_core + nlohmann_json::nlohmann_json + ${TRTMC_CUDART_LIBRARY} +) +target_compile_options(trtmc_model_mask2former PRIVATE + "$<$:-Wall;-Wextra;-Wpedantic>" +) +set_target_properties(trtmc_model_mask2former PROPERTIES + LIBRARY_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}" + BUILD_RPATH "\$ORIGIN" + INSTALL_RPATH "\$ORIGIN" +) +install(TARGETS trtmc_model_mask2former + LIBRARY DESTINATION ${CMAKE_INSTALL_LIBDIR} +) +# The library carries code adapted from Pillow (MIT-CMU); ship its notice with it. +install(FILES ${PROJECT_SOURCE_DIR}/families/mask2former/NOTICE + DESTINATION ${CMAKE_INSTALL_DATADIR}/trtmc/families/mask2former +) + +if(TRTMC_BUILD_TESTS) + # The image operations are compiled into the tests directly: the model library exports only its factory. + add_executable(test_mask2former_task_contract + ${PROJECT_SOURCE_DIR}/families/mask2former/tests/cpp/test_task_contract.cpp + image_ops.cpp + pipeline.cpp + ) + add_executable(mask2former_image_ops_tool + ${PROJECT_SOURCE_DIR}/families/mask2former/tests/cpp/image_ops_tool.cpp + image_ops.cpp + ) + foreach(_target IN ITEMS test_mask2former_task_contract mask2former_image_ops_tool) + target_include_directories(${_target} PRIVATE + ${PROJECT_SOURCE_DIR} + ${PROJECT_SOURCE_DIR}/core/runtime/include + ) + target_include_directories(${_target} SYSTEM PRIVATE + ${TRTMC_CUDA_INCLUDE_DIR} + ) + target_link_libraries(${_target} PRIVATE trtmc_core ${TRTMC_CUDART_LIBRARY}) + target_compile_options(${_target} PRIVATE -Wall -Wextra -Wpedantic -Werror) + endforeach() + target_link_libraries(test_mask2former_task_contract PRIVATE nlohmann_json::nlohmann_json) + set_target_properties(mask2former_image_ops_tool PROPERTIES + RUNTIME_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}" + ) + add_test(NAME mask2former_task_contract COMMAND test_mask2former_task_contract) + set_tests_properties(mask2former_task_contract PROPERTIES LABELS "cpu") + + foreach(_language IN ITEMS c cpp) + add_executable(test_mask2former_sdk_${_language} + ${PROJECT_SOURCE_DIR}/families/mask2former/tests/sdk_consumer.${_language} + ) + target_link_libraries(test_mask2former_sdk_${_language} PRIVATE trtmc_c) + target_compile_options(test_mask2former_sdk_${_language} PRIVATE + -Wall -Wextra -Wpedantic -Werror + ) + set_target_properties(test_mask2former_sdk_${_language} PROPERTIES + RUNTIME_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}" + ) + endforeach() + # Premerge builds the family's CTest targets by name; the Python parity test runs the image-ops tool. + add_dependencies(test_mask2former_task_contract + mask2former_image_ops_tool test_mask2former_sdk_c test_mask2former_sdk_cpp + ) +endif() diff --git a/families/mask2former/runtime/image_ops.cpp b/families/mask2former/runtime/image_ops.cpp new file mode 100644 index 0000000000..c8f9de5fd6 --- /dev/null +++ b/families/mask2former/runtime/image_ops.cpp @@ -0,0 +1,268 @@ +/* + * SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. + * SPDX-License-Identifier: Apache-2.0 + */ + +#include "families/mask2former/runtime/image_ops.h" + +#include +#include +#include +#include +#include + +namespace trtmc::mask2former { +namespace { + +// Pillow's 8-bit resampling: coefficients in double, normalized to 22-bit fixed point, accumulated +// in int from a half-unit rounding offset and clipped to [0, 255]. Adapted from Pillow +// src/libImaging/Resample.c (precompute_coeffs, normalize_coeffs_8bpc, ImagingResampleInner); see +// NOTICE. +constexpr int kPrecisionBits = 32 - 8 - 2; + +struct Taps { + std::vector first; + std::vector count; + std::vector weights; // [output][max_taps] + std::int32_t max_taps{0}; +}; + +double bilinear_filter(double x) { + if (x < 0.0) + x = -x; + return x < 1.0 ? 1.0 - x : 0.0; +} + +Taps bilinear_taps(std::int32_t input_size, std::int32_t output_size) { + const double scale = static_cast(static_cast(input_size)) / output_size; + const double filter_scale = std::max(scale, 1.0); + const double support = 1.0 * filter_scale; + Taps taps; + taps.max_taps = static_cast(std::ceil(support)) * 2 + 1; + taps.first.resize(static_cast(output_size)); + taps.count.resize(static_cast(output_size)); + taps.weights.assign(static_cast(output_size) * taps.max_taps, 0); + const double inverse_filter_scale = 1.0 / filter_scale; + std::vector raw(static_cast(taps.max_taps)); + for (std::int32_t index = 0; index < output_size; ++index) { + const double center = (index + 0.5) * scale; + const auto first = std::max(static_cast(center - support + 0.5), 0); + const auto end = std::min(static_cast(center + support + 0.5), input_size); + const auto count = end - first; + double total = 0.0; + for (std::int32_t tap = 0; tap < count; ++tap) { + raw[static_cast(tap)] = + bilinear_filter((tap + first - center + 0.5) * inverse_filter_scale); + total += raw[static_cast(tap)]; + } + auto* weights = taps.weights.data() + static_cast(index) * taps.max_taps; + for (std::int32_t tap = 0; tap < count; ++tap) { + const double value = total != 0.0 ? raw[static_cast(tap)] / total : 0.0; + weights[tap] = static_cast(0.5 + value * (1 << kPrecisionBits)); + } + taps.first[static_cast(index)] = first; + taps.count[static_cast(index)] = count; + } + return taps; +} + +std::uint8_t clip8(std::int32_t value) { + return static_cast(std::clamp(value >> kPrecisionBits, 0, 255)); +} + +// One pass along rows (horizontal) or columns (vertical) of an HWC RGB image. +std::vector resample_horizontal(const std::vector& input, + std::int32_t height, std::int32_t width, + std::int32_t out_width) { + const auto taps = bilinear_taps(width, out_width); + std::vector output(static_cast(height) * out_width * 3); + for (std::int32_t y = 0; y < height; ++y) { + const auto* row = input.data() + static_cast(y) * width * 3; + auto* out = output.data() + static_cast(y) * out_width * 3; + for (std::int32_t x = 0; x < out_width; ++x) { + const auto first = taps.first[static_cast(x)]; + const auto count = taps.count[static_cast(x)]; + const auto* weights = taps.weights.data() + static_cast(x) * taps.max_taps; + for (int channel = 0; channel < 3; ++channel) { + std::int32_t sum = 1 << (kPrecisionBits - 1); + for (std::int32_t tap = 0; tap < count; ++tap) + sum += row[static_cast(first + tap) * 3 + channel] * weights[tap]; + out[static_cast(x) * 3 + channel] = clip8(sum); + } + } + } + return output; +} + +std::vector resample_vertical(const std::vector& input, + std::int32_t height, std::int32_t width, + std::int32_t out_height) { + const auto taps = bilinear_taps(height, out_height); + const auto stride = static_cast(width) * 3; + std::vector output(static_cast(out_height) * stride); + for (std::int32_t y = 0; y < out_height; ++y) { + const auto first = taps.first[static_cast(y)]; + const auto count = taps.count[static_cast(y)]; + const auto* weights = taps.weights.data() + static_cast(y) * taps.max_taps; + auto* out = output.data() + static_cast(y) * stride; + for (std::size_t column = 0; column < stride; ++column) { + std::int32_t sum = 1 << (kPrecisionBits - 1); + for (std::int32_t tap = 0; tap < count; ++tap) + sum += + input[static_cast(first + tap) * stride + column] * weights[tap]; + out[column] = clip8(sum); + } + } + return output; +} + +// The processor rescales in float64 and casts to float32, then normalizes in float32. The cast is +// defined only for products within float range; normalization_is_finite() checks that first. +float normalize(std::uint8_t value, std::size_t channel, const PreprocessConfig& config) { + const auto rescaled = static_cast(static_cast(value) * config.rescale_factor); + return (rescaled - config.mean[channel]) / config.std[channel]; +} + +void require_extent(std::int32_t height, std::int32_t width, const char* what) { + if (height <= 0 || width <= 0 || + static_cast(height) > + std::numeric_limits::max() / static_cast(width) / 4) + throw std::invalid_argument(std::string("Mask2Former ") + what + + " must be a positive size"); +} + +} // namespace + +std::vector resize_bilinear_rgb8(const std::uint8_t* pixels, std::int32_t height, + std::int32_t width, std::int32_t out_height, + std::int32_t out_width) { + require_extent(height, width, "source image"); + require_extent(out_height, out_width, "resize target"); + if (pixels == nullptr) + throw std::invalid_argument("Mask2Former source image is null"); + std::vector image(pixels, pixels + static_cast(height) * width * 3); + const bool horizontal = out_width != width; + const bool vertical = out_height != height; + // Pillow 13 runs the vertical pass first when the height shrinks by more than twice the width's + // reduction. + const bool horizontal_first = + !((height - out_height) > 0 && (height - out_height) > (width - out_width) * 2); + if (horizontal_first) { + if (horizontal) + image = resample_horizontal(image, height, width, out_width); + if (vertical) + image = resample_vertical(image, height, out_width, out_height); + } else { + if (vertical) + image = resample_vertical(image, height, width, out_height); + if (horizontal) + image = resample_horizontal(image, out_height, width, out_width); + } + return image; +} + +bool normalization_is_finite(const PreprocessConfig& config) { + if (!(config.rescale_factor > 0.0) || !std::isfinite(config.rescale_factor) || + 255.0 * config.rescale_factor > static_cast(std::numeric_limits::max())) + return false; + for (std::size_t channel = 0; channel < 3; ++channel) { + // An infinite std would map every value to a finite zero. + if (!std::isfinite(config.mean[channel]) || !std::isfinite(config.std[channel])) + return false; + for (int value = 0; value <= 255; ++value) + if (!std::isfinite(normalize(static_cast(value), channel, config))) + return false; + } + return true; +} + +std::vector preprocess(const std::uint8_t* pixels, std::int32_t height, std::int32_t width, + const PreprocessConfig& config) { + if (!normalization_is_finite(config)) + throw std::invalid_argument("Mask2Former rescale_factor, image_mean and image_std must " + "normalize 8-bit values to finite float32 values"); + const auto resized = resize_bilinear_rgb8(pixels, height, width, config.height, config.width); + const auto plane = static_cast(config.height) * config.width; + std::vector values(plane * 3); + for (std::size_t index = 0; index < plane; ++index) + for (std::size_t channel = 0; channel < 3; ++channel) + values[channel * plane + index] = + normalize(resized[index * 3 + channel], channel, config); + return values; +} + +std::vector resize_argmax(const float* scores, std::int32_t classes, + std::int32_t score_height, std::int32_t score_width, + std::int32_t height, std::int32_t width) { + require_extent(score_height, score_width, "score map"); + require_extent(height, width, "segmentation size"); + if (scores == nullptr || classes <= 0) + throw std::invalid_argument("Mask2Former scores must be nonempty"); + const auto plane = static_cast(score_height) * score_width; + if (plane > std::numeric_limits::max() / static_cast(classes)) + throw std::invalid_argument("Mask2Former score maps are too large"); + // Every score, not only those the resize reads: a smaller image samples only some of them. + if (!std::all_of(scores, scores + plane * static_cast(classes), + [](float value) { return std::isfinite(value); })) + throw std::runtime_error("Mask2Former semantic scores are not finite"); + // torch area_pixel_compute_source_index (align_corners=False) in float: src = max(scale * (dst + // + 0.5) - 0.5, 0), the lower tap is trunc(src) and the upper one is clamped to the last row or + // column. + struct Axis { + std::vector low, high; + std::vector low_weight, high_weight; + }; + const auto axis = [](std::int32_t input, std::int32_t output) { + Axis result; + const float scale = static_cast(input) / static_cast(output); + for (std::int32_t index = 0; index < output; ++index) { + const float source = std::max(scale * (static_cast(index) + 0.5F) - 0.5F, 0.0F); + const auto low = static_cast(source); + const float lambda = source - static_cast(low); + result.low.push_back(low); + result.high.push_back(low < input - 1 ? low + 1 : low); + result.high_weight.push_back(lambda); + result.low_weight.push_back(1.0F - lambda); + } + return result; + }; + const auto rows = axis(score_height, height); + const auto columns = axis(score_width, width); + std::vector labels(static_cast(height) * width, 0); + std::vector best(static_cast(width)); + for (std::int32_t y = 0; y < height; ++y) { + const auto top = + static_cast(rows.low[static_cast(y)]) * score_width; + const auto bottom = + static_cast(rows.high[static_cast(y)]) * score_width; + const float top_weight = rows.low_weight[static_cast(y)]; + const float bottom_weight = rows.high_weight[static_cast(y)]; + auto* row_labels = labels.data() + static_cast(y) * width; + std::fill(best.begin(), best.end(), -std::numeric_limits::infinity()); + for (std::int32_t label = 0; label < classes; ++label) { + const float* source = scores + static_cast(label) * plane; + for (std::int32_t x = 0; x < width; ++x) { + const auto left = + static_cast(columns.low[static_cast(x)]); + const auto right = + static_cast(columns.high[static_cast(x)]); + const float left_weight = columns.low_weight[static_cast(x)]; + const float right_weight = columns.high_weight[static_cast(x)]; + const float value = top_weight * (left_weight * source[top + left] + + right_weight * source[top + right]) + + bottom_weight * (left_weight * source[bottom + left] + + right_weight * source[bottom + right]); + if (!std::isfinite(value)) + throw std::runtime_error("Mask2Former semantic scores are not finite"); + // Strictly greater keeps the first maximum, as torch.argmax does. + if (value > best[static_cast(x)]) { + best[static_cast(x)] = value; + row_labels[x] = label; + } + } + } + } + return labels; +} + +} // namespace trtmc::mask2former diff --git a/families/mask2former/runtime/image_ops.h b/families/mask2former/runtime/image_ops.h new file mode 100644 index 0000000000..54c4fc07d0 --- /dev/null +++ b/families/mask2former/runtime/image_ops.h @@ -0,0 +1,46 @@ +/* + * SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. + * SPDX-License-Identifier: Apache-2.0 + */ + +#pragma once + +#include +#include +#include + +namespace trtmc::mask2former { + +struct PreprocessConfig { + std::int32_t height{0}; + std::int32_t width{0}; + double rescale_factor{0.0}; + std::array mean{}; + std::array std{}; +}; + +// Image.resize((width, height), Image.BILINEAR) of Pillow 13 on an 8-bit RGB image: separable +// fixed-point passes, each rounded to 8 bits, in Pillow's pass order. Input and output are +// contiguous HWC. +std::vector resize_bilinear_rgb8(const std::uint8_t* pixels, std::int32_t height, + std::int32_t width, std::int32_t out_height, + std::int32_t out_width); + +// True when every 8-bit value normalizes to a finite float32 the way preprocess() computes it: a +// positive rescale factor that keeps 255 within float range, and no mean or std that makes +// (value - mean) / std overflow. +bool normalization_is_finite(const PreprocessConfig& config); + +// Mask2FormerImageProcessor on an 8-bit RGB image: the resize above, then float32(value * +// rescale_factor) and (value - mean) / std per channel. Returns CHW float32 pixel values; throws +// std::invalid_argument when the normalization is not finite. +std::vector preprocess(const std::uint8_t* pixels, std::int32_t height, std::int32_t width, + const PreprocessConfig& config); + +// Class map of CHW scores resized bilinearly (torch interpolate, align_corners=False) to height x +// width: the first class with the largest resized score at each pixel. +std::vector resize_argmax(const float* scores, std::int32_t classes, + std::int32_t score_height, std::int32_t score_width, + std::int32_t height, std::int32_t width); + +} // namespace trtmc::mask2former diff --git a/families/mask2former/runtime/pipeline.cpp b/families/mask2former/runtime/pipeline.cpp new file mode 100644 index 0000000000..b267f7df4a --- /dev/null +++ b/families/mask2former/runtime/pipeline.cpp @@ -0,0 +1,217 @@ +/* + * SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. + * SPDX-License-Identifier: Apache-2.0 + */ + +#include "families/mask2former/runtime/pipeline.h" + +#include +#include +#include +#include +#include +#include +#include + +namespace trtmc::mask2former { +namespace { + +constexpr const char* kInput = "pixel_values"; +constexpr const char* kOutput = "semantic_scores"; + +using Json = nlohmann::json; + +[[noreturn]] void invalid_metadata(const std::string& message) { + throw std::runtime_error("Mask2Former runtime.json " + message); +} + +// The default parser keeps the last of two equal keys; refuse them instead. +Json parse_unique_keys(const std::vector& data) { + std::vector> keys; + try { + return Json::parse(data.begin(), data.end(), + [&keys](int, Json::parse_event_t event, Json& parsed) { + if (event == Json::parse_event_t::object_start) { + keys.emplace_back(); + } else if (event == Json::parse_event_t::object_end) { + keys.pop_back(); + } else if (event == Json::parse_event_t::key && + !keys.back().insert(parsed.get()).second) { + invalid_metadata("repeats the key " + parsed.get()); + } + return true; + }); + } catch (const Json::exception& error) { + invalid_metadata(std::string("is not valid JSON: ") + error.what()); + } +} + +const Json& field(const Json& json, const char* name) { + const auto found = json.find(name); + if (found == json.end()) + invalid_metadata(std::string("is missing ") + name); + return *found; +} + +// A JSON integer only: get() would truncate 384.5 and wrap values beyond int32. +// The parser stores every nonnegative integer as unsigned. +std::int32_t positive_int32(const Json& json, const char* name) { + const auto& value = field(json, name); + if (value.is_number_unsigned()) { + const auto number = value.get(); + if (number > 0 && + number <= static_cast(std::numeric_limits::max())) + return static_cast(number); + } + invalid_metadata(std::string(name) + " must be a positive integer within int32"); +} + +double finite_number(const Json& value, const char* name) { + if (!value.is_number()) + invalid_metadata(std::string(name) + " must be a number"); + const auto number = value.get(); + if (!std::isfinite(number)) + invalid_metadata(std::string(name) + " must be finite"); + return number; +} + +std::array float_channels(const Json& json, const char* name) { + const auto& values = field(json, name); + if (!values.is_array() || values.size() != 3) + invalid_metadata(std::string(name) + " must hold three numbers"); + std::array result{}; + for (std::size_t index = 0; index < result.size(); ++index) { + const auto number = finite_number(values[index], name); + // Converting a double beyond float range to float is undefined. + if (std::fabs(number) > static_cast(std::numeric_limits::max())) + invalid_metadata(std::string(name) + " must fit float"); + result[index] = static_cast(number); + } + return result; +} + +std::vector class_names(const Json& json) { + const auto& values = field(json, "labels"); + if (!values.is_array() || values.empty()) + invalid_metadata("labels must be a nonempty array"); + std::vector names; + names.reserve(values.size()); + for (const auto& value : values) { + if (!value.is_string() || value.get_ref().empty()) + invalid_metadata("labels must be nonempty strings"); + names.push_back(value.get()); + } + return names; +} + +// The checkpoint's processor resizes 8-bit images. Float32 pixels in [0, 1] are quantized to the +// nearest 8-bit value, which recovers the exact bytes of an 8-bit image decoded as value / 255. +std::vector rgb8(const internal::ImageView& image) { + if (image.data == nullptr || image.channels != 3 || image.height == 0 || image.width == 0 || + image.height > static_cast(std::numeric_limits::max()) || + image.width > static_cast(std::numeric_limits::max()) || + static_cast(image.height) > + std::numeric_limits::max() / image.width / 3 / sizeof(float)) + throw std::invalid_argument("Mask2Former requires a nonempty contiguous RGB image"); + const auto count = static_cast(image.height) * image.width * 3; + if (image.format == internal::ImageFormat::UInt8) { + if (image.byte_size != count) + throw std::invalid_argument("Mask2Former 8-bit RGB input has the wrong byte size"); + const auto* values = static_cast(image.data); + return {values, values + count}; + } + if (image.format != internal::ImageFormat::Float32 || image.byte_size != count * sizeof(float)) + throw std::invalid_argument("Mask2Former requires 8-bit or float32 RGB input"); + const auto* values = static_cast(image.data); + std::vector bytes(count); + for (std::size_t index = 0; index < count; ++index) { + const float value = values[index]; + if (!(value >= 0.0F && value <= 1.0F)) + throw std::invalid_argument("Mask2Former float32 RGB values must lie in [0, 1]"); + bytes[index] = static_cast(std::lround(value * 255.0F)); + } + return bytes; +} + +bool has_shape(const ITrtModule& engine, const char* name, const std::vector& shape) { + return engine.tensor_dtype(name) == DType::kFloat32 && engine.tensor_shape(name) == shape; +} + +} // namespace + +RuntimeMetadata parse_runtime_json(const std::vector& data) { + const auto json = parse_unique_keys(data); + if (!json.is_object()) + invalid_metadata("must be a JSON object"); + RuntimeMetadata metadata; + metadata.preprocess.height = positive_int32(json, "input_height"); + metadata.preprocess.width = positive_int32(json, "input_width"); + metadata.preprocess.rescale_factor = + finite_number(field(json, "rescale_factor"), "rescale_factor"); + metadata.preprocess.mean = float_channels(json, "image_mean"); + metadata.preprocess.std = float_channels(json, "image_std"); + metadata.head.score_height = positive_int32(json, "score_height"); + metadata.head.score_width = positive_int32(json, "score_width"); + metadata.head.labels = class_names(json); + if (static_cast(positive_int32(json, "num_classes")) != + metadata.head.labels.size()) + invalid_metadata("labels do not match num_classes"); + return metadata; +} + +Mask2FormerSemanticSegmentation::Mask2FormerSemanticSegmentation(std::unique_ptr engine, + PreprocessConfig preprocess, + SemanticHead head) + : engine_(std::move(engine)), preprocess_(preprocess), head_(std::move(head)) { + if (!engine_ || !engine_->ok()) + throw std::runtime_error("Mask2Former engine failed to load"); + const auto classes = static_cast(head_.labels.size()); + if (preprocess_.height <= 0 || preprocess_.width <= 0 || head_.score_height <= 0 || + head_.score_width <= 0 || classes <= 0 || + classes > std::numeric_limits::max() || !(preprocess_.rescale_factor > 0.0) || + !std::isfinite(preprocess_.rescale_factor)) + throw std::runtime_error("Mask2Former runtime.json does not match its runtime contract"); + if (!normalization_is_finite(preprocess_)) + throw std::runtime_error("Mask2Former rescale_factor, image_mean and image_std must " + "normalize 8-bit values to finite float32 values"); + if (!engine_->has_input(kInput) || !engine_->has_output(kOutput) || + !has_shape(*engine_, kInput, {1, 3, preprocess_.height, preprocess_.width}) || + !has_shape(*engine_, kOutput, {1, classes, head_.score_height, head_.score_width})) + throw std::runtime_error("Mask2Former engine I/O does not match runtime.json"); +} + +internal::SemanticSegmentationResult +Mask2FormerSemanticSegmentation::run(const internal::ImageToSemanticSegmentationRequest& request, + internal::ConfigView config) { + if (!config.empty()) + throw internal::ConfigError("Mask2Former has no runtime configuration"); + const auto& image = request.image; + const auto bytes = rgb8(image); + const auto height = static_cast(image.height); + const auto width = static_cast(image.width); + auto pixels = preprocess(bytes.data(), height, width, preprocess_); + + Tensor input; + input.data = pixels.data(); + input.shape = {1, 3, preprocess_.height, preprocess_.width}; + input.dtype = DType::kFloat32; + const auto outputs = engine_->forward({{kInput, input}}); + const auto found = outputs.find(kOutput); + const auto classes = static_cast(head_.labels.size()); + const std::vector expected{1, classes, head_.score_height, head_.score_width}; + if (found == outputs.end() || found->second.data == nullptr || + found->second.dtype != DType::kFloat32 || found->second.shape != expected) + throw std::runtime_error("Mask2Former engine returned no complete float32 semantic scores"); + + internal::SemanticSegmentationResult result; + result.labels = resize_argmax(static_cast(found->second.data), classes, + head_.score_height, head_.score_width, height, width); + result.height = image.height; + result.width = image.width; + result.class_ids.resize(head_.labels.size()); + std::iota(result.class_ids.begin(), result.class_ids.end(), 0); + result.class_names = head_.labels; + return result; +} + +} // namespace trtmc::mask2former diff --git a/families/mask2former/runtime/pipeline.h b/families/mask2former/runtime/pipeline.h new file mode 100644 index 0000000000..6e05e8b7e3 --- /dev/null +++ b/families/mask2former/runtime/pipeline.h @@ -0,0 +1,59 @@ +/* + * SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. + * SPDX-License-Identifier: Apache-2.0 + */ + +#pragma once + +#include "families/mask2former/runtime/image_ops.h" +#include "trtmc/internal/model.h" +#include "trtmc/internal/perception.h" +#include "trtmc/runtime/trt_module.h" + +#include +#include +#include +#include + +namespace trtmc::mask2former { + +struct SemanticHead { + std::int32_t score_height{0}; + std::int32_t score_width{0}; + std::vector labels; // One name per class ID, in class order. +}; + +// The bundle's runtime.json: the image preprocessing and the semantic head. +struct RuntimeMetadata { + PreprocessConfig preprocess; + SemanticHead head; +}; + +// Reads runtime.json strictly: one JSON object without repeated keys; sizes and the class count are +// positive JSON integers within int32; numbers are finite, and those stored as float fit float; +// labels are nonempty strings, one per class. Throws std::runtime_error otherwise. +RuntimeMetadata parse_runtime_json(const std::vector& data); + +class Mask2FormerSemanticSegmentation final : public internal::IModel, + public internal::IImageToSemanticSegmentation { + public: + Mask2FormerSemanticSegmentation(std::unique_ptr engine, PreprocessConfig preprocess, + SemanticHead head); + + const char* task() const noexcept override { + return IImageToSemanticSegmentation::kTask.data(); + } + std::vector task_bindings() override { + return {internal::bind(*this)}; + } + internal::SemanticSegmentationResult + run(const internal::ImageToSemanticSegmentationRequest& request, + internal::ConfigView config) override; + + private: + std::unique_ptr engine_; + PreprocessConfig preprocess_; + SemanticHead head_; +}; + +} // namespace trtmc::mask2former diff --git a/families/mask2former/runtime/plugin.cpp b/families/mask2former/runtime/plugin.cpp new file mode 100644 index 0000000000..bfc8baad31 --- /dev/null +++ b/families/mask2former/runtime/plugin.cpp @@ -0,0 +1,40 @@ +/* + * SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. + * SPDX-License-Identifier: Apache-2.0 + */ + +#include "families/mask2former/runtime/pipeline.h" +#include "trtmc/runtime/family_factory.h" +#include "trtmc/runtime/trt_backend.h" + +#include +#include +#include + +namespace trtmc::mask2former { +namespace { + +std::vector require_section(const BundleReader& bundle, const char* name) { + const auto* section = bundle.find_section(name); + if (section == nullptr || section->length == 0) + throw std::runtime_error("bundle section is missing or empty: " + std::string(name)); + return bundle.read_section(name); +} + +} // namespace +} // namespace trtmc::mask2former + +extern "C" trtmc::ITask* trtmc_create_family(const trtmc::FamilyContext& context) { + if (context.kv_cache_size_bytes != 0) + throw std::invalid_argument("mask2former does not support --kv-cache-size"); + auto metadata = trtmc::mask2former::parse_runtime_json( + trtmc::mask2former::require_section(context.reader, "runtime.json")); + const auto plan = trtmc::mask2former::require_section(context.reader, "engine.plan"); + + trtmc::ModuleCreateOptions options{}; + auto engine = context.backend.create_module(plan.data(), plan.size(), options); + if (!engine || !engine->ok()) + throw std::runtime_error("Mask2Former engine failed to load"); + return new trtmc::mask2former::Mask2FormerSemanticSegmentation( + std::move(engine), metadata.preprocess, std::move(metadata.head)); +} diff --git a/families/mask2former/support.py b/families/mask2former/support.py new file mode 100644 index 0000000000..048192ab53 --- /dev/null +++ b/families/mask2former/support.py @@ -0,0 +1,14 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +"""Checkpoint identity and task ownership for Mask2Former.""" + +from tensorrt_model_connect.model_support import family_support + + +describe = family_support( + model_types=("mask2former",), + architectures=("Mask2FormerForUniversalSegmentation",), + tasks=("image_to_semantic_segmentation",), + default_task="image_to_semantic_segmentation", +) diff --git a/families/mask2former/swin.py b/families/mask2former/swin.py new file mode 100644 index 0000000000..1e9023c6d6 --- /dev/null +++ b/families/mask2former/swin.py @@ -0,0 +1,246 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +"""The Swin backbone of Mask2Former, as `SwinBackbone` computes it. + +Two properties of the backbone's call are easy to miss: + +* it partitions windows unconditionally (`always_partition=True`), so a stage whose resolution equals the window + size keeps the configured window and, in every odd block, the half-window cyclic shift and its region mask; +* each returned feature map is the stage output *before* patch merging, normalized by that stage's own LayerNorm. +""" + +from __future__ import annotations + +import math + +import numpy as np + +from . import graph as g +from .config import Mask2FormerConfig + +_PREFIX = "model.pixel_level_module.encoder" +# The region mask Swin adds to attention scores across shifted-window seams. +_SEAM_MASK = -100.0 + + +def relative_position_index(window: int) -> np.ndarray: + """`SwinSelfAttention.create_relative_position_index` for a square window.""" + + coords = np.stack(np.meshgrid(np.arange(window), np.arange(window), indexing="ij")) + flat = coords.reshape(2, -1) + relative = (flat[:, :, None] - flat[:, None, :]).transpose(1, 2, 0) + (window - 1) + return relative[:, :, 0] * (2 * window - 1) + relative[:, :, 1] + + +def shifted_window_mask(height: int, width: int, window: int, shift: int) -> np.ndarray: + """`SwinLayer.get_attn_mask`: (windows, window*window, window*window) of 0 and -100.""" + + image = np.zeros((height, width), dtype=np.float32) + count = 0 + for rows in (slice(0, -window), slice(-window, -shift), slice(-shift, None)): + for columns in (slice(0, -window), slice(-window, -shift), slice(-shift, None)): + image[rows, columns] = count + count += 1 + windows = ( + image.reshape(height // window, window, width // window, window) + .transpose(0, 2, 1, 3) + .reshape(-1, window * window) + ) + difference = windows[:, None, :] - windows[:, :, None] + return np.where(difference != 0, np.float32(_SEAM_MASK), np.float32(0.0)).astype(np.float32) + + +def _relative_bias(weights, prefix: str, window: int, heads: int) -> np.ndarray: + table = np.asarray(weights[f"{prefix}.relative_position_bias_table"], dtype=np.float32) + index = np.asarray(weights[f"{prefix}.relative_position_index"]) + expected = relative_position_index(window) + if index.shape != expected.shape or not np.array_equal(index, expected): + raise ValueError( + f"mask2former {prefix} relative_position_index does not match a {window}x{window} window" + ) + if table.shape != ((2 * window - 1) ** 2, heads): + raise ValueError( + f"mask2former {prefix} relative_position_bias_table has shape {table.shape}" + ) + tokens = window * window + return table[index.reshape(-1)].reshape(tokens, tokens, heads).transpose(2, 0, 1)[None] + + +def _window_attention(network, hidden, weights, prefix, *, heads, window, mask): + """Attention inside each window: hidden is (windows, window*window, C).""" + + windows, tokens, channels = g.shape(hidden) + head_dim = channels // heads + query = g.split_heads( + network, + g.linear( + network, hidden, weights[f"{prefix}.query.weight"], weights[f"{prefix}.query.bias"] + ), + heads, + ) + key = g.split_heads( + network, + g.linear(network, hidden, weights[f"{prefix}.key.weight"], weights[f"{prefix}.key.bias"]), + heads, + ) + value = g.split_heads( + network, + g.linear( + network, hidden, weights[f"{prefix}.value.weight"], weights[f"{prefix}.value.bias"] + ), + heads, + ) + scores = g.matmul(network, query, key, transpose_right=True) + scores = g.div(network, scores, g.scalar_like(network, math.sqrt(head_dim), 4)) + scores = g.add( + network, scores, g.constant(network, _relative_bias(weights, prefix, window, heads)) + ) + if mask is not None: + scores = g.add(network, scores, g.constant(network, mask[:, None])) + context = g.matmul(network, g.softmax(network, scores, 3), value) + return g.merge_heads(network, context) + + +def _block( + network, hidden, weights, prefix, config: Mask2FormerConfig, *, resolution, heads, shift +): + height, width = resolution + _, _, channels = g.shape(hidden) + window = config.window_size + eps = config.backbone_eps + shortcut = hidden + hidden = g.layer_norm( + network, + hidden, + weights[f"{prefix}.layernorm_before.weight"], + weights[f"{prefix}.layernorm_before.bias"], + eps, + ) + hidden = g.reshape(network, hidden, (1, height, width, channels)) + if shift: + hidden = g.roll(network, hidden, (-shift, -shift), (1, 2)) + rows, columns = height // window, width // window + windows = g.shuffle( + network, + hidden, + reshape=(rows, window, columns, window, channels), + transpose=(0, 2, 1, 3, 4), + ) + windows = g.reshape(network, windows, (rows * columns, window * window, channels)) + mask = shifted_window_mask(height, width, window, shift) if shift else None + attended = _window_attention( + network, windows, weights, f"{prefix}.attention.self", heads=heads, window=window, mask=mask + ) + attended = g.linear( + network, + attended, + weights[f"{prefix}.attention.output.dense.weight"], + weights[f"{prefix}.attention.output.dense.bias"], + ) + attended = g.shuffle( + network, + attended, + reshape=(rows, columns, window, window, channels), + transpose=(0, 2, 1, 3, 4), + ) + attended = g.reshape(network, attended, (1, height, width, channels)) + if shift: + attended = g.roll(network, attended, (shift, shift), (1, 2)) + hidden = g.add(network, shortcut, g.reshape(network, attended, (1, height * width, channels))) + + inner = g.layer_norm( + network, + hidden, + weights[f"{prefix}.layernorm_after.weight"], + weights[f"{prefix}.layernorm_after.bias"], + eps, + ) + inner = g.gelu( + network, + g.linear( + network, + inner, + weights[f"{prefix}.intermediate.dense.weight"], + weights[f"{prefix}.intermediate.dense.bias"], + ), + ) + inner = g.linear( + network, + inner, + weights[f"{prefix}.output.dense.weight"], + weights[f"{prefix}.output.dense.bias"], + ) + return g.add(network, hidden, inner) + + +def _patch_merging(network, hidden, weights, prefix, *, resolution): + height, width = resolution + _, _, channels = g.shape(hidden) + grid = g.reshape(network, hidden, (1, height, width, channels)) + half = (1, height // 2, width // 2, channels) + # x[0::2, 0::2], x[1::2, 0::2], x[0::2, 1::2], x[1::2, 1::2] along (rows, columns), in this order. + pieces = [ + g.slice_static(network, grid, (0, row, column, 0), half, (1, 2, 2, 1)) + for row, column in ((0, 0), (1, 0), (0, 1), (1, 1)) + ] + merged = g.reshape( + network, g.concat(network, pieces, 3), (1, (height // 2) * (width // 2), 4 * channels) + ) + merged = g.layer_norm( + network, merged, weights[f"{prefix}.norm.weight"], weights[f"{prefix}.norm.bias"], 1e-5 + ) + return g.linear(network, merged, weights[f"{prefix}.reduction.weight"]) + + +def build_backbone(network, pixels, weights, config: Mask2FormerConfig): + """Return the four normalized stage feature maps, each (1, C, H, W).""" + + hidden = g.conv2d( + network, + pixels, + weights[f"{_PREFIX}.embeddings.patch_embeddings.projection.weight"], + weights[f"{_PREFIX}.embeddings.patch_embeddings.projection.bias"], + stride=config.patch_size, + ) + hidden = g.tokens_from_nchw(network, hidden) + hidden = g.layer_norm( + network, + hidden, + weights[f"{_PREFIX}.embeddings.norm.weight"], + weights[f"{_PREFIX}.embeddings.norm.bias"], + 1e-5, + ) + + features = [] + for stage, (depth, heads) in enumerate(zip(config.depths, config.num_heads)): + resolution = config.stage_resolutions[stage] + for block in range(depth): + hidden = _block( + network, + hidden, + weights, + f"{_PREFIX}.encoder.layers.{stage}.blocks.{block}", + config, + resolution=resolution, + heads=heads, + shift=0 if block % 2 == 0 else config.window_size // 2, + ) + name = f"stage{stage + 1}" + normed = g.layer_norm( + network, + hidden, + weights[f"{_PREFIX}.hidden_states_norms.{name}.weight"], + weights[f"{_PREFIX}.hidden_states_norms.{name}.bias"], + 1e-5, + ) + features.append(g.nchw_from_tokens(network, normed, *resolution)) + if stage < len(config.depths) - 1: + hidden = _patch_merging( + network, + hidden, + weights, + f"{_PREFIX}.encoder.layers.{stage}.downsample", + resolution=resolution, + ) + return features diff --git a/families/mask2former/tests/__init__.py b/families/mask2former/tests/__init__.py new file mode 100644 index 0000000000..7f68158866 --- /dev/null +++ b/families/mask2former/tests/__init__.py @@ -0,0 +1,4 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +"""Tests owned by the Mask2Former family.""" diff --git a/families/mask2former/tests/cpp/image_ops_tool.cpp b/families/mask2former/tests/cpp/image_ops_tool.cpp new file mode 100644 index 0000000000..d5f45f1d0c --- /dev/null +++ b/families/mask2former/tests/cpp/image_ops_tool.cpp @@ -0,0 +1,103 @@ +/* + * SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. + * SPDX-License-Identifier: Apache-2.0 + */ + +// Runs the family's image operations on raw files so that tests/test_image_ops.py can compare them +// with Pillow, the reference image processor and torch. +// +// resize IN.u8 H W OUT_H OUT_W OUT.u8 +// preprocess IN.u8 H W OUT_H OUT_W RESCALE MEAN0 MEAN1 MEAN2 STD0 STD1 STD2 OUT.f32 +// argmax IN.f32 CLASSES SCORE_H SCORE_W H W OUT.i32 + +#include "families/mask2former/runtime/image_ops.h" + +#include +#include +#include +#include +#include +#include + +namespace { + +std::int32_t integer(const char* text) { + std::size_t consumed = 0; + const auto value = std::stol(text, &consumed); + if (text[consumed] != '\0' || value <= 0 || value > 1 << 20) + throw std::invalid_argument(std::string("invalid size: ") + text); + return static_cast(value); +} + +float number(const char* text) { + std::size_t consumed = 0; + const auto value = std::stof(text, &consumed); + if (text[consumed] != '\0') + throw std::invalid_argument(std::string("invalid number: ") + text); + return value; +} + +template +std::vector read(const char* path, std::size_t count) { + std::vector values(count); + std::ifstream file(path, std::ios::binary); + file.read(reinterpret_cast(values.data()), + static_cast(count * sizeof(T))); + if (!file || file.peek() != std::char_traits::eof()) + throw std::runtime_error(std::string("input size does not match the stated shape: ") + + path); + return values; +} + +template +void write(const char* path, const std::vector& values) { + std::ofstream file(path, std::ios::binary); + file.write(reinterpret_cast(values.data()), + static_cast(values.size() * sizeof(T))); + if (!file) + throw std::runtime_error(std::string("cannot write ") + path); +} + +} // namespace + +int main(int argc, char** argv) { + try { + const std::string mode = argc > 1 ? argv[1] : ""; + if (mode == "resize" && argc == 8) { + const auto height = integer(argv[3]), width = integer(argv[4]); + const auto input = + read(argv[2], static_cast(height) * width * 3); + write(argv[7], trtmc::mask2former::resize_bilinear_rgb8( + input.data(), height, width, integer(argv[5]), integer(argv[6]))); + return 0; + } + if (mode == "preprocess" && argc == 15) { + const auto height = integer(argv[3]), width = integer(argv[4]); + const auto input = + read(argv[2], static_cast(height) * width * 3); + trtmc::mask2former::PreprocessConfig config; + config.height = integer(argv[5]); + config.width = integer(argv[6]); + config.rescale_factor = std::stod(argv[7]); + config.mean = {number(argv[8]), number(argv[9]), number(argv[10])}; + config.std = {number(argv[11]), number(argv[12]), number(argv[13])}; + write(argv[14], trtmc::mask2former::preprocess(input.data(), height, width, config)); + return 0; + } + if (mode == "argmax" && argc == 9) { + const auto classes = integer(argv[3]); + const auto score_height = integer(argv[4]), score_width = integer(argv[5]); + const auto scores = read(argv[2], static_cast(classes) * + score_height * score_width); + write(argv[8], trtmc::mask2former::resize_argmax(scores.data(), classes, score_height, + score_width, integer(argv[6]), + integer(argv[7]))); + return 0; + } + std::cerr << "usage: see the header of image_ops_tool.cpp\n"; + return 2; + } catch (const std::exception& error) { + std::cerr << error.what() << '\n'; + return 1; + } +} diff --git a/families/mask2former/tests/cpp/test_task_contract.cpp b/families/mask2former/tests/cpp/test_task_contract.cpp new file mode 100644 index 0000000000..1e55916a1f --- /dev/null +++ b/families/mask2former/tests/cpp/test_task_contract.cpp @@ -0,0 +1,358 @@ +/* + * SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. + * SPDX-License-Identifier: Apache-2.0 + */ + +#include "families/mask2former/runtime/pipeline.h" + +#include +#include +#include +#include +#include + +namespace { + +constexpr int kSize = 4; +constexpr int kClasses = 3; + +// Scores that select class 1 on the left half and class 2 on the right half of a 4x4 map. +std::vector halves() { + std::vector scores(kClasses * kSize * kSize, 0.0F); + for (int y = 0; y < kSize; ++y) { + for (int x = 0; x < kSize; ++x) { + scores[(1 * kSize + y) * kSize + x] = x < kSize / 2 ? 2.0F : 0.5F; + scores[(2 * kSize + y) * kSize + x] = x < kSize / 2 ? 0.5F : 2.0F; + } + } + return scores; +} + +class RecordingModule final : public trtmc::ITrtModule { + public: + trtmc::TensorMap forward(const trtmc::TensorMap& inputs) override { + ++calls; + const auto& image = inputs.at("pixel_values"); + shape = image.shape; + const auto* data = static_cast(image.data); + pixels.assign(data, data + image.numel()); + return {{"semantic_scores", {scores.data(), output_shape, output_dtype}}}; + } + trtmc::DeviceTensorMap forward_device(const trtmc::DeviceTensorMap&) override { return {}; } + void forward_device_async(const trtmc::DeviceTensorMap&) override {} + void forward_async(const trtmc::TensorMap&) override {} + void sync() override {} + cudaStream_t stream() const override { return nullptr; } + void enable_cuda_graph() override {} + bool cuda_graph_active() const override { return false; } + bool cuda_graph_captured() const override { return false; } + int32_t profile_idx() const override { return 0; } + std::vector input_info() const override { return {}; } + std::vector output_info() const override { return {}; } + bool has_input(const std::string& name) const override { return name == "pixel_values"; } + bool has_output(const std::string& name) const override { return name == "semantic_scores"; } + trtmc::DType tensor_dtype(const std::string&) const override { return trtmc::DType::kFloat32; } + std::vector tensor_shape(const std::string& name) const override { + return name == "pixel_values" ? std::vector{1, 3, kSize, kSize} : engine_scores; + } + std::vector input_profile_shape(const std::string&, int32_t, + trtmc::ProfileShapeSelector) const override { + return {}; + } + int32_t optimization_profile_count() const override { return 1; } + void* device_ptr(const std::string&) const override { return nullptr; } + void bind_external(const std::string&, void*) override {} + void bind_external(const std::string&, void*, const std::vector&) override {} + int32_t input_rank(const std::string&) const override { return 4; } + bool input_is_dynamic(const std::string&) const override { return false; } + void reset_execution_context() override {} + void set_timing_label(std::string) override {} + bool ok() const override { return true; } + void keep_alive(std::shared_ptr) override {} + + int calls{0}; + std::vector scores = halves(); + std::vector engine_scores{1, kClasses, kSize, kSize}; + std::vector output_shape{1, kClasses, kSize, kSize}; + trtmc::DType output_dtype{trtmc::DType::kFloat32}; + std::vector pixels; + std::vector shape; +}; + +void require(bool value, const char* message) { + if (!value) + throw std::runtime_error(message); +} + +template +void rejects(Function function, const char* message) { + try { + function(); + } catch (const Error&) { + return; + } + throw std::runtime_error(message); +} + +trtmc::mask2former::PreprocessConfig preprocessing() { + trtmc::mask2former::PreprocessConfig config; + config.height = kSize; + config.width = kSize; + config.rescale_factor = 1.0 / 255.0; + config.mean = {0.5F, 0.25F, 0.0F}; + config.std = {0.5F, 0.25F, 1.0F}; + return config; +} + +trtmc::mask2former::SemanticHead head() { + return {kSize, kSize, {"first", "second", "third"}}; +} + +trtmc::internal::ImageToSemanticSegmentationRequest +request(const std::vector& pixels, std::uint32_t height, std::uint32_t width) { + return {{pixels.data(), pixels.size() * sizeof(float), height, width, 3, + trtmc::internal::ImageFormat::Float32}}; +} + +void test_binding_and_owned_result() { + trtmc::internal::SemanticSegmentationResult result; + { + auto module = std::make_unique(); + auto* recording = module.get(); + trtmc::mask2former::Mask2FormerSemanticSegmentation model(std::move(module), + preprocessing(), head()); + const auto bindings = model.task_bindings(); + require(bindings.size() == 1 && bindings[0].key.id == "image_to_semantic_segmentation" && + bindings[0].key.major == 1 && bindings[0].key.minor == 0, + "family must publish exactly its implemented semantic task"); + require(bindings[0].fields.empty(), "family has no runtime config options"); + require(bindings[0].implementation == + static_cast(&model), + "bind must preserve the interface subobject address"); + require(std::string(model.task()) == "image_to_semantic_segmentation", + "bundle primary task must match the binding"); + + const std::vector pixels(kSize * kSize * 3, 0.75F); + result = + static_cast(bindings[0].implementation) + ->run(request(pixels, kSize, kSize), {}); + require(recording->shape == std::vector({1, 3, kSize, kSize}), + "preprocessing must feed the engine one NCHW image"); + // 0.75 quantizes to 191; float32(191 / 255) normalized per channel. + const float rescaled = static_cast(191.0 * (1.0 / 255.0)); + const float expected[3] = {(rescaled - 0.5F) / 0.5F, (rescaled - 0.25F) / 0.25F, + (rescaled - 0.0F) / 1.0F}; + for (int channel = 0; channel < 3; ++channel) + for (int index = 0; index < kSize * kSize; ++index) + require(recording->pixels[channel * kSize * kSize + index] == expected[channel], + "preprocessing must rescale and normalize every channel plane"); + recording->scores.assign(recording->scores.size(), 0.0F); + model.run(request(pixels, kSize, kSize), {}); + } + require(result.height == kSize && result.width == kSize, "labels keep the image size"); + for (int y = 0; y < kSize; ++y) + for (int x = 0; x < kSize; ++x) + require(result.labels[y * kSize + x] == (x < kSize / 2 ? 1 : 2), + "labels must own the argmax across later calls and model destruction"); + require(result.class_ids == std::vector({0, 1, 2}) && + result.class_names == std::vector({"first", "second", "third"}), + "every class ID is named in order"); + require(result.vocabulary_id.empty() && !result.ignore_label && !result.background_label, + "no invented vocabulary, ignore or background label"); + require(result.class_scores.empty() && result.score_height == 0 && result.score_width == 0, + "the family does not publish its unnormalized score maps"); +} + +void test_original_resolution_and_uint8_input() { + auto module = std::make_unique(); + auto* recording = module.get(); + trtmc::mask2former::Mask2FormerSemanticSegmentation model(std::move(module), preprocessing(), + head()); + const std::vector pixels(2 * 8 * 3, 0.5F); + const auto result = model.run(request(pixels, 2, 8), {}); + require(result.height == 2 && result.width == 8 && result.labels.size() == 16, + "labels must come back at the original image resolution"); + for (int x = 0; x < 8; ++x) + require(result.labels[x] == (x < 4 ? 1 : 2) && result.labels[8 + x] == result.labels[x], + "the score map is resized to the original image before the argmax"); + const auto float_pixels = recording->pixels; + + const std::vector bytes(2 * 8 * 3, 128); + trtmc::internal::ImageToSemanticSegmentationRequest uint8{ + {bytes.data(), bytes.size(), 2, 8, 3, trtmc::internal::ImageFormat::UInt8}}; + const auto from_bytes = model.run(uint8, {}); + require(from_bytes.labels == result.labels && recording->pixels == float_pixels, + "0.5 quantizes to 128: float32 and 8-bit inputs must agree"); +} + +void test_scores_are_resized_before_the_argmax() { + auto module = std::make_unique(); + auto* recording = module.get(); + trtmc::mask2former::Mask2FormerSemanticSegmentation model(std::move(module), preprocessing(), + head()); + // Class 1 scores 100 in the left half and class 2 scores 1 in the right half. Resizing the + // scores from width 4 to width 8 keeps class 1 at column 4 (0.25 * 100 against 0.75 * 1); + // resizing the argmax map instead would take column 2's class 2 there. + recording->scores.assign(recording->scores.size(), 0.0F); + for (int y = 0; y < kSize; ++y) { + for (int x = 0; x < kSize; ++x) { + recording->scores[(1 * kSize + y) * kSize + x] = x < kSize / 2 ? 100.0F : 0.0F; + recording->scores[(2 * kSize + y) * kSize + x] = x < kSize / 2 ? 0.0F : 1.0F; + } + } + const std::vector pixels(2 * 8 * 3, 0.5F); + const auto result = model.run(request(pixels, 2, 8), {}); + const std::vector row{1, 1, 1, 1, 1, 2, 2, 2}; + require(result.labels.size() == 16, "labels come back at the image resolution"); + for (int y = 0; y < 2; ++y) + require(std::vector(result.labels.begin() + y * 8, + result.labels.begin() + (y + 1) * 8) == row, + "the scores are resized to the image before the argmax"); +} + +void test_invalid_inputs_and_outputs() { + auto module = std::make_unique(); + auto* recording = module.get(); + trtmc::mask2former::Mask2FormerSemanticSegmentation model(std::move(module), preprocessing(), + head()); + std::vector pixels(kSize * kSize * 3, 0.25F); + const auto input = request(pixels, kSize, kSize); + const trtmc::internal::ConfigEntry unsupported{"threshold", 0.5}; + rejects([&] { model.run(input, {&unsupported, 1}); }, + "unsupported config must fail"); + auto invalid = input; + invalid.image.byte_size -= sizeof(float); + rejects([&] { model.run(invalid, {}); }, "reject truncated image"); + invalid = input; + invalid.image.channels = 4; + rejects([&] { model.run(invalid, {}); }, "reject non-RGB image"); + invalid = input; + invalid.image.width = 0; + rejects([&] { model.run(invalid, {}); }, "reject empty image"); + pixels[5] = 1.5F; + rejects([&] { model.run(input, {}); }, "reject values above one"); + pixels[5] = std::nanf(""); + rejects([&] { model.run(input, {}); }, "reject NaN pixels"); + pixels[5] = 0.25F; + require(recording->calls == 0, "invalid input and config must fail before engine execution"); + + recording->output_shape = {1, kClasses, kSize, kSize - 1}; + rejects([&] { model.run(input, {}); }, "reject incomplete scores"); + recording->output_shape = {1, kClasses, kSize, kSize}; + recording->output_dtype = trtmc::DType::kFloat16; + rejects([&] { model.run(input, {}); }, "reject wrong output dtype"); + recording->output_dtype = trtmc::DType::kFloat32; + recording->scores[0] = std::numeric_limits::infinity(); + rejects([&] { model.run(input, {}); }, "reject nonfinite scores"); + // A 1x1 image reads only score rows and columns 1 and 2; the score at (0, 0) must still count. + const std::vector one_pixel(3, 0.25F); + recording->scores[0] = std::nanf(""); + rejects([&] { model.run(request(one_pixel, 1, 1), {}); }, + "reject nonfinite scores that the resize does not sample"); + recording->scores[0] = 0.0F; + require(model.run(request(one_pixel, 1, 1), {}).labels.size() == 1, + "the same request with finite scores succeeds"); +} + +void test_engine_must_match_runtime_metadata() { + auto module = std::make_unique(); + module->engine_scores = {1, kClasses + 1, kSize, kSize}; + rejects( + [&] { + trtmc::mask2former::Mask2FormerSemanticSegmentation model(std::move(module), + preprocessing(), head()); + }, + "an engine with another class count must be rejected at load"); + auto zero_std = preprocessing(); + zero_std.std[1] = 0.0F; + rejects( + [&] { + trtmc::mask2former::Mask2FormerSemanticSegmentation model( + std::make_unique(), zero_std, head()); + }, + "zero image_std must be rejected at load"); +} + +void test_normalization_must_stay_finite() { + // Finite and nonzero, but 1 / 1e-40 overflows float32. + auto tiny_std = preprocessing(); + tiny_std.std[2] = 1e-40F; + // 255 * 1e300 does not fit float. + auto huge_rescale = preprocessing(); + huge_rescale.rescale_factor = 1e300; + // An infinite std turns every value into a finite zero. + auto infinite_std = preprocessing(); + infinite_std.std[0] = std::numeric_limits::infinity(); + const std::vector pixel(3, 255); + for (const auto& config : {tiny_std, huge_rescale, infinite_std}) { + auto module = std::make_unique(); + rejects( + [&] { + trtmc::mask2former::Mask2FormerSemanticSegmentation model(std::move(module), config, + head()); + }, + "a normalization that overflows float32 must be rejected at load"); + rejects( + [&] { trtmc::mask2former::preprocess(pixel.data(), 1, 1, config); }, + "preprocessing must refuse a normalization that overflows float32"); + } +} + +std::vector characters(const std::string& text) { + return {text.begin(), text.end()}; +} + +void test_runtime_json_is_read_strictly() { + const std::string valid = + R"({"input_height": 4, "input_width": 4, "score_height": 4, "score_width": 4, )" + R"("num_classes": 3, "rescale_factor": 0.00392156862745098, "image_mean": [0.5, 0.25, 0.0], )" + R"("image_std": [0.5, 0.25, 1.0], "labels": ["first", "second", "third"]})"; + const auto metadata = trtmc::mask2former::parse_runtime_json(characters(valid)); + require(metadata.preprocess.height == 4 && metadata.preprocess.width == 4 && + metadata.preprocess.rescale_factor == 0.00392156862745098 && + metadata.preprocess.mean[1] == 0.25F && metadata.preprocess.std[2] == 1.0F && + metadata.head.score_height == 4 && metadata.head.score_width == 4 && + metadata.head.labels == std::vector({"first", "second", "third"}), + "a valid runtime.json is read in full"); + const std::pair invalid[] = { + {R"("input_height": 4)", R"("input_height": 4.5)"}, + // 2^32 + 4 wraps to 4 as int32. + {R"("input_height": 4)", R"("input_height": 4294967300)"}, + {R"("input_width": 4)", R"("input_width": -4)"}, + {R"("score_width": 4)", R"("score_width": null)"}, + {R"("num_classes": 3)", R"("num_classes": 3.0)"}, + {R"("num_classes": 3)", R"("num_classes": 4)"}, + {R"("input_height": 4)", R"("input_height": 4, "input_height": 8)"}, + {R"("image_std": [0.5, 0.25, 1.0])", R"("image_std": [0.5, 0.25, 1e300])"}, + {R"("image_mean": [0.5, 0.25, 0.0])", R"("image_mean": [0.5, 0.25])"}, + {R"("rescale_factor": 0.00392156862745098)", R"("rescale_factor": "0.0039")"}, + {R"("third"])", R"(3])"}, + }; + for (const auto& change : invalid) { + auto text = valid; + const auto position = text.find(change.first); + require(position != std::string::npos, "every invalid runtime.json changes the valid one"); + text.replace(position, change.first.size(), change.second); + rejects( + [&] { trtmc::mask2former::parse_runtime_json(characters(text)); }, + change.second.c_str()); + } +} + +} // namespace + +int main() { + try { + test_binding_and_owned_result(); + test_original_resolution_and_uint8_input(); + test_scores_are_resized_before_the_argmax(); + test_invalid_inputs_and_outputs(); + test_engine_must_match_runtime_metadata(); + test_normalization_must_stay_finite(); + test_runtime_json_is_read_strictly(); + return 0; + } catch (const std::exception& error) { + std::cerr << error.what() << '\n'; + return 1; + } +} diff --git a/families/mask2former/tests/data/test_img.png b/families/mask2former/tests/data/test_img.png new file mode 100644 index 0000000000..517bec879b Binary files /dev/null and b/families/mask2former/tests/data/test_img.png differ diff --git a/families/mask2former/tests/manifests/mask2former-swin-large-ade-semantic.json b/families/mask2former/tests/manifests/mask2former-swin-large-ade-semantic.json new file mode 100644 index 0000000000..83f8b1424e --- /dev/null +++ b/families/mask2former/tests/manifests/mask2former-swin-large-ade-semantic.json @@ -0,0 +1,17 @@ +{ + "name": "mask2former-swin-large-ade-semantic", + "hf_id": "facebook/mask2former-swin-large-ade-semantic", + "hf_revision": "aa25c92404a40599614215e76514c79b427c7527", + "bundle": "mask2former-swin-large-ade-semantic.bundle", + "family": "mask2former", + "task": "image_to_semantic_segmentation", + "precision": "fp32", + "testcases": [ + { + "name": "mask2former-swin-large-ade-semantic", + "premerge": true, + "test_image": "data/test_img.png" + } + ], + "tensor_parallel_size": 1 +} diff --git a/families/mask2former/tests/sdk_consumer.c b/families/mask2former/tests/sdk_consumer.c new file mode 100644 index 0000000000..a6db730d2e --- /dev/null +++ b/families/mask2former/tests/sdk_consumer.c @@ -0,0 +1,168 @@ +/* + * SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. + * SPDX-License-Identifier: Apache-2.0 + */ + +/* Public C SDK consumer for the family-owned end-to-end test: semantic segmentation of one float32 + * RGB image. Writes the int32 label map to OUT_LABELS and one JSON summary line to stdout. */ +#include +#include +#include +#include +#include +#include +#include + +_Static_assert(sizeof(float) == 4, "input uses float32"); + +static trtmc_string_view text(const char* value) { + const trtmc_string_view result = {value, (uint64_t)strlen(value)}; + return result; +} +static uint32_t dimension(const char* text_value) { + char* end = NULL; + uintmax_t value; + errno = 0; + value = strtoumax(text_value, &end, 10); + if (errno || end == text_value || *end || !value || value > INT32_MAX) + return 0; + return (uint32_t)value; +} +static void json_string(trtmc_string_view value) { + uint64_t i; + putchar('"'); + for (i = 0; i < value.size; ++i) { + const unsigned char byte = (unsigned char)value.data[i]; + if (byte == '"' || byte == '\\') { + putchar('\\'); + putchar(byte); + } else if (byte < 32) { + printf("\\u%04x", (unsigned)byte); + } else { + putchar(byte); + } + } + putchar('"'); +} + +int main(int argc, char** argv) { + const trtmc_core_api_v1* core = NULL; + const trtmc_api_header* header = NULL; + const trtmc_image_to_semantic_segmentation_api_v1* task = NULL; + trtmc_model* model = NULL; + trtmc_result* result = NULL; + trtmc_error* error = NULL; + trtmc_load_options_v1 options = {0}; + trtmc_perception_image_request_v1 request = {0}; + trtmc_semantic_segmentation_view_v1 view = {0}; + float* input = NULL; + FILE* file = NULL; + uint32_t height, width; + size_t count; + uint64_t i, field_count = 0; + int status = 1; + if (argc != 7) { + fprintf(stderr, "Usage: %s BUNDLE RUNTIME_ROOT RGB_F32 HEIGHT WIDTH OUT_LABELS\n", argv[0]); + return 2; + } + height = dimension(argv[4]); + width = dimension(argv[5]); + if (!height || !width || (size_t)height > SIZE_MAX / width / 3 / sizeof(float)) { + fprintf(stderr, "invalid or overflowing image dimensions\n"); + return 2; + } + count = (size_t)height * width * 3; + input = (float*)malloc(count * sizeof(float)); + file = fopen(argv[3], "rb"); + if (!input || !file || fread(input, sizeof(float), count, file) != count || + fgetc(file) != EOF || ferror(file)) { + fprintf(stderr, "input must contain exactly HEIGHT x WIDTH x 3 float32 RGB values\n"); + goto cleanup; + } + fclose(file); + file = NULL; + if (trtmc_get_api(1, 0, &core) != TRTMC_OK || !core) { + fprintf(stderr, "unable to obtain the v1 C API\n"); + goto cleanup; + } + options.struct_size = sizeof(options); + options.runtime_root = text(argv[2]); + if (core->model_load(text(argv[1]), &options, &model, &error) != TRTMC_OK) + goto cleanup; + if (core->model_get_task_api(model, text(TRTMC_TASK_IMAGE_TO_SEMANTIC_SEGMENTATION), 1, 0, + &header, &error) != TRTMC_OK) + goto cleanup; + if (!header || header->byte_size < sizeof(*task)) { + fprintf(stderr, "incomplete semantic segmentation C table\n"); + goto cleanup; + } + task = (const trtmc_image_to_semantic_segmentation_api_v1*)header; + if (core->config_field_count(model, text(TRTMC_TASK_IMAGE_TO_SEMANTIC_SEGMENTATION), 1, 0, + &field_count, &error) != TRTMC_OK) + goto cleanup; + if (field_count != 0) { + fprintf(stderr, "Mask2Former must expose no runtime Config fields\n"); + goto cleanup; + } + request.image = + (trtmc_image_input_v1){input, count * sizeof(float), height, width, 3, TRTMC_IMAGE_FLOAT32}; + if (task->run(model, &request, NULL, &result, &error) != TRTMC_OK) + goto cleanup; + free(input); + input = NULL; + core->model_release(model); + model = NULL; + if (task->result_view(result, &view, &error) != TRTMC_OK) + goto cleanup; + if (view.height != height || view.width != width || + view.pixel_count != (uint64_t)height * width || !view.class_ids.size) { + fprintf(stderr, "semantic segmentation must label every pixel of the input\n"); + goto cleanup; + } + file = fopen(argv[6], "wb"); + if (!file || + fwrite(view.labels, sizeof(int32_t), (size_t)view.pixel_count, file) != + (size_t)view.pixel_count || + fclose(file) != 0) { + file = NULL; + fprintf(stderr, "unable to write the label map\n"); + goto cleanup; + } + file = NULL; + printf("{\"task\":\"image_to_semantic_segmentation\",\"height\":%" PRIu32 ",\"width\":%" PRIu32 + ",\"pixel_count\":%" PRIu64 ",\"class_ids\":[", + view.height, view.width, view.pixel_count); + for (i = 0; i < view.class_ids.size; ++i) { + if (i) + putchar(','); + printf("%" PRId32, view.class_ids.data[i]); + } + printf("],\"class_names\":["); + for (i = 0; i < view.class_names.size; ++i) { + if (i) + putchar(','); + json_string(view.class_names.data[i]); + } + printf("],\"vocabulary_id\":"); + json_string(view.vocabulary_id); + printf(",\"has_ignore_label\":%" PRIu32 ",\"has_background_label\":%" PRIu32 + ",\"score_count\":%" PRIu64 "}\n", + view.has_ignore_label, view.has_background_label, view.score_count); + status = fflush(stdout) == 0 && !ferror(stdout) ? 0 : 1; +cleanup: + if (error && core) { + const trtmc_string_view message = core->error_message(error); + fprintf(stderr, "C API error %d: ", (int)core->error_code(error)); + fwrite(message.data, 1, (size_t)message.size, stderr); + fputc('\n', stderr); + core->error_release(error); + } + if (core) { + core->result_release(result); + core->model_release(model); + } + if (file) + fclose(file); + free(input); + return status; +} diff --git a/families/mask2former/tests/sdk_consumer.cpp b/families/mask2former/tests/sdk_consumer.cpp new file mode 100644 index 0000000000..8019ad748d --- /dev/null +++ b/families/mask2former/tests/sdk_consumer.cpp @@ -0,0 +1,108 @@ +/* + * SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. + * SPDX-License-Identifier: Apache-2.0 + */ + +/* Public C++ SDK consumer for the family-owned end-to-end test: semantic segmentation of one + * float32 RGB image. Writes the int32 label map to OUT_LABELS and one JSON summary line to stdout. + */ +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace { +std::uint32_t dimension(const char* argument) { + const std::string text(argument); + std::size_t consumed = 0; + const auto value = std::stoull(text, &consumed); + if (consumed != text.size() || !value || value > std::numeric_limits::max()) + throw std::invalid_argument("image dimensions must be positive int32 values"); + return static_cast(value); +} +void json_string(std::string_view value) { + std::cout << '"'; + for (const unsigned char byte : value) { + if (byte == '"' || byte == '\\') + std::cout << '\\' << static_cast(byte); + else if (byte < 32) + std::cout << "\\u" << std::hex << std::setw(4) << std::setfill('0') + << static_cast(byte) << std::dec << std::setfill(' '); + else + std::cout << static_cast(byte); + } + std::cout << '"'; +} +} // namespace + +int main(int argc, char** argv) { + if (argc != 7) { + std::cerr << "Usage: " << argv[0] + << " BUNDLE RUNTIME_ROOT RGB_F32 HEIGHT WIDTH OUT_LABELS\n"; + return 2; + } + try { + static_assert(sizeof(float) == 4, "input uses float32"); + const auto height = dimension(argv[4]), width = dimension(argv[5]); + const auto limit = static_cast(std::numeric_limits::max()); + if (height > limit / width / 3 / sizeof(float)) + throw std::invalid_argument("image byte count overflows input storage"); + const auto count = static_cast(height) * width * 3; + std::vector input(count); + std::ifstream file(argv[3], std::ios::binary); + file.read(reinterpret_cast(input.data()), + static_cast(count * sizeof(float))); + if (!file || file.peek() != std::char_traits::eof()) + throw std::runtime_error( + "input must contain exactly HEIGHT x WIDTH x 3 RGB float32 values"); + auto result = [&] { + trtmc::LoadOptions options; + options.runtime_root = argv[2]; + auto model = trtmc::Model::load(argv[1], options); + const auto task = model.task(); + if (!task.config_fields().empty()) + throw std::runtime_error("Mask2Former must expose no runtime Config fields"); + return task.run({trtmc::ImageInput({input.data(), input.size()}, height, width)}); + }(); + input.clear(); + input.shrink_to_fit(); + const auto view = result.view(); + if (view.height != height || view.width != width || + view.pixel_count != static_cast(height) * width || !view.class_ids.size) + throw std::runtime_error("semantic segmentation must label every pixel of the input"); + std::ofstream labels(argv[6], std::ios::binary); + labels.write(reinterpret_cast(view.labels), + static_cast(view.pixel_count * sizeof(std::int32_t))); + labels.close(); + if (!labels) + throw std::runtime_error("unable to write the label map"); + std::cout << "{\"task\":\"image_to_semantic_segmentation\",\"height\":" << view.height + << ",\"width\":" << view.width << ",\"pixel_count\":" << view.pixel_count + << ",\"class_ids\":["; + for (std::uint64_t i = 0; i < view.class_ids.size; ++i) + std::cout << (i ? "," : "") << view.class_ids.data[i]; + std::cout << "],\"class_names\":["; + for (std::uint64_t i = 0; i < view.class_names.size; ++i) { + if (i) + std::cout << ','; + json_string(trtmc::detail::string_view(view.class_names.data[i])); + } + std::cout << "],\"vocabulary_id\":"; + json_string(trtmc::detail::string_view(view.vocabulary_id)); + std::cout << ",\"has_ignore_label\":" << view.has_ignore_label + << ",\"has_background_label\":" << view.has_background_label + << ",\"score_count\":" << view.score_count << "}\n"; + std::cout.flush(); + if (!std::cout) + throw std::runtime_error("failed to write the segmentation summary"); + return 0; + } catch (const std::exception& error) { + std::cerr << error.what() << '\n'; + return 1; + } +} diff --git a/families/mask2former/tests/test_config.py b/families/mask2former/tests/test_config.py new file mode 100644 index 0000000000..9bcef102a9 --- /dev/null +++ b/families/mask2former/tests/test_config.py @@ -0,0 +1,165 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +"""Checkpoint configuration: malformed or unsupported values are rejected before any engine is built.""" + +from __future__ import annotations + +import copy +import json +from pathlib import Path + +import pytest + +from families.mask2former import config as config_module + +# The released facebook/mask2former-swin-large-ade-semantic structure, with three of its 150 classes. +_CONFIG = { + "model_type": "mask2former", + "architectures": ["Mask2FormerForUniversalSegmentation"], + "backbone_config": { + "model_type": "swin", + "depths": [2, 2, 18, 2], + "num_heads": [6, 12, 24, 48], + "embed_dim": 192, + "patch_size": 4, + "window_size": 12, + "mlp_ratio": 4.0, + "layer_norm_eps": 1e-05, + "out_features": ["stage1", "stage2", "stage3", "stage4"], + "hidden_act": "gelu", + "qkv_bias": True, + "use_absolute_embeddings": False, + "num_channels": 3, + }, + "pre_norm": False, + "activation_function": "relu", + "enforce_input_projection": False, + "feature_size": 256, + "hidden_dim": 256, + "mask_feature_size": 256, + "num_attention_heads": 8, + "feature_strides": [4, 8, 16, 32], + "common_stride": 4, + "encoder_layers": 6, + "encoder_feedforward_dim": 1024, + "decoder_layers": 10, + "dim_feedforward": 2048, + "num_queries": 100, + "use_timm_backbone": None, + "backbone": None, + "id2label": {"0": "wall", "1": "building", "2": "sky"}, +} +_PROCESSOR = { + "do_normalize": True, + "do_rescale": True, + "do_resize": True, + "image_mean": [0.48500001430511475, 0.4560000002384186, 0.4059999883174896], + "image_std": [0.2290000021457672, 0.2239999920129776, 0.22499999403953552], + "resample": 2, + "rescale_factor": 0.00392156862745098, + "size": {"height": 384, "width": 384}, + "size_divisor": 32, +} + + +def _load(directory: Path, config: dict | str = _CONFIG, processor: dict | str = _PROCESSOR): + for name, value in (("config.json", config), ("preprocessor_config.json", processor)): + text = value if isinstance(value, str) else json.dumps(value) + (directory / name).write_text(text, encoding="utf-8") + return config_module.load(directory) + + +def _with(base: dict, path: tuple[str, ...], value) -> dict: + result = copy.deepcopy(base) + target = result + for key in path[:-1]: + target = target[key] + target[path[-1]] = value + return result + + +def test_the_released_configuration_loads(tmp_path: Path) -> None: + loaded = _load(tmp_path) + assert loaded.labels == ("wall", "building", "sky") + assert (loaded.image_height, loaded.image_width) == (384, 384) + assert (loaded.backbone_eps, loaded.mlp_ratio, loaded.num_queries) == (1e-05, 4.0, 100) + + +def test_repeated_json_keys_are_rejected(tmp_path: Path) -> None: + config = json.dumps(_CONFIG).replace( + '"num_queries": 100', '"num_queries": 100, "num_queries": 50' + ) + with pytest.raises(ValueError, match="config.json .*repeats the key 'num_queries'"): + _load(tmp_path, config=config) + processor = json.dumps(_PROCESSOR).replace( + '"rescale_factor": ', '"rescale_factor": 1.0, "rescale_factor": ' + ) + with pytest.raises( + ValueError, match="preprocessor_config.json .*repeats the key 'rescale_factor'" + ): + _load(tmp_path, processor=processor) + + +@pytest.mark.parametrize("key", ["00", "+1", " 1", "1_0"]) +def test_class_indices_must_be_canonical(tmp_path: Path, key: str) -> None: + # int() reads each of these keys as an index another key already holds, or as a gap. + config = _with(_CONFIG, ("id2label",), {"0": "wall", "1": "building", key: "sky"}) + with pytest.raises(ValueError, match="canonical class indices"): + _load(tmp_path, config=config) + + +@pytest.mark.parametrize( + "value", ["1e-05", True, -1e-05, 0.0, float("nan"), float("inf"), 1e-50, None] +) +def test_the_backbone_norm_epsilon_must_be_a_positive_float32(tmp_path: Path, value) -> None: + config = _with(_CONFIG, ("backbone_config", "layer_norm_eps"), value) + with pytest.raises(ValueError, match="layer_norm_eps"): + _load(tmp_path, config=config) + + +@pytest.mark.parametrize( + "value", [True, -4.0, float("nan"), "4.0", None, pytest.param(10**400, id="huge-integer")] +) +def test_the_mlp_ratio_must_be_a_positive_number(tmp_path: Path, value) -> None: + config = _with(_CONFIG, ("backbone_config", "mlp_ratio"), value) + with pytest.raises(ValueError, match="mlp_ratio must be a positive number"): + _load(tmp_path, config=config) + + +@pytest.mark.parametrize( + ("section", "path", "value"), + [ + ("processor", ("resample",), 2.0), + ("processor", ("resample",), None), + ("processor", ("size_divisor",), True), + ("config", ("backbone_config", "num_channels"), 3.0), + ], +) +def test_integer_fields_accept_only_json_integers( + tmp_path: Path, section: str, path, value +) -> None: + if section == "config": + arguments = {"config": _with(_CONFIG, path, value)} + else: + arguments = {"processor": _with(_PROCESSOR, path, value)} + with pytest.raises(ValueError, match="must be an integer"): + _load(tmp_path, **arguments) + + +@pytest.mark.parametrize( + ("field", "value"), + [ + # Finite and nonzero, but 1 / 1e-40 overflows float32. + ("image_std", [0.2290000021457672, 0.2239999920129776, 1e-40]), + # Finite as float64, infinite as the float32 the runtime stores. + ("image_mean", [1e39, 0.4560000002384186, 0.4059999883174896]), + # Infinite as float32, where it would turn every value into a finite zero. + ("image_std", [1e39, 0.2239999920129776, 0.22499999403953552]), + # 255 * 1e300 does not fit float32. + ("rescale_factor", 1e300), + ], +) +def test_normalization_must_stay_finite_in_float32(tmp_path: Path, field: str, value) -> None: + with pytest.raises(ValueError, match="float32"): + _load(tmp_path, processor=_with(_PROCESSOR, (field,), value)) diff --git a/families/mask2former/tests/test_e2e.py b/families/mask2former/tests/test_e2e.py new file mode 100644 index 0000000000..344cc54dda --- /dev/null +++ b/families/mask2former/tests/test_e2e.py @@ -0,0 +1,506 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +"""Direct build, native CLI and SDK runs, and the official Transformers reference for Mask2Former. + +The reference is `Mask2FormerImageProcessor` (the checkpoint's own processor, PIL resize) and +`Mask2FormerForUniversalSegmentation` in float32 on the GPU with TF32 disabled, post-processed by +`post_process_semantic_segmentation` at the original image size. The test image is lossless, so the CLI's image +loader, the C and C++ SDK consumers and the reference all see the same 8-bit pixels; every label map is held to the +same agreement with the reference. +""" + +from __future__ import annotations + +import json +import os +import shlex +import subprocess +from pathlib import Path + +import numpy as np +import pytest + +from tensorrt_model_connect import BuildRequest, build +from tools.e2e_evidence import evidence_stage, record_evidence + +FAMILY = "mask2former" +TASK = "image_to_semantic_segmentation" +TEST_ROOT = Path(__file__).resolve().parent +MANIFEST_ROOT = TEST_ROOT / "manifests" +THRESHOLD_ROOT = TEST_ROOT / "thresholds" + + +def _cases() -> dict[str, tuple[dict, dict]]: + result = {} + for path in sorted(MANIFEST_ROOT.glob("*.json")): + manifest = json.loads(path.read_text(encoding="utf-8")) + assert manifest["family"] == FAMILY + assert manifest["task"] == TASK + for case in manifest["testcases"]: + name = str(case["name"]) + assert name not in result + result[name] = (manifest, case) + assert result + return result + + +CASES = _cases() + + +def _values(raw_values) -> set[str]: + return { + value.strip() for raw in raw_values or [] for value in str(raw).split(",") if value.strip() + } + + +def _selected_cases(config) -> list[str] | None: + """Return the selected cases, or None when no E2E selector is given. + + A case is selected when it matches the model filters (`--e2e-model`, `--e2e-models-file`: the family, a manifest + or a case name) and the testcase filters (`--e2e-testcase`); a missing kind of filter matches every case. A + selection that names this family, one of its manifests or one of its cases but matches no case is a usage error, + so that a misspelt name cannot pass without testing anything; a selection of other families selects nothing here. + """ + + models = _values(config.getoption("--e2e-model", default=[])) + models_file = config.getoption("--e2e-models-file", default=None) + if models_file: + models.update( + line.strip() + for line in Path(models_file).read_text(encoding="utf-8").splitlines() + if line.strip() and not line.lstrip().startswith("#") + ) + testcases = _values(config.getoption("--e2e-testcase", default=[])) + if not models and not testcases: + return None + selected = [ + name + for name, (manifest, _) in CASES.items() + if (not models or models & {FAMILY, name, manifest["name"]}) + and (not testcases or name in testcases) + ] + own_names = {FAMILY, *CASES, *(manifest["name"] for manifest, _ in CASES.values())} + if not selected and (models | testcases) & own_names: + raise pytest.UsageError( + f"the E2E selection names {FAMILY} but matches none of its testcases " + f"(models: {sorted(models)}, testcases: {sorted(testcases)}; available: {sorted(CASES)})" + ) + return selected + + +def pytest_generate_tests(metafunc) -> None: + if "case_name" not in metafunc.fixturenames: + return + selected = _selected_cases(metafunc.config) + if selected is None: + selected = [ + pytest.param( + name, + marks=pytest.mark.skip( + reason="the real Mask2Former E2E requires explicit selection" + ), + id=name, + ) + for name in CASES + ] + metafunc.parametrize("case_name", selected) + + +def _required_path(value: str | None, label: str) -> Path: + assert value, f"selected Mask2Former E2E requires {label}" + path = Path(value) + assert path.exists(), f"selected Mask2Former E2E {label} does not exist: {path}" + return path + + +def _model_dir(manifest: dict) -> 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 _asset(case: dict) -> Path: + path = TEST_ROOT / str(case["test_image"]) + assert path.is_file(), f"selected Mask2Former E2E image is missing: {path}" + record_evidence("inputs", {"image": path}) + return path + + +def _thresholds(case_name: str) -> dict: + path = THRESHOLD_ROOT / f"{case_name}.json" + assert path.is_file(), f"selected Mask2Former E2E requires its thresholds: {path}" + return json.loads(path.read_text(encoding="utf-8"))["threshold_overrides"] + + +def _labels(model_dir: Path) -> list[str]: + id2label = json.loads((model_dir / "config.json").read_text(encoding="utf-8"))["id2label"] + return [id2label[str(index)] for index in range(len(id2label))] + + +def _reference(model_dir: Path, image) -> np.ndarray: + import torch + from transformers import Mask2FormerForUniversalSegmentation, Mask2FormerImageProcessor + + torch.backends.cuda.matmul.allow_tf32 = False + torch.backends.cudnn.allow_tf32 = False + assert torch.get_float32_matmul_precision() == "highest" + processor = Mask2FormerImageProcessor.from_pretrained(model_dir) + model = ( + Mask2FormerForUniversalSegmentation.from_pretrained(model_dir, dtype=torch.float32) + .to("cuda") + .eval() + ) + inputs = processor(images=image, return_tensors="pt") + with torch.no_grad(): + outputs = model(pixel_values=inputs["pixel_values"].to("cuda")) + labels = processor.post_process_semantic_segmentation( + outputs, target_sizes=[(image.height, image.width)] + )[0] + return labels.cpu().numpy().astype(np.int32) + + +def _agreement(actual: np.ndarray, expected: np.ndarray) -> dict: + """Pixel accuracy and the mean IoU over every class either map uses.""" + + assert actual.shape == expected.shape and actual.ndim == 2 + ious = [] + for label in np.union1d(actual, expected): + left, right = actual == label, expected == label + ious.append(np.logical_and(left, right).sum() / np.logical_or(left, right).sum()) + return {"pixel_accuracy": float(np.mean(actual == expected)), "mIoU": float(np.mean(ious))} + + +_CHECK_LABELS = {"pixel_accuracy": "Pixel accuracy", "mIoU": "Mean IoU"} +_PATH_LABELS = {"cli": "CLI", "sdk": "C and C++ SDK"} + + +def _comparison( + label: str, native: Path, reference: Path, measured: dict, thresholds: dict +) -> dict: + """One `reference_comparison` record: both label maps and every bound the test asserts.""" + + checks = [] + for name, text in _CHECK_LABELS.items(): + actual, expected = float(measured[name]), float(thresholds[name]) + checks.append( + { + "name": name, + "label": text, + "scope": "independent_reference", + "actual": actual, + "operator": ">=", + "expected": expected, + "passed": bool(actual >= expected), + } + ) + return { + "label": label, + "scope": "independent_reference", + "enforced": True, + "native": native, + "reference": reference, + "checks": checks, + } + + +def _assert_agreement(measured: dict, thresholds: dict) -> None: + # Calibrated on the test image (382 x 640 = 244,480 pixels): every healthy run of the CLI and of the C and C++ + # SDKs (2 E2E runs) agreed with the reference on every pixel (1.0 / 1.0); the reference map holds 7 classes, and + # 17 of the 384 x 384 score pixels have a top-2 margin below 1e-3 against an engine deviation of at most 7.8e-6. + # A defective input path (the JPEG of this image decoded by another decoder, up to 3 levels off in 4.7 % of the + # values) gave pixel accuracy 0.9986 and mIoU 0.859; both bounds reject it. + assert measured["pixel_accuracy"] >= float(thresholds["pixel_accuracy"]), measured + assert measured["mIoU"] >= float(thresholds["mIoU"]), measured + + +def _view(image, mask: np.ndarray, names: list[str], path: Path) -> dict: + """Blend one fixed color per class over the image and count the pixels of every class present.""" + + from PIL import Image + + palette = np.random.default_rng(0).integers(0, 256, size=(len(names), 3), dtype=np.uint8) + colors = Image.fromarray(palette[mask]) + Image.blend(image, colors, alpha=0.5).save(path) + classes, counts = np.unique(mask, return_counts=True) + order = np.argsort(-counts, kind="stable") + return { + "image": path, + "class_pixels": {names[int(classes[index])]: int(counts[index]) for index in order}, + } + + +def _compare( + image, native: dict, expected: np.ndarray, labels: list[str], thresholds: dict, tmp_path: Path +) -> None: + """Record every label map, its overlay and its comparison with the reference, then assert the bounds. + + `native` maps a path name (CLI, SDK) to its label map. The comparisons are recorded before the assertions, so a + failing case keeps its measured values. + """ + + maps = {**{f"native-{name}": mask for name, mask in native.items()}, "reference": expected} + for name, mask in maps.items(): + assert mask.shape == (image.height, image.width), name + assert mask.min() >= 0 and mask.max() < len(labels), name + np.save(tmp_path / f"{name}.labels.npy", mask, allow_pickle=False) + record_evidence( + "native", + { + name: _view(image, mask, labels, tmp_path / f"native-{name}.png") + for name, mask in native.items() + }, + ) + record_evidence("reference", _view(image, expected, labels, tmp_path / "reference.png")) + measured = {name: _agreement(mask, expected) for name, mask in native.items()} + for name in native: + record_evidence( + "reference_comparison", + _comparison( + f"{_PATH_LABELS[name]} label map vs Transformers", + tmp_path / f"native-{name}.labels.npy", + tmp_path / "reference.labels.npy", + measured[name], + thresholds, + ), + ) + for name in native: + _assert_agreement(measured[name], thresholds) + + +def _native( + binary: Path, runtime_root: Path, bundle: Path, image: Path, labels: list[str] +) -> np.ndarray: + completed = subprocess.run( + [ + str(binary), + "segment", + str(bundle), + "--runtime-root", + str(runtime_root), + "--image", + str(image), + ], + check=True, + capture_output=True, + text=True, + timeout=900, + ) + record_evidence( + "native_process", {"command": shlex.join(completed.args), "stderr": completed.stderr} + ) + payload = json.loads(completed.stdout) + height, width = int(payload["height"]), int(payload["width"]) + assert payload["class_ids"] == list(range(len(labels))) + assert payload["class_names"] == labels + assert payload["vocabulary_id"] == "" + assert payload["ignore_label"] is None and payload["background_label"] is None + assert ( + payload["class_scores"] == [] + and payload["score_height"] == 0 + and payload["score_width"] == 0 + ) + mask = np.asarray(payload["mask"], dtype=np.int32) + assert mask.size == height * width + return mask.reshape(height, width) + + +def _sdk_masks( + runtime_root: Path, bundle: Path, pixels: np.ndarray, labels: list[str], tmp_path: Path +) -> list: + native_build = _required_path( + os.environ.get("TRTMC_NATIVE_BUILD_DIR"), "TRTMC_NATIVE_BUILD_DIR" + ) + raw_image = tmp_path / "sdk-input.rgb.f32" + (pixels.astype(np.float32) / np.float32(255.0)).tofile(raw_image) + env = os.environ.copy() + env["LD_LIBRARY_PATH"] = ":".join( + value for value in (str(runtime_root), env.get("LD_LIBRARY_PATH", "")) if value + ) + masks = [] + for language in ("c", "cpp"): + consumer = native_build / f"test_mask2former_sdk_{language}" + assert consumer.is_file(), f"build the family-owned SDK consumer: {consumer.name}" + output = tmp_path / f"sdk-{language}.labels.i32" + completed = subprocess.run( + [ + str(consumer), + str(bundle), + str(runtime_root), + str(raw_image), + *map(str, pixels.shape[:2]), + str(output), + ], + check=True, + capture_output=True, + text=True, + env=env, + timeout=900, + ) + summary = json.loads(completed.stdout) + record_evidence(f"sdk_{language}", summary) + assert summary["task"] == TASK + assert (summary["height"], summary["width"]) == pixels.shape[:2] + assert summary["pixel_count"] == pixels.shape[0] * pixels.shape[1] + assert summary["class_ids"] == list(range(len(labels))) and summary["class_names"] == labels + assert summary["vocabulary_id"] == "" and summary["score_count"] == 0 + assert summary["has_ignore_label"] == 0 and summary["has_background_label"] == 0 + masks.append(np.fromfile(output, dtype=np.int32).reshape(pixels.shape[:2])) + assert np.array_equal(masks[0], masks[1]), "the C and C++ SDKs must return the same labels" + return masks + + +def test_official_checkpoint_e2e(case_name: str, tmp_path: Path) -> None: + from PIL import Image + + manifest, case = CASES[case_name] + record_evidence("inputs", {"manifest": manifest, "case": case}) + thresholds = record_evidence("thresholds", _thresholds(case_name)) + binary = _required_path(os.environ.get("TRTMC_BINARY"), "TRTMC_BINARY") + runtime_root = _required_path(os.environ.get("TRTMC_RUNTIME_ROOT"), "TRTMC_RUNTIME_ROOT") + assert (runtime_root / "libtrtmc_backend_trt.so").is_file() + assert (runtime_root / f"libtrtmc_model_{FAMILY}.so").is_file() + model_dir = _model_dir(manifest) + record_evidence( + "checkpoint", + { + "model_dir": str(model_dir), + "hf_id": manifest["hf_id"], + "hf_revision": manifest["hf_revision"], + }, + ) + labels = _labels(model_dir) + bundle = tmp_path / manifest["bundle"] + with evidence_stage("build"): + build( + BuildRequest( + model_dir=model_dir, + output_path=bundle, + family=FAMILY, + task=manifest["task"], + precision=manifest["precision"], + tensor_parallel_size=int(manifest["tensor_parallel_size"]), + ) + ) + image_path = _asset(case) + with evidence_stage("native"): + native = _native(binary, runtime_root, bundle, image_path, labels) + image = Image.open(image_path).convert("RGB") + sdk = _sdk_masks(runtime_root, bundle, np.asarray(image), labels, tmp_path) + with evidence_stage("reference"): + expected = _reference(model_dir, image) + with evidence_stage("compare"): + _compare(image, {"cli": native, "sdk": sdk[0]}, expected, labels, thresholds, tmp_path) + + +def test_agreement_metrics_count_every_used_class() -> None: + expected = np.asarray([[0, 0], [1, 1]], dtype=np.int32) + assert _agreement(expected, expected) == {"pixel_accuracy": 1.0, "mIoU": 1.0} + measured = _agreement(np.asarray([[0, 0], [1, 2]], dtype=np.int32), expected) + assert measured["pixel_accuracy"] == 0.75 + assert measured["mIoU"] == pytest.approx((1.0 + 0.5 + 0.0) / 3) + with pytest.raises(AssertionError): + _assert_agreement(measured, {"pixel_accuracy": 0.9, "mIoU": 0.5}) + + +def test_compare_saves_every_map_and_its_overlay_before_it_asserts(tmp_path: Path) -> None: + from PIL import Image + + image = Image.new("RGB", (4, 2)) + expected = np.asarray([[0, 0, 1, 1], [0, 0, 1, 1]], dtype=np.int32) + thresholds = {"pixel_accuracy": 0.999, "mIoU": 0.98} + (tmp_path / "equal").mkdir() + _compare(image, {"cli": expected.copy()}, expected, ["a", "b"], thresholds, tmp_path / "equal") + with pytest.raises(AssertionError): + _compare( + image, + {"cli": expected, "sdk": 1 - expected}, + expected, + ["a", "b"], + thresholds, + tmp_path, + ) + for name in ("native-cli", "native-sdk", "reference"): + assert (tmp_path / f"{name}.png").is_file() + assert np.array_equal( + np.load(tmp_path / f"{name}.labels.npy"), + 1 - expected if name == "native-sdk" else expected, + ) + with pytest.raises(AssertionError, match="native-cli"): + _compare(image, {"cli": expected + 1}, expected, ["a", "b"], thresholds, tmp_path) + + +def test_the_comparison_record_holds_every_asserted_bound(tmp_path: Path) -> None: + native, reference = tmp_path / "native.labels.npy", tmp_path / "reference.labels.npy" + record = _comparison( + "label", + native, + reference, + {"pixel_accuracy": 0.75, "mIoU": 0.99}, + {"pixel_accuracy": 0.9, "mIoU": 0.98}, + ) + assert record["native"] == native and record["reference"] == reference + assert [ + (check["name"], check["actual"], check["expected"], check["passed"]) + for check in record["checks"] + ] == [ + ("pixel_accuracy", 0.75, 0.9, False), + ("mIoU", 0.99, 0.98, True), + ] + assert all(type(check["passed"]) is bool for check in record["checks"]) + + +class _Config: + def __init__(self, options: dict) -> None: + self._options = options + + def getoption(self, name: str, default=None): + return self._options.get(name, default) + + +class _Metafunc: + fixturenames = ("case_name", "tmp_path") + + def __init__(self, options: dict) -> None: + self.config = _Config(options) + self.values = None + + def parametrize(self, name: str, values) -> None: + assert name == "case_name" + self.values = list(values) + + +def _parametrized(options: dict) -> list: + metafunc = _Metafunc(options) + pytest_generate_tests(metafunc) + return metafunc.values + + +def test_an_explicit_selection_of_this_family_that_matches_no_case_is_an_error( + tmp_path: Path, +) -> None: + case = next(iter(CASES)) + models_file = tmp_path / "models.txt" + models_file.write_text(f"# selected models\n{CASES[case][0]['name']}\n", encoding="utf-8") + unselected = _parametrized({}) + assert [value.values for value in unselected] == [(name,) for name in CASES] + assert all([mark.name for mark in value.marks] == ["skip"] for value in unselected) + assert _parametrized({"--e2e-model": ["another-family"]}) == [] + assert _parametrized({"--e2e-testcase": ["another-case"]}) == [] + assert _parametrized({"--e2e-testcase": [case]}) == [case] + assert _parametrized( + {"--e2e-model": [f"another-family,{FAMILY}"], "--e2e-testcase": [case]} + ) == [case] + assert _parametrized({"--e2e-models-file": str(models_file)}) == list(CASES) + for options in ( + {"--e2e-model": [FAMILY], "--e2e-testcase": ["no-such-case"]}, + {"--e2e-models-file": str(models_file), "--e2e-testcase": ["another-case"]}, + {"--e2e-model": ["another-family"], "--e2e-testcase": [case]}, + {"--e2e-testcase": [FAMILY]}, + ): + with pytest.raises(pytest.UsageError, match="matches none of its testcases"): + _parametrized(options) diff --git a/families/mask2former/tests/test_image_ops.py b/families/mask2former/tests/test_image_ops.py new file mode 100644 index 0000000000..2ce9e09032 --- /dev/null +++ b/families/mask2former/tests/test_image_ops.py @@ -0,0 +1,126 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +"""The native image operations against Pillow, the reference image processor and torch, on the CPU. + +The family's `mask2former_image_ops_tool` (built with the CTest targets) runs the runtime's own code on raw files. +Resizing and preprocessing must match bit for bit; the resized argmax must match wherever the reference's best +class is not a near-tie. +""" + +from __future__ import annotations + +import os +import subprocess +from pathlib import Path + +import numpy as np +import pytest + +# The checkpoint's preprocessor_config.json: a fixed 384 x 384 bilinear resize, 1/255 rescale, ImageNet statistics. +_SIZE = 384 +_RESCALE = 0.00392156862745098 +_MEAN = (0.48500001430511475, 0.4560000002384186, 0.4059999883174896) +_STD = (0.2290000021457672, 0.2239999920129776, 0.22499999403953552) +# (height, width) -> (height, width): Pillow 13 runs the horizontal pass first unless the height shrinks by more +# than twice the width's reduction; both orders, growth, shrinkage, identity and one-pixel edges are covered. +_RESIZES = ( + ((382, 640), (_SIZE, _SIZE)), + ((1000, 600), (_SIZE, _SIZE)), + ((900, 300), (_SIZE, _SIZE)), + ((_SIZE, _SIZE), (_SIZE, _SIZE)), + ((97, 1203), (_SIZE, _SIZE)), + ((1, 1), (_SIZE, _SIZE)), + ((5, 3), (2, 7)), + ((2, 400), (1, 9)), +) + + +def _tool() -> Path: + build = os.environ.get("TRTMC_NATIVE_BUILD_DIR") + assert build, "the image-ops parity test requires TRTMC_NATIVE_BUILD_DIR" + tool = Path(build) / "mask2former_image_ops_tool" + assert tool.is_file(), f"build the family's CTest targets first: {tool}" + return tool + + +def _run(*arguments) -> None: + subprocess.run([str(_tool()), *(str(value) for value in arguments)], check=True, timeout=300) + + +def _image(seed: int, height: int, width: int) -> np.ndarray: + return np.random.default_rng(seed).integers(0, 256, size=(height, width, 3), dtype=np.uint8) + + +@pytest.mark.parametrize( + "source,target", _RESIZES, ids=[f"{s[0]}x{s[1]}-{t[0]}x{t[1]}" for s, t in _RESIZES] +) +def test_resize_matches_pillow(source, target, tmp_path: Path) -> None: + from PIL import Image + + image = _image(source[0] * 7919 + source[1], *source) + image.tofile(tmp_path / "in.u8") + _run("resize", tmp_path / "in.u8", *source, *target, tmp_path / "out.u8") + actual = np.fromfile(tmp_path / "out.u8", dtype=np.uint8).reshape(target + (3,)) + expected = np.asarray( + Image.fromarray(image).resize((target[1], target[0]), Image.Resampling.BILINEAR) + ) + assert np.array_equal(actual, expected) + + +@pytest.mark.parametrize("source", [source for source, _ in _RESIZES[:5]]) +def test_preprocess_matches_the_reference_processor(source, tmp_path: Path) -> None: + from PIL import Image + from transformers import Mask2FormerImageProcessor + + processor = Mask2FormerImageProcessor( + do_resize=True, + size={"height": _SIZE, "width": _SIZE}, + size_divisor=32, + resample=Image.Resampling.BILINEAR, + do_rescale=True, + rescale_factor=_RESCALE, + do_normalize=True, + image_mean=list(_MEAN), + image_std=list(_STD), + ) + image = _image(source[0] * 31 + source[1], *source) + expected = processor(images=Image.fromarray(image), return_tensors="np")["pixel_values"][0] + image.tofile(tmp_path / "in.u8") + _run( + "preprocess", + tmp_path / "in.u8", + *source, + _SIZE, + _SIZE, + repr(_RESCALE), + *map(repr, _MEAN), + *map(repr, _STD), + tmp_path / "out.f32", + ) + actual = np.fromfile(tmp_path / "out.f32", dtype=np.float32).reshape(3, _SIZE, _SIZE) + assert expected.dtype == np.float32 and expected.shape == actual.shape + assert np.array_equal(actual, expected) + + +@pytest.mark.parametrize("target", [(382, 640), (_SIZE, _SIZE), (17, 23), (1, 5), (1000, 3)]) +def test_resize_argmax_matches_torch(target, tmp_path: Path) -> None: + import torch + + classes, height, width = 7, 13, 11 + scores = np.random.default_rng(target[0] * 13 + target[1]).random( + (classes, height, width), dtype=np.float32 + ) + scores.tofile(tmp_path / "scores.f32") + _run( + "argmax", tmp_path / "scores.f32", classes, height, width, *target, tmp_path / "labels.i32" + ) + actual = np.fromfile(tmp_path / "labels.i32", dtype=np.int32).reshape(target) + resized = torch.nn.functional.interpolate( + torch.from_numpy(scores)[None], size=target, mode="bilinear", align_corners=False + )[0] + expected = resized.argmax(dim=0).numpy() + top2 = torch.topk(resized, 2, dim=0).values + decided = (top2[0] - top2[1]).numpy() > 1e-5 + assert decided.mean() > 0.99 + assert np.array_equal(actual[decided], expected[decided]) diff --git a/families/mask2former/tests/test_support.py b/families/mask2former/tests/test_support.py new file mode 100644 index 0000000000..0661fd2ba1 --- /dev/null +++ b/families/mask2former/tests/test_support.py @@ -0,0 +1,32 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +"""Dependency-free checkpoint identity and default task for Mask2Former.""" + +from families.mask2former.support import describe +from tensorrt_model_connect.model_support import ModelMetadata + + +def test_checkpoint_identity_selects_semantic_segmentation(): + support = describe( + ModelMetadata( + config={ + "model_type": "mask2former", + "architectures": ["Mask2FormerForUniversalSegmentation"], + }, + model_index={}, + ) + ) + assert support is not None + assert support.tasks == ("image_to_semantic_segmentation",) + assert support.default_task == "image_to_semantic_segmentation" + assert support.default_precision == "fp32" + + +def test_related_segmentation_checkpoints_are_not_claimed(): + for config in ( + {"model_type": "maskformer", "architectures": ["MaskFormerForInstanceSegmentation"]}, + {"model_type": "oneformer", "architectures": ["OneFormerForUniversalSegmentation"]}, + {"model_type": "segformer", "architectures": ["SegformerForSemanticSegmentation"]}, + ): + assert describe(ModelMetadata(config=config, model_index={})) is None diff --git a/families/mask2former/tests/test_weights.py b/families/mask2former/tests/test_weights.py new file mode 100644 index 0000000000..a4961f328a --- /dev/null +++ b/families/mask2former/tests/test_weights.py @@ -0,0 +1,150 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +"""Checkpoint tensors against the configuration: names, dtypes and shapes are checked before any tensor loads.""" + +from __future__ import annotations + +import dataclasses +from pathlib import Path + +import numpy as np +import pytest +from safetensors.numpy import save_file + +from families.mask2former import weights +from families.mask2former.config import Mask2FormerConfig + +# A miniature of the released structure: every width differs, so a check that reads the wrong field fails. +_CONFIG = Mask2FormerConfig( + image_height=8, + image_width=8, + image_mean=(0.5, 0.5, 0.5), + image_std=(0.5, 0.5, 0.5), + rescale_factor=1 / 255, + patch_size=1, + embed_dim=2, + depths=(1, 1, 2, 1), + num_heads=(1, 1, 2, 2), + window_size=1, + mlp_ratio=3.0, + backbone_eps=1e-5, + feature_size=4, + mask_feature_size=5, + hidden_dim=4, + num_attention_heads=2, + encoder_layers=2, + encoder_feedforward_dim=6, + decoder_layers=3, + dim_feedforward=7, + num_queries=2, + labels=("a", "b"), +) + + +def _checkpoint(directory: Path, config: Mask2FormerConfig = _CONFIG, **changes) -> Path: + tensors = { + name: np.zeros(shape, dtype=np.int64 if dtype == "I64" else np.float32) + for name, (shape, dtype) in weights.expected_tensors(config).items() + } + tensors["criterion.empty_weight"] = np.ones(config.num_labels + 1, dtype=np.float32) + for name, value in changes.items(): + if value is None: + del tensors[name] + else: + tensors[name] = value + save_file(tensors, str(directory / "model.safetensors")) + return directory + + +def test_the_released_structure_reads_every_checkpoint_tensor() -> None: + released = dataclasses.replace( + _CONFIG, + image_height=384, + image_width=384, + patch_size=4, + embed_dim=192, + depths=(2, 2, 18, 2), + num_heads=(6, 12, 24, 48), + window_size=12, + mlp_ratio=4.0, + feature_size=256, + mask_feature_size=256, + hidden_dim=256, + num_attention_heads=8, + encoder_layers=6, + encoder_feedforward_dim=1024, + decoder_layers=10, + dim_feedforward=2048, + num_queries=100, + labels=tuple(str(index) for index in range(150)), + ) + # facebook/mask2former-swin-large-ade-semantic holds 782 tensors: these and criterion.empty_weight. + tensors = weights.expected_tensors(released) + assert len(tensors) == 781 + assert tensors["class_predictor.weight"] == ((151, 256), "F32") + assert tensors[ + "model.pixel_level_module.encoder.encoder.layers.2.blocks.17.intermediate.dense.weight" + ] == ((3072, 768), "F32") + assert tensors["model.transformer_module.decoder.layers.8.fc1.weight"] == ((2048, 256), "F32") + + +def test_a_checkpoint_that_matches_its_configuration_loads(tmp_path: Path) -> None: + loaded = weights.load(_checkpoint(tmp_path), _CONFIG) + assert set(loaded) == set(weights.expected_tensors(_CONFIG)) + assert loaded["model.transformer_module.decoder.layers.1.fc1.weight"].shape == (7, 4) + + +@pytest.mark.parametrize( + ("field", "value", "tensor"), + [ + ("dim_feedforward", 8, "model.transformer_module.decoder.layers.0.fc1.weight"), + ( + "encoder_feedforward_dim", + 8, + "model.pixel_level_module.decoder.encoder.layers.0.fc1.weight", + ), + ("mask_feature_size", 4, "model.pixel_level_module.decoder.mask_projection.weight"), + ("mlp_ratio", 4.0, "intermediate.dense.weight"), + ("num_queries", 3, "queries_embedder.weight"), + ], +) +def test_a_configuration_that_disagrees_with_its_weights_is_rejected( + tmp_path: Path, field: str, value, tensor: str +) -> None: + _checkpoint(tmp_path) + with pytest.raises(ValueError, match=f"tensor .*{tensor}.* configuration implies"): + weights.load(tmp_path, dataclasses.replace(_CONFIG, **{field: value})) + + +@pytest.mark.parametrize( + ("changes", "message"), + [ + ({"class_predictor.bias": None}, "1 missing .*class_predictor.bias"), + ( + {"model.extra.weight": np.zeros(2, dtype=np.float32)}, + "1 unexpected .*model.extra.weight", + ), + ( + { + "model.transformer_module.decoder.layers.2.fc1.weight": np.zeros( + (7, 4), dtype=np.float32 + ) + }, + "unexpected .*decoder.layers.2.fc1.weight", + ), + ( + { + "model.pixel_level_module.encoder.encoder.layers.0.blocks.0.attention.self.relative_position_index": ( + np.zeros((1, 1), dtype=np.float32) + ) + }, + "relative_position_index is F32 \\[1, 1\\], but the configuration implies I64", + ), + ], +) +def test_missing_unexpected_and_mistyped_tensors_are_rejected( + tmp_path: Path, changes: dict, message: str +) -> None: + with pytest.raises(ValueError, match=message): + weights.load(_checkpoint(tmp_path, **changes), _CONFIG) diff --git a/families/mask2former/tests/thresholds/mask2former-swin-large-ade-semantic.json b/families/mask2former/tests/thresholds/mask2former-swin-large-ade-semantic.json new file mode 100644 index 0000000000..4ff3c3efb3 --- /dev/null +++ b/families/mask2former/tests/thresholds/mask2former-swin-large-ade-semantic.json @@ -0,0 +1,6 @@ +{ + "threshold_overrides": { + "pixel_accuracy": 0.999, + "mIoU": 0.98 + } +} diff --git a/families/mask2former/transformer_decoder.py b/families/mask2former/transformer_decoder.py new file mode 100644 index 0000000000..948801ffa5 --- /dev/null +++ b/families/mask2former/transformer_decoder.py @@ -0,0 +1,258 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +"""The Mask2Former transformer module and the semantic-segmentation head. + +Read from `Mask2FormerTransformerModule`, `Mask2FormerMaskedAttentionDecoder` and +`Mask2FormerImageProcessor.post_process_semantic_segmentation`: + +* the decoder runs `decoder_layers - 1` post-norm layers; layer `i` cross-attends to pixel-decoder level `i % 3`, + then self-attends, then applies its feed-forward block; +* before every layer the mask predictor turns the layer-normed queries into mask logits at the mask-feature + resolution; resized bilinearly to the next level, `sigmoid < 0.5` marks the positions a query may not attend to, + and a query whose positions are all marked attends to every position instead; +* the semantic map is the einsum of the class probabilities (no-object class removed) with the sigmoid of the final + mask logits after bilinear resizing to the reference post-processor's fixed size. +""" + +from __future__ import annotations + +import math + +import numpy as np +import tensorrt as trt + +from . import graph as g +from .config import FEATURE_LEVELS, NORM_EPS, SEMANTIC_SCORE_SIZE, Mask2FormerConfig +from .pixel_decoder import sine_position_embedding + +_PREFIX = "model.transformer_module" + + +def _layer_norm(network, tensor, weights, name): + return g.layer_norm( + network, tensor, weights[f"{name}.weight"], weights[f"{name}.bias"], NORM_EPS + ) + + +def _mask_embeddings(network, queries, weights): + hidden = queries + for index in range(3): + base = f"{_PREFIX}.decoder.mask_predictor.mask_embedder.{index}.0" + hidden = g.linear(network, hidden, weights[f"{base}.weight"], weights[f"{base}.bias"]) + if index < 2: + hidden = g.relu(network, hidden) + return hidden + + +def _mask_logits(network, queries, mask_features, weights): + """(1, queries, width) and (1, width, H*W) -> (1, queries, H*W) mask logits.""" + + return g.matmul(network, _mask_embeddings(network, queries, weights), mask_features) + + +def _attention_mask(network, logits, mask_shape, target): + """Positions a query may not attend to at the target level, as `Mask2FormerMaskPredictor` marks them. + + A query whose positions are all marked attends everywhere (`Mask2FormerMaskedAttentionDecoder.forward`). + Returns a (1, 1, queries, h*w) boolean tensor; true means the position is excluded. + """ + + _, queries, _ = g.shape(logits) + height, width = target + resized = g.resize_bilinear( + network, g.reshape(network, logits, (1, queries) + tuple(mask_shape)), height, width + ) + excluded = g.elementwise( + network, + g.sigmoid(network, resized), + g.scalar_like(network, 0.5, 4), + trt.ElementWiseOperation.LESS, + ) + excluded = g.reshape(network, excluded, (1, 1, queries, height * width)) + count = network.add_reduce( + network.add_cast(excluded, trt.float32).get_output(0), trt.ReduceOperation.SUM, 1 << 3, True + ) + if count is None: + raise RuntimeError("TensorRT rejected the Mask2Former attention-mask count") + complete = g.elementwise( + network, + count.get_output(0), + g.scalar_like(network, float(height * width), 4), + trt.ElementWiseOperation.EQUAL, + ) + keep = network.add_unary(complete, trt.UnaryOperation.NOT) + if keep is None: + raise RuntimeError("TensorRT rejected the Mask2Former attention-mask negation") + return g.elementwise(network, excluded, keep.get_output(0), trt.ElementWiseOperation.AND) + + +def _attend(network, query, key, value, excluded=None): + """Softmax attention over (1, heads, N, D) tensors; `excluded` positions get no weight.""" + + scores = g.matmul(network, query, key, transpose_right=True) + if excluded is not None: + blocked = g.constant(network, np.full((1, 1, 1, 1), -np.inf, dtype=np.float32)) + select = network.add_select(excluded, blocked, scores) + if select is None: + raise RuntimeError("TensorRT rejected the Mask2Former masked attention") + scores = select.get_output(0) + return g.merge_heads(network, g.matmul(network, g.softmax(network, scores, 3), value)) + + +def _cross_attention( + network, hidden, query_position, memory, key_input, excluded, weights, prefix, heads +): + """`nn.MultiheadAttention` with a boolean mask: q is scaled by head_dim ** -0.5 after its projection.""" + + width = g.shape(hidden)[-1] + in_weight = np.asarray(weights[f"{prefix}.in_proj_weight"], dtype=np.float32) + in_bias = np.asarray(weights[f"{prefix}.in_proj_bias"], dtype=np.float32) + if in_weight.shape != (3 * width, width) or in_bias.shape != (3 * width,): + raise ValueError(f"mask2former {prefix} in-projection has shape {in_weight.shape}") + query = g.linear( + network, g.add(network, hidden, query_position), in_weight[:width], in_bias[:width] + ) + query = g.mul( + network, + g.split_heads(network, query, heads), + g.scalar_like(network, math.sqrt(1.0 / (width // heads)), 4), + ) + key = g.split_heads( + network, + g.linear(network, key_input, in_weight[width : 2 * width], in_bias[width : 2 * width]), + heads, + ) + value = g.split_heads( + network, g.linear(network, memory, in_weight[2 * width :], in_bias[2 * width :]), heads + ) + attended = _attend(network, query, key, value, excluded) + return g.linear( + network, attended, weights[f"{prefix}.out_proj.weight"], weights[f"{prefix}.out_proj.bias"] + ) + + +def _self_attention(network, hidden, query_position, weights, prefix, heads): + """`Mask2FormerAttention`: queries and keys carry the position embeddings, values do not.""" + + width = g.shape(hidden)[-1] + posed = g.add(network, hidden, query_position) + query = g.linear( + network, posed, weights[f"{prefix}.q_proj.weight"], weights[f"{prefix}.q_proj.bias"] + ) + query = g.mul(network, query, g.scalar_like(network, (width // heads) ** -0.5, 3)) + key = g.linear( + network, posed, weights[f"{prefix}.k_proj.weight"], weights[f"{prefix}.k_proj.bias"] + ) + value = g.linear( + network, hidden, weights[f"{prefix}.v_proj.weight"], weights[f"{prefix}.v_proj.bias"] + ) + attended = _attend( + network, + g.split_heads(network, query, heads), + g.split_heads(network, key, heads), + g.split_heads(network, value, heads), + ) + return g.linear( + network, attended, weights[f"{prefix}.out_proj.weight"], weights[f"{prefix}.out_proj.bias"] + ) + + +def build_semantic_scores(network, multi_scale, mask_features, weights, config: Mask2FormerConfig): + """Return (1, classes, 384, 384) semantic scores, the tensor the reference post-processor resizes and argmaxes.""" + + heads = config.num_attention_heads + width = config.hidden_dim + level_embed = np.asarray(weights[f"{_PREFIX}.level_embed.weight"], dtype=np.float32) + if level_embed.shape != (FEATURE_LEVELS, width): + raise ValueError(f"mask2former transformer level_embed has shape {level_embed.shape}") + memories, keys, sizes = [], [], [] + for index, level in enumerate(multi_scale): + height, width_l = g.shape(level)[2:] + sizes.append((height, width_l)) + memory = g.add( + network, + g.tokens_from_nchw(network, level), + g.constant(network, level_embed[index].reshape(1, 1, width)), + ) + memories.append(memory) + keys.append( + g.add( + network, + memory, + g.constant(network, sine_position_embedding(height, width_l, width // 2)[None]), + ) + ) + + queries_weight = np.asarray(weights[f"{_PREFIX}.queries_embedder.weight"], dtype=np.float32) + features_weight = np.asarray(weights[f"{_PREFIX}.queries_features.weight"], dtype=np.float32) + expected = (config.num_queries, width) + if queries_weight.shape != expected or features_weight.shape != expected: + raise ValueError("mask2former query embeddings do not match num_queries and hidden_dim") + query_position = g.constant(network, queries_weight[None]) + hidden = g.constant(network, features_weight[None]) + + mask_shape = g.shape(mask_features)[2:] + flat_masks = g.reshape( + network, mask_features, (1, g.shape(mask_features)[1], mask_shape[0] * mask_shape[1]) + ) + normed = _layer_norm(network, hidden, weights, f"{_PREFIX}.decoder.layernorm") + logits = _mask_logits(network, normed, flat_masks, weights) + layers = config.decoder_layers - 1 + for index in range(layers): + level = index % FEATURE_LEVELS + excluded = _attention_mask(network, logits, mask_shape, sizes[level]) + prefix = f"{_PREFIX}.decoder.layers.{index}" + attended = _cross_attention( + network, + hidden, + query_position, + memories[level], + keys[level], + excluded, + weights, + f"{prefix}.cross_attn", + heads, + ) + hidden = _layer_norm( + network, g.add(network, hidden, attended), weights, f"{prefix}.cross_attn_layer_norm" + ) + attended = _self_attention( + network, hidden, query_position, weights, f"{prefix}.self_attn", heads + ) + hidden = _layer_norm( + network, g.add(network, hidden, attended), weights, f"{prefix}.self_attn_layer_norm" + ) + inner = g.relu( + network, + g.linear( + network, hidden, weights[f"{prefix}.fc1.weight"], weights[f"{prefix}.fc1.bias"] + ), + ) + inner = g.linear( + network, inner, weights[f"{prefix}.fc2.weight"], weights[f"{prefix}.fc2.bias"] + ) + hidden = _layer_norm( + network, g.add(network, hidden, inner), weights, f"{prefix}.final_layer_norm" + ) + normed = _layer_norm(network, hidden, weights, f"{_PREFIX}.decoder.layernorm") + logits = _mask_logits(network, normed, flat_masks, weights) + + classes = config.num_labels + class_logits = g.linear( + network, normed, weights["class_predictor.weight"], weights["class_predictor.bias"] + ) + if g.shape(class_logits)[-1] != classes + 1: + raise ValueError( + "mask2former class_predictor does not match id2label plus the no-object class" + ) + probabilities = g.slice_static( + network, g.softmax(network, class_logits, 2), (0, 0, 0), (1, config.num_queries, classes) + ) + size = SEMANTIC_SCORE_SIZE + masks = g.resize_bilinear( + network, g.reshape(network, logits, (1, config.num_queries) + tuple(mask_shape)), size, size + ) + masks = g.reshape(network, g.sigmoid(network, masks), (1, config.num_queries, size * size)) + scores = g.matmul(network, probabilities, masks, transpose_left=True) + return g.reshape(network, scores, (1, classes, size, size)) diff --git a/families/mask2former/weights.py b/families/mask2former/weights.py new file mode 100644 index 0000000000..9d6b806a94 --- /dev/null +++ b/families/mask2former/weights.py @@ -0,0 +1,173 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +"""The checkpoint tensors the Mask2Former graph reads, checked against the configuration before any is loaded. + +Most layer widths reach the graph through the weights, so a configuration that disagrees with its weights would build +the weights' topology and ignore the configuration. Every tensor must therefore exist with the dtype and shape the +configuration implies, and the checkpoint may hold no other tensor than the training-only `criterion.empty_weight`. +""" + +from __future__ import annotations + +from pathlib import Path + +import numpy as np +from safetensors import safe_open + +from .config import ENCODER_POINTS, FEATURE_LEVELS, Mask2FormerConfig + +# A training-only buffer that inference never reads. +_UNUSED = frozenset({"criterion.empty_weight"}) +_DTYPES = {"F32": np.float32, "I64": np.int64} + + +def expected_tensors(config: Mask2FormerConfig) -> dict[str, tuple[tuple[int, ...], str]]: + """Name -> (shape, safetensors dtype) of every tensor the graph reads.""" + + tensors: dict[str, tuple[tuple[int, ...], str]] = {} + + def add(name: str, *shape: int, dtype: str = "F32") -> None: + tensors[name] = (tuple(shape), dtype) + + def linear(prefix: str, out_features: int, in_features: int, *, bias: bool = True) -> None: + add(f"{prefix}.weight", out_features, in_features) + if bias: + add(f"{prefix}.bias", out_features) + + def norm(prefix: str, width: int) -> None: + add(f"{prefix}.weight", width) + add(f"{prefix}.bias", width) + + embed, window = config.embed_dim, config.window_size + backbone = "model.pixel_level_module.encoder" + add( + f"{backbone}.embeddings.patch_embeddings.projection.weight", + embed, + 3, + config.patch_size, + config.patch_size, + ) + add(f"{backbone}.embeddings.patch_embeddings.projection.bias", embed) + norm(f"{backbone}.embeddings.norm", embed) + for stage, (depth, heads, width) in enumerate( + zip(config.depths, config.num_heads, config.stage_channels) + ): + hidden = int(config.mlp_ratio * width) + for block in range(depth): + prefix = f"{backbone}.encoder.layers.{stage}.blocks.{block}" + norm(f"{prefix}.layernorm_before", width) + for name in ("query", "key", "value"): + linear(f"{prefix}.attention.self.{name}", width, width) + add( + f"{prefix}.attention.self.relative_position_bias_table", + (2 * window - 1) ** 2, + heads, + ) + add( + f"{prefix}.attention.self.relative_position_index", + window * window, + window * window, + dtype="I64", + ) + linear(f"{prefix}.attention.output.dense", width, width) + norm(f"{prefix}.layernorm_after", width) + linear(f"{prefix}.intermediate.dense", hidden, width) + linear(f"{prefix}.output.dense", width, hidden) + if stage + 1 < len(config.depths): + norm(f"{backbone}.encoder.layers.{stage}.downsample.norm", 4 * width) + linear( + f"{backbone}.encoder.layers.{stage}.downsample.reduction", + 2 * width, + 4 * width, + bias=False, + ) + norm(f"{backbone}.hidden_states_norms.stage{stage + 1}", width) + + features, heads = config.feature_size, config.num_attention_heads + decoder = "model.pixel_level_module.decoder" + add(f"{decoder}.level_embed", FEATURE_LEVELS, features) + # The transformer levels, coarsest first: stage 4, stage 3, stage 2. + for index, channels in enumerate(reversed(config.stage_channels[-FEATURE_LEVELS:])): + add(f"{decoder}.input_projections.{index}.0.weight", features, channels, 1, 1) + add(f"{decoder}.input_projections.{index}.0.bias", features) + norm(f"{decoder}.input_projections.{index}.1", features) + for layer in range(config.encoder_layers): + prefix = f"{decoder}.encoder.layers.{layer}" + points = heads * FEATURE_LEVELS * ENCODER_POINTS + linear(f"{prefix}.self_attn.sampling_offsets", 2 * points, features) + linear(f"{prefix}.self_attn.attention_weights", points, features) + linear(f"{prefix}.self_attn.value_proj", features, features) + linear(f"{prefix}.self_attn.output_proj", features, features) + norm(f"{prefix}.self_attn_layer_norm", features) + linear(f"{prefix}.fc1", config.encoder_feedforward_dim, features) + linear(f"{prefix}.fc2", features, config.encoder_feedforward_dim) + norm(f"{prefix}.final_layer_norm", features) + add(f"{decoder}.adapter_1.0.weight", features, config.stage_channels[0], 1, 1) + norm(f"{decoder}.adapter_1.1", features) + add(f"{decoder}.layer_1.0.weight", features, features, 3, 3) + norm(f"{decoder}.layer_1.1", features) + add(f"{decoder}.mask_projection.weight", config.mask_feature_size, features, 1, 1) + add(f"{decoder}.mask_projection.bias", config.mask_feature_size) + + hidden_dim, module = config.hidden_dim, "model.transformer_module" + add(f"{module}.queries_embedder.weight", config.num_queries, hidden_dim) + add(f"{module}.queries_features.weight", config.num_queries, hidden_dim) + add(f"{module}.level_embed.weight", FEATURE_LEVELS, hidden_dim) + norm(f"{module}.decoder.layernorm", hidden_dim) + for layer in range(config.decoder_layers - 1): + prefix = f"{module}.decoder.layers.{layer}" + for name in ("q_proj", "k_proj", "v_proj", "out_proj"): + linear(f"{prefix}.self_attn.{name}", hidden_dim, hidden_dim) + norm(f"{prefix}.self_attn_layer_norm", hidden_dim) + add(f"{prefix}.cross_attn.in_proj_weight", 3 * hidden_dim, hidden_dim) + add(f"{prefix}.cross_attn.in_proj_bias", 3 * hidden_dim) + linear(f"{prefix}.cross_attn.out_proj", hidden_dim, hidden_dim) + norm(f"{prefix}.cross_attn_layer_norm", hidden_dim) + linear(f"{prefix}.fc1", config.dim_feedforward, hidden_dim) + linear(f"{prefix}.fc2", hidden_dim, config.dim_feedforward) + norm(f"{prefix}.final_layer_norm", hidden_dim) + for index, out_features in enumerate((hidden_dim, hidden_dim, config.mask_feature_size)): + linear(f"{module}.decoder.mask_predictor.mask_embedder.{index}.0", out_features, hidden_dim) + linear("class_predictor", config.num_labels + 1, hidden_dim) + return tensors + + +def _names(kind: str, names: list[str]) -> str: + shown = ", ".join(names[:3]) + (", ..." if len(names) > 3 else "") + return f"{len(names)} {kind} ({shown})" + + +def load(model_dir: Path, config: Mask2FormerConfig) -> dict[str, np.ndarray]: + """Check every tensor's name, dtype and shape from the safetensors header, then load them.""" + + path = Path(model_dir) / "model.safetensors" + if not path.is_file(): + raise FileNotFoundError(f"missing mask2former weights: {path}") + expected = expected_tensors(config) + with safe_open(str(path), framework="numpy") as reader: + names = set(reader.keys()) + missing = sorted(set(expected) - names) + unexpected = sorted(names - set(expected) - _UNUSED) + if missing or unexpected: + found = [ + _names(kind, items) + for kind, items in (("missing", missing), ("unexpected", unexpected)) + if items + ] + raise ValueError( + "mask2former checkpoint tensors do not match its configuration: " + "; ".join(found) + ) + for name, (shape, dtype) in expected.items(): + header = reader.get_slice(name) + found = (tuple(header.get_shape()), header.get_dtype()) + if found != (shape, dtype): + raise ValueError( + f"mask2former tensor {name} is {found[1]} {list(found[0])}, " + f"but the configuration implies {dtype} {list(shape)}" + ) + weights = {name: reader.get_tensor(name) for name in expected} + for name, (_, dtype) in expected.items(): + if weights[name].dtype != _DTYPES[dtype]: + raise ValueError(f"mask2former tensor {name} did not load as {dtype}") + return weights