diff --git a/ASSET_LICENSES.md b/ASSET_LICENSES.md index f1ffd99087..167d37df26 100644 --- a/ASSET_LICENSES.md +++ b/ASSET_LICENSES.md @@ -64,6 +64,10 @@ inclusion and redistribution in this repository under the Apache License 2.0: `families/timm_resnet/tests/data/test_img_car.jpeg`, a crop of the same photograph, and is distributed under the same terms. +- `families/siglip2/tests/data/test_img.png` is a lossless PNG encoding of the same + photograph, pixel-identical to `families/detr/tests/data/test_img.jpeg` decoded by + Pillow, and is distributed under the same terms. + `families/swinv2/tests/data/test_img.png` is the same photograph decoded to RGB and saved losslessly as PNG (its pixels equal Pillow's decode of the `test_img.jpeg` copies listed above) and is distributed under the same terms. diff --git a/families/siglip2/NOTICE b/families/siglip2/NOTICE new file mode 100644 index 0000000000..40c6d6e1df --- /dev/null +++ b/families/siglip2/NOTICE @@ -0,0 +1,150 @@ +The NaFlex image preprocessing in runtime/naflex_preprocess.cpp ports code from three +upstream sources. + +1. The patch-budget size search and the patch layout follow + get_image_size_for_max_num_patches and convert_image_to_patches in + src/transformers/models/siglip2/image_processing_siglip2.py of transformers v5.2.0: + https://github.com/huggingface/transformers/blob/v5.2.0/src/transformers/models/siglip2/image_processing_siglip2.py + The file carries this header: + +Copyright 2025 The HuggingFace Inc. team. All rights reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. + +2. The 8-bit bilinear resize reproduces precompute_coeffs, normalize_coeffs_8bpc, + ImagingResampleHorizontal_8bpc, ImagingResampleVertical_8bpc and the pass order of + ImagingResampleInner in src/libImaging/Resample.c of Pillow 13.0.0: + https://github.com/python-pillow/Pillow/blob/13.0.0/src/libImaging/Resample.c + Pillow is licensed as follows: + +The Python Imaging Library (PIL) is + + Copyright © 1997-2011 by Secret Labs AB + Copyright © 1995-2011 by Fredrik Lundh and contributors + +Pillow is the friendly PIL fork. It is + + Copyright © 2010 by Jeffrey 'Alex' Clark and contributors + +Like PIL, Pillow is licensed under the open source MIT-CMU License: + +By obtaining, using, and/or copying this software and/or its associated +documentation, you agree that you have read, understood, and will comply +with the following terms and conditions: + +Permission to use, copy, modify and distribute this software and its +documentation for any purpose and without fee is hereby granted, +provided that the above copyright notice appears in all copies, and that +both that copyright notice and this permission notice appear in supporting +documentation, and that the name of Secret Labs AB or the author not be +used in advertising or publicity pertaining to distribution of the software +without specific, written prior permission. + +SECRET LABS AB AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS +SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. +IN NO EVENT SHALL SECRET LABS AB OR THE AUTHOR BE LIABLE FOR ANY SPECIAL, +INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM +LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE +OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR +PERFORMANCE OF THIS SOFTWARE. + +3. The antialiased bilinear taps that resample the position table follow + HelperInterpBase::_compute_indices_min_size_weights_aa in + aten/src/ATen/native/cpu/UpSampleKernel.cpp of PyTorch v2.12.0: + https://github.com/pytorch/pytorch/blob/v2.12.0/aten/src/ATen/native/cpu/UpSampleKernel.cpp + PyTorch is licensed as follows: + +From PyTorch: + +Copyright (c) 2016- Facebook, Inc (Adam Paszke) +Copyright (c) 2014- Facebook, Inc (Soumith Chintala) +Copyright (c) 2011-2014 Idiap Research Institute (Ronan Collobert) +Copyright (c) 2012-2014 Deepmind Technologies (Koray Kavukcuoglu) +Copyright (c) 2011-2012 NEC Laboratories America (Koray Kavukcuoglu) +Copyright (c) 2011-2013 NYU (Clement Farabet) +Copyright (c) 2006-2010 NEC Laboratories America (Ronan Collobert, Leon Bottou, Iain Melvin, Jason Weston) +Copyright (c) 2006 Idiap Research Institute (Samy Bengio) +Copyright (c) 2001-2004 Idiap Research Institute (Ronan Collobert, Samy Bengio, Johnny Mariethoz) + +From Caffe2: + +Copyright (c) 2016-present, Facebook Inc. All rights reserved. + +All contributions by Facebook: +Copyright (c) 2016 Facebook Inc. + +All contributions by Google: +Copyright (c) 2015 Google Inc. +All rights reserved. + +All contributions by Yangqing Jia: +Copyright (c) 2015 Yangqing Jia +All rights reserved. + +All contributions by Kakao Brain: +Copyright 2019-2020 Kakao Brain + +All contributions by Cruise LLC: +Copyright (c) 2022 Cruise LLC. +All rights reserved. + +All contributions by Tri Dao: +Copyright (c) 2024 Tri Dao. +All rights reserved. + +All contributions by Arm: +Copyright (c) 2021, 2023-2025 Arm Limited and/or its affiliates + +All contributions from Caffe: +Copyright(c) 2013, 2014, 2015, the respective contributors +All rights reserved. + +All other contributions: +Copyright(c) 2015, 2016 the respective contributors +All rights reserved. + +Caffe2 uses a copyright model similar to Caffe: each contributor holds +copyright over their contributions to Caffe2. The project versioning records +all such contribution and copyright details. If a contributor wants to further +mark their specific copyright on a particular contribution, they should +indicate their copyright solely in the commit message of the change when it is +committed. + +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + +1. Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + +2. Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + +3. Neither the names of Facebook, Deepmind Technologies, NYU, NEC Laboratories America + and IDIAP Research Institute nor the names of its contributors may be + used to endorse or promote products derived from this software without + specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE +LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +POSSIBILITY OF SUCH DAMAGE. diff --git a/families/siglip2/README.md b/families/siglip2/README.md new file mode 100644 index 0000000000..00fc7a1985 --- /dev/null +++ b/families/siglip2/README.md @@ -0,0 +1,152 @@ +# SigLIP 2 NaFlex image and text embeddings + +This family builds +[`google/siglip2-base-patch16-naflex`](https://huggingface.co/google/siglip2-base-patch16-naflex/tree/b53b807d3a2d5e2b3911292f2d69e5341cdc064c) +(`Siglip2Model`, `model_type: siglip2`) into one bundle that serves three existing +Tasks: `image_to_embedding`, `text_to_embedding` and `text_image_to_relevance` (the +default). Both towers return 768-dimensional L2-normalised vectors in the `siglip2` +embedding space; relevance is the checkpoint's per-pair sigmoid, +`sigmoid(exp(logit_scale) * cos(image, text) + logit_bias)`, returned as a +probability. + +Scope: float32 (the checkpoint's own precision), one image or one text per request, +TP1 / CP1, the TensorRT backend. Reduced precision, quantization, batching, +`Siglip2ForImageClassification` and other image processors are refused at build +time. The fixed-resolution SigLIP 2 checkpoints publish `model_type: siglip` and the +`SiglipModel` graph; they belong to the `siglip` family, not to this one. Only the +checkpoint above is qualified: other `siglip2` checkpoints resolve to this family and +build by the same rules, but have not been validated. + +## Bundle and runtime + +The bundle carries a vision engine, a text engine, `tokenizer.json` and +`runtime.json`. The checkpoint's `config.json` states almost nothing, so the +geometry is read from the tensor shapes and `preprocessor_config.json`, and any +stated value is checked against them. + +- **Image.** NaFlex resizes each image, keeping its aspect ratio, to the largest + size whose sides are whole 16-pixel patches and whose patch count fits the + processor's budget of 256, using the reference processor's own binary search. + The runtime then reproduces the reference processor value for value: Pillow 13's + 8-bit bilinear resize (fixed-point coefficients and Pillow 13's choice of which + pass runs first), numpy's float64 rescale and float32 normalisation, and the + patch cut in (row, column, channel) order. The vision engine takes exactly the + image's patches, with the patch count dynamic from 1 to 256, so no padding or + attention mask is needed: the reference pads to the budget and masks the padding, + which computes the same function. The 16 x 16 position table stays in the engine; + the runtime passes the antialiased bilinear taps that resample it to the image's + grid (`[patches, 256]`, built in float64), and the engine multiplies them in. + Pooling is the checkpoint's attention head (one learned query over all patches). +- **Text.** A byte-fallback BPE tokenizer reproduces the reference tokenizer: the + only normalisation is the space marker, there is no pre-tokenizer, and `` is + appended. Like the reference, it does **not** lowercase: the `do_lower_case` entry + in `tokenizer_config.json` is not applied by the tokenizer that transformers loads + for this checkpoint. SigLIP 2 was trained on lowercased text (transformers' + `Siglip2Tokenizer` class, which is not the one loaded here, adds a lowercase + normaliser for that reason), so callers should lowercase their labels. The prompt is + right-padded with `` to the 64-token window, and a longer prompt keeps its + first 63 tokens and ``, as the reference truncation does. The pooled row is + the last row of the window, so the window length is a correctness rule, not a + capacity. The tokenizer is adapted from the repository's family-local BPE + implementation in `families/embeddinggemma2/runtime/bpe_tokenizer.cpp`. It merges in + the reference tokenizer's order (the lowest-ranked adjacent pair, the leftmost on a + tie, one at a time). Like the builder, it refuses on load a `tokenizer.json` that it + would tokenise differently: another normaliser, pre-tokenizer or template shape, BPE + dropout, a subword prefix or suffix or `ignore_merges`, vocabulary ids outside + 0..N-1 or no `▁` marker, a merge rule that is not one pair of vocabulary entries + with a result in the vocabulary, a byte fallback that could need the unknown token, + added tokens with matching options or with an id other than their vocabulary id, and + an end token that expands to other ids than its own. It has no decoder: the + family never turns ids back into text. + +## Reference behaviours this family takes a position on + +- **Pillow version.** Pillow 13.0.0 resamples vertically first when the height + shrinks by more than twice as many pixels as the width; Pillow 12 always went + horizontally first. Each pass rounds to 8 bits, so the two versions disagree by one + step on such images. The family reproduces Pillow 13.0.0, pinned in + `requirements.txt`. +- **Slow and fast processors.** The checkpoint names `Siglip2ImageProcessorFast`, + which transformers selects when torchvision is installed. It resizes with + torchvision instead of Pillow and lands one 8-bit step away on about 45 % of the + pixel values of the test images, which moves the image embeddings by up to + 2.6e-4 per component. The family reproduces the Pillow processor + (`use_fast=False`), and the E2E compares against it. +- **A grid one patch wide.** PyTorch's CPU kernel for antialiased bilinear + interpolation returns wrong values when the width is 1 (torch 2.12.0 and 2.15.0a0 + on CPU: up to 7.1 on this checkpoint's position table and 0.8 to 1.1 on random + tables), while its CUDA kernel matches the + separable definition to 4e-7. The reference resizes the position table with that + call, so on CPU it disagrees with itself on GPU for images whose NaFlex grid is a + single column (for example 3000 x 20 pixels). The runtime implements the + definition, which is what the reference computes on GPU. Such images are not in + the E2E, whose reference runs on CPU. + +## Validation + +CPU tests (no GPU, no checkpoint): + +```sh +PYTHONPATH=core/builder:apps/benchmark:. python -m pytest families/siglip2/tests -q +``` + +`test_model.py` covers the geometry resolution, every refused build option, the +processor settings and tokenizer contracts the runtime does not reproduce, and the +prompt window. The native CTests (`test_siglip2_naflex_preprocess`, +`test_siglip2_pipeline`, `test_siglip2_tokenizer`) check the target-size search, +Pillow's resize and the position taps against values produced by the reference +implementations, the patch layout, the padded text window, normalisation, the +sigmoid relevance and the runtime's refusals. + +GPU E2E: cache the checkpoint at the revision above (or set +`TRTMC_SIGLIP2_MODEL_DIR`), install `requirements.txt`, configure `TRTMC_BINARY`, +`TRTMC_RUNTIME_ROOT` and `TRTMC_NATIVE_BUILD_DIR` for the native build, then: + +```sh +python -m pytest families/siglip2/tests/test_e2e.py --e2e-model siglip2 -q +``` + +The case first runs the runtime's host preprocessing through +`siglip2_preprocess_dump` on three images with different grids (the test +photograph, a portrait crop and a small crop the processor upscales) and requires +every pixel value to equal the reference processor's, and the resampled position +table to match the reference's to 1e-4. It then builds the bundle and compares the +native embeddings of the three images and of six texts (English, mixed case, +French, Chinese and a 78-token prompt that is truncated), and the relevance logit +of a matching and a non-matching pair, with the reference model in float32 on the +CPU. + +Measured on one B300 PCIe (TensorRT 11.4.0.106, CUDA 13.4, torch 2.15.0a0 from the +NGC PyTorch 26.10 image with transformers 5.2.0 and Pillow 13.0.0): host +preprocessing is exact on all three images (grids 12 x 21, 22 x 11 and 14 x 18); +the embeddings are within 4.2e-07 (images) and 6.4e-07 (texts) of the reference, +the logits within 1.3e-05. The gates (1e-04 per embedding component, 2e-03 on the +logit) were set between that noise and deliberate breaks of the graph or the host +inputs, built and measured on the same case (photograph, two texts): + +| Variant | Image max \|diff\| | Text max \|diff\| | Logit \|diff\| | +| --- | --- | --- | --- | +| Correct float32 build | 2.1e-07 | 1.2e-07 | 1.3e-05 | +| Exact GELU instead of the tanh approximation | 1.1e-03 | 4.5e-04 | 2.3e-02 | +| Patches padded to the budget, no mask | 5.5e-03 | - | 1.3e-01 | +| Position table not resampled (first rows) | 1.4e-01 | - | 2.9e+00 | +| Position table resampled transposed | 2.0e-01 | - | 3.7e+00 | +| Patch flattened in (channel, row, column) order | 2.9e-01 | - | 7.7e+00 | +| Pooling-head residual taken after its norm | 3.3e-01 | - | 2.6e+01 | +| Text pooled at the first row of the window | - | 3.2e-01 | 2.9e+01 | + +Outside the E2E, the host preprocessing was also compared value for value with +the reference processor on 17 images from 1 x 1 to 3000 x 20 and 2 x 4000 pixels +(identical grids and pixels), and the runtime tokenizer with the reference +tokenizer on 2,614 strings (identical ids), including all 256 single-byte code +points, nine scripts, whitespace runs, added tokens and over-long prompts, and on +5,709 more built around the merge table's 903 rank inversions (a merge whose +result forms a pair that ranks before it), also with identical ids. + +## Assets + +`tests/data/test_img.png` is the repository's shared vehicle photograph (see +`ASSET_LICENSES.md`). The checkpoint and its tokenizer are Apache-2.0 and are not +redistributed by this family. The NaFlex preprocessing adapts code from transformers +(Apache-2.0), Pillow (MIT-CMU) and PyTorch (BSD-3-Clause); `NOTICE` gives the sources +and their license texts. diff --git a/families/siglip2/__init__.py b/families/siglip2/__init__.py new file mode 100644 index 0000000000..171e515062 --- /dev/null +++ b/families/siglip2/__init__.py @@ -0,0 +1,4 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +"""siglip2 family.""" diff --git a/families/siglip2/config.py b/families/siglip2/config.py new file mode 100644 index 0000000000..087736961f --- /dev/null +++ b/families/siglip2/config.py @@ -0,0 +1,267 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +"""Read the SigLIP 2 NaFlex geometry out of the tensors and the processor file. + +The published ``config.json`` states the architecture, the sub-model types and the +text vocabulary size, nothing else: every width, depth, head count, activation and +epsilon is supplied by the reference library's defaults. Every number a tensor shape +fixes is therefore read from that shape, whatever the file does state is checked +against it and refused on disagreement, and the few numbers no shape carries (head +count, activation, epsilon) are the reference's documented defaults unless the file +states them. + +NaFlex has no fixed input size. The processor resizes each image, keeping its aspect +ratio, to the largest multiple of the patch size whose patch count fits +``max_num_patches``, and the vision tower interpolates its square position table to +that grid. Both numbers live in ``preprocessor_config.json``; the table's grid comes +from the tensor. +""" + +from __future__ import annotations + +import json +import sys +from pathlib import Path + +# Reference defaults (Siglip2TextConfig / Siglip2VisionConfig) for numbers that no +# tensor shape carries. A head count is not derivable from any projection, which is +# [width, width] whatever the count, so a file that omits it gets the reference's 12. +_REFERENCE_HEADS = 12 +_EXPECTED_ACTIVATION = "gelu_pytorch_tanh" +_DEFAULT_EPS = 1e-6 +_CHANNELS = 3 + +# Siglip2ImageProcessor defaults, used only when preprocessor_config.json omits a key. +_DEFAULT_PATCH = 16 +_DEFAULT_MAX_PATCHES = 256 +_DEFAULT_MEAN = [0.5, 0.5, 0.5] +_DEFAULT_STD = [0.5, 0.5, 0.5] +# PIL's enumeration: 2 is bilinear. The runtime reproduces Pillow's 8-bit bilinear +# resize exactly, and nothing else. +_BILINEAR = 2 +_RESCALE = 1.0 / 255.0 +_PROCESSORS = {"Siglip2ImageProcessor", "Siglip2ImageProcessorFast"} + + +def _integer(value, what: str) -> int: + # A JSON value is taken with its own type: a fraction, a bool or a string is refused where + # an integer or a number belongs, not rounded, counted or parsed into one. + if type(value) is not int: + raise ValueError(f"siglip2 {what} must be an integer, not {value!r}") + return value + + +def _number(value, what: str) -> float: + # The json module also reads NaN and Infinity; they, and an integer past the float range, + # fail the comparison. + if type(value) not in (int, float) or not abs(value) <= sys.float_info.max: + raise ValueError(f"siglip2 {what} must be a finite number, not {value!r}") + return float(value) + + +def _shape(weights, key: str) -> tuple: + if key not in weights: + raise KeyError(f"siglip2 checkpoint is missing '{key}'") + return tuple(int(v) for v in weights[key].shape) + + +def _agree(stated, derived, what: str) -> None: + """Refuse a config.json claim that the tensors contradict.""" + if stated is not None and _integer(stated, what) != int(derived): + raise ValueError( + f"siglip2 config.json says {what}={stated} but the tensors say {derived}") + + +def _count_layers(weights, prefix: str) -> int: + indices = set() + needle = f"{prefix}.encoder.layers." + for key in weights: + if key.startswith(needle): + indices.add(int(key[len(needle):].split(".", 1)[0])) + if not indices: + raise KeyError(f"siglip2 checkpoint has no {prefix} encoder layers") + if indices != set(range(len(indices))): + raise ValueError(f"siglip2 {prefix} encoder layer indices are not contiguous") + return len(indices) + + +def _tower(weights, config, prefix: str, name: str) -> dict: + stated = config.get(name) or {} + + # fc1 is [intermediate, hidden]; one tensor fixes both widths at once. + intermediate, hidden = _shape(weights, f"{prefix}.encoder.layers.0.mlp.fc1.weight") + _agree(stated.get("hidden_size"), hidden, f"{name}.hidden_size") + _agree(stated.get("intermediate_size"), intermediate, f"{name}.intermediate_size") + + layers = _count_layers(weights, prefix) + _agree(stated.get("num_hidden_layers"), layers, f"{name}.num_hidden_layers") + + heads = _integer(stated.get("num_attention_heads", _REFERENCE_HEADS), + f"{name}.num_attention_heads") + if heads <= 0 or hidden % heads: + raise ValueError(f"siglip2 {name} width {hidden} is not divisible by {heads} heads") + + activation = stated.get("hidden_act", _EXPECTED_ACTIVATION) + if activation != _EXPECTED_ACTIVATION: + # The tanh approximation and the exact GELU agree to about 1e-3, which moves + # the logits; they are not interchangeable. + raise NotImplementedError( + f"siglip2 {name} is qualified for {_EXPECTED_ACTIVATION}, not {activation}") + + return { + "hidden_size": hidden, + "intermediate_size": intermediate, + "num_layers": layers, + "num_heads": heads, + "head_dim": hidden // heads, + "eps": _number(stated.get("layer_norm_eps", _DEFAULT_EPS), f"{name}.layer_norm_eps"), + } + + +def _text(weights, config) -> dict: + text = _tower(weights, config, "text_model", "text_config") + stated = config.get("text_config") or {} + + vocab_size, width = _shape(weights, "text_model.embeddings.token_embedding.weight") + _agree(stated.get("vocab_size"), vocab_size, "text_config.vocab_size") + if width != text["hidden_size"]: + raise ValueError("siglip2 token embedding width disagrees with the encoder width") + text["vocab_size"] = vocab_size + + # The position table is the whole prompt window, and the text tower pools the LAST + # row of that window: its length is a correctness rule, not a capacity. + window, width = _shape(weights, "text_model.embeddings.position_embedding.weight") + _agree(stated.get("max_position_embeddings"), window, "text_config.max_position_embeddings") + if width != text["hidden_size"]: + raise ValueError("siglip2 text position table width disagrees with the encoder width") + text["max_text_len"] = window + + projection, width = _shape(weights, "text_model.head.weight") + _agree(stated.get("projection_size"), projection, "text_config.projection_size") + if width != text["hidden_size"]: + raise ValueError("siglip2 text head input width disagrees with the encoder width") + text["projection_size"] = projection + return text + + +def _preprocessor(model_dir: Path) -> dict: + path = model_dir / "preprocessor_config.json" + if not path.is_file(): + raise FileNotFoundError(f"missing siglip2 image processor config: {path}") + loaded = json.loads(path.read_text()) + + kind = loaded.get("image_processor_type") + if kind is not None and kind not in _PROCESSORS: + raise NotImplementedError(f"siglip2 implements the Siglip2 image processor, not {kind}") + if not loaded.get("do_resize", True): + # NaFlex needs every side to be a whole number of patches. + raise NotImplementedError("siglip2 requires the processor's aspect-preserving resize") + resample = _integer(loaded.get("resample", _BILINEAR), "resample") + if resample != _BILINEAR: + raise NotImplementedError( + f"siglip2 is qualified for Pillow bilinear resize ({_BILINEAR}), not {resample}") + if not loaded.get("do_rescale", True): + raise NotImplementedError("siglip2 requires the processor's 1/255 rescale") + rescale = _number(loaded.get("rescale_factor", _RESCALE), "rescale_factor") + if abs(rescale - _RESCALE) > 1e-12: + raise NotImplementedError(f"siglip2 is qualified for a 1/255 rescale, not {rescale}") + if not loaded.get("do_normalize", True): + raise NotImplementedError("siglip2 requires the processor's mean/std normalization") + + mean = [_number(v, "image_mean") for v in loaded.get("image_mean", _DEFAULT_MEAN)] + std = [_number(v, "image_std") for v in loaded.get("image_std", _DEFAULT_STD)] + if len(mean) != _CHANNELS or len(std) != _CHANNELS: + raise ValueError("siglip2 image statistics must have three channels") + if any(v == 0 for v in std): + raise ValueError("siglip2 image deviation must be nonzero") + + patch = _integer(loaded.get("patch_size", _DEFAULT_PATCH), "patch_size") + max_patches = _integer(loaded.get("max_num_patches", _DEFAULT_MAX_PATCHES), "max_num_patches") + if patch <= 0 or max_patches <= 0: + raise ValueError("siglip2 patch size and patch budget must be positive") + return { + "image_mean": mean, + "image_std": std, + "resample": resample, + "rescale_factor": rescale, + "patch_size": patch, + "max_num_patches": max_patches, + } + + +def _vision(weights, config, processor: dict) -> dict: + vision = _tower(weights, config, "vision_model", "vision_config") + stated = config.get("vision_config") or {} + width = vision["hidden_size"] + + channels = _integer(stated.get("num_channels", _CHANNELS), "vision_config.num_channels") + if channels != _CHANNELS: + raise NotImplementedError(f"siglip2 takes 3-channel images, not {channels}") + + # NaFlex embeds already-flattened patches with a Linear layer. Its input width is + # channels x patch x patch in (row, column, channel) order, so it fixes the patch + # size the processor must cut; the two files are checked against it. + out_features, in_features = _shape(weights, "vision_model.embeddings.patch_embedding.weight") + if out_features != width: + raise ValueError("siglip2 patch embedding width disagrees with the encoder width") + patch = processor["patch_size"] + if in_features != _CHANNELS * patch * patch: + raise ValueError( + f"siglip2 patch embedding takes {in_features} values per patch, not the " + f"{_CHANNELS} x {patch} x {patch} the processor cuts") + _agree(stated.get("patch_size"), patch, "vision_config.patch_size") + vision["patch_size"] = patch + vision["patch_features"] = in_features + + # The position table is square (the reference reshapes it to grid x grid before + # interpolating), and its row count is not the patch budget: the budget is how many + # patches an image may have, the table is resized to whatever grid it gets. + positions, position_width = _shape(weights, "vision_model.embeddings.position_embedding.weight") + if position_width != width: + raise ValueError("siglip2 position table width disagrees with the encoder width") + grid = int(round(positions ** 0.5)) + if grid * grid != positions: + raise NotImplementedError(f"siglip2 needs a square position table, not {positions} rows") + _agree(stated.get("num_patches"), positions, "vision_config.num_patches") + vision["num_positions"] = positions + vision["grid"] = grid + vision["max_num_patches"] = processor["max_num_patches"] + + # The pooling head is a torch MultiheadAttention: its projections arrive packed as + # one [3 * width, width] tensor in q, k, v order. + packed, packed_width = _shape(weights, "vision_model.head.attention.in_proj_weight") + if packed_width != width or packed != 3 * width: + raise ValueError("siglip2 pooling head projection is not a packed QKV tensor") + probe = _shape(weights, "vision_model.head.probe") + if probe != (1, 1, width): + raise ValueError(f"siglip2 pooling probe has shape {probe}, expected (1, 1, {width})") + if stated.get("vision_use_head") is False: + raise NotImplementedError("siglip2 embeds images through the attention-pooling head") + return vision + + +def resolve(model_dir: Path, weights: dict) -> dict: + """Return the geometry both builders and the runtime need.""" + model_dir = Path(model_dir) + config = json.loads((model_dir / "config.json").read_text()) + + architectures = config.get("architectures") + if architectures is not None and "Siglip2Model" not in architectures: + # Siglip2ForImageClassification shares the model type but replaces the + # pooling head and the text tower with a classifier. + raise NotImplementedError(f"siglip2 builds Siglip2Model, not {architectures}") + + processor = _preprocessor(model_dir) + text = _text(weights, config) + vision = _vision(weights, config, processor) + if text["projection_size"] != vision["hidden_size"]: + raise ValueError("siglip2 text and image embeddings have different widths") + return { + "text": text, + "vision": vision, + "image_mean": processor["image_mean"], + "image_std": processor["image_std"], + "resample": processor["resample"], + "rescale_factor": processor["rescale_factor"], + } diff --git a/families/siglip2/encoder_builder.py b/families/siglip2/encoder_builder.py new file mode 100644 index 0000000000..9b048829e1 --- /dev/null +++ b/families/siglip2/encoder_builder.py @@ -0,0 +1,44 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +"""The transformer stack both SigLIP 2 towers share. + +Pre-norm layers: LayerNorm, QKV with bias, an output projection with bias, then a +GELU-tanh MLP, each added back to the residual. The towers differ only in width, +depth and row count. +""" + +from __future__ import annotations + +import numpy as np + +from . import graph as g + + +def _linear(network, hidden, weights, name, dtype): + return g.add_linear(network, hidden, weights[f"{name}.weight"], weights[f"{name}.bias"], + dtype=dtype) + + +def build_layers(network, hidden, weights, prefix, cfg, *, dtype=np.float32): + """Run ``cfg["num_layers"]`` pre-norm encoder layers over rows ``[seq, width]``.""" + for index in range(cfg["num_layers"]): + layer = f"{prefix}.encoder.layers.{index}" + + normed = g.add_layer_norm(network, hidden, weights[f"{layer}.layer_norm1.weight"], + weights[f"{layer}.layer_norm1.bias"], cfg["eps"]) + query, key, value = ( + _linear(network, normed, weights, f"{layer}.self_attn.{name}", dtype) + for name in ("q_proj", "k_proj", "v_proj")) + attention = g.add_attention(network, query, key, value, num_heads=cfg["num_heads"], + head_dim=cfg["head_dim"]) + attention = _linear(network, attention, weights, f"{layer}.self_attn.out_proj", dtype) + hidden = g.add_sum(network, hidden, attention) + + normed = g.add_layer_norm(network, hidden, weights[f"{layer}.layer_norm2.weight"], + weights[f"{layer}.layer_norm2.bias"], cfg["eps"]) + inner = _linear(network, normed, weights, f"{layer}.mlp.fc1", dtype) + inner = g.add_gelu_tanh(network, inner, dtype=dtype) + inner = _linear(network, inner, weights, f"{layer}.mlp.fc2", dtype) + hidden = g.add_sum(network, hidden, inner) + return hidden diff --git a/families/siglip2/graph.py b/families/siglip2/graph.py new file mode 100644 index 0000000000..b7e0305dda --- /dev/null +++ b/families/siglip2/graph.py @@ -0,0 +1,121 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +"""TensorRT graph helpers for SigLIP 2. + +Both towers are pre-norm transformers over a row tensor ``[seq, width]``. The text +window is fixed, but the image row count is the patch count of the request's own +NaFlex grid, so every helper here keeps the row axis symbolic: shapes are taken from +the weights, never from the input, and reshapes infer the row count. + +Two details are load-bearing: + +* the activation is the **tanh approximation** of GELU, not the exact GELU; +* ``add_attention`` lets the query carry a different row count from the keys, + because the vision tower is pooled by attending one learned query row against + every patch. +""" + +from __future__ import annotations + +import numpy as np +import tensorrt as trt + + +def add_constant(network, shape, values, dtype=np.float32): + data = np.ascontiguousarray(np.asarray(values, dtype=dtype).reshape(shape)) + return network.add_constant(shape, data).get_output(0) + + +def add_sum(network, left, right): + return network.add_elementwise(left, right, trt.ElementWiseOperation.SUM).get_output(0) + + +def add_layer_norm(network, inp, gamma, beta, eps): + """LayerNorm over the last axis, spelled out in fp32.""" + axis = len(inp.shape) - 1 + mean = network.add_reduce(inp, trt.ReduceOperation.AVG, 1 << axis, True).get_output(0) + centred = network.add_elementwise(inp, mean, trt.ElementWiseOperation.SUB).get_output(0) + square = network.add_elementwise(centred, centred, trt.ElementWiseOperation.PROD).get_output(0) + variance = network.add_reduce(square, trt.ReduceOperation.AVG, 1 << axis, True).get_output(0) + ones = tuple([1] * len(inp.shape)) + shifted = network.add_elementwise(variance, add_constant(network, ones, np.full((1,), eps)), + trt.ElementWiseOperation.SUM).get_output(0) + deviation = network.add_unary(shifted, trt.UnaryOperation.SQRT).get_output(0) + normed = network.add_elementwise(centred, deviation, trt.ElementWiseOperation.DIV).get_output(0) + width = int(np.asarray(gamma).shape[-1]) + shape = tuple([1] * (len(inp.shape) - 1) + [width]) + scaled = network.add_elementwise(normed, add_constant(network, shape, gamma), + trt.ElementWiseOperation.PROD).get_output(0) + return network.add_elementwise(scaled, add_constant(network, shape, beta), + trt.ElementWiseOperation.SUM).get_output(0) + + +def add_linear(network, inp, weight, bias=None, dtype=np.float32): + """y = x @ W^T + b for rows ``[seq, in]``, matching torch.nn.Linear's layout.""" + weight = np.ascontiguousarray(np.asarray(weight, dtype=dtype)) + constant = add_constant(network, tuple(weight.shape), weight, dtype=dtype) + out = network.add_matrix_multiply(inp, trt.MatrixOperation.NONE, constant, + trt.MatrixOperation.TRANSPOSE).get_output(0) + if bias is None: + return out + bias = np.asarray(bias, dtype=dtype).reshape(1, -1) + return network.add_elementwise(out, add_constant(network, bias.shape, bias, dtype=dtype), + trt.ElementWiseOperation.SUM).get_output(0) + + +def add_gelu_tanh(network, inp, dtype=np.float32): + """``0.5 * x * (1 + tanh(sqrt(2/pi) * (x + 0.044715 * x^3)))``. + + Both towers state ``gelu_pytorch_tanh``. This tanh approximation and the exact + GELU agree to about 1e-3, which the relevance logit notices, so the function is + spelled out rather than left to an activation enum. + """ + ones = tuple([1] * len(inp.shape)) + + def constant(value): + return add_constant(network, ones, np.full((1,), value), dtype=dtype) + + def prod(left, right): + return network.add_elementwise(left, right, trt.ElementWiseOperation.PROD).get_output(0) + + cube = prod(prod(inp, inp), inp) + inner = network.add_elementwise(inp, prod(constant(0.044715), cube), + trt.ElementWiseOperation.SUM).get_output(0) + scaled = prod(constant(np.sqrt(2.0 / np.pi)), inner) + tanh = network.add_activation(scaled, trt.ActivationType.TANH).get_output(0) + gate = network.add_elementwise(constant(1.0), tanh, trt.ElementWiseOperation.SUM).get_output(0) + return prod(prod(constant(0.5), inp), gate) + + +def _to_heads(network, rows, num_heads, head_dim): + """``[seq, width]`` to ``[1, heads, seq, head_dim]`` with the row count inferred.""" + layer = network.add_shuffle(rows) + layer.reshape_dims = (1, -1, num_heads, head_dim) + layer.second_transpose = (0, 2, 1, 3) + return layer.get_output(0) + + +def add_attention(network, query, key, value, *, num_heads, head_dim): + """Unmasked multi-head attention over rows, the query free to be shorter. + + ``query`` is ``[q_seq, width]`` and ``key``/``value`` are ``[kv_seq, width]``. No + mask: the text tower is bidirectional over its whole padded window, and the image + rows are exactly the request's patches (the reference pads them to the patch budget + and masks the padding out, which leaves the same function). + """ + scores = network.add_matrix_multiply( + _to_heads(network, query, num_heads, head_dim), trt.MatrixOperation.NONE, + _to_heads(network, key, num_heads, head_dim), trt.MatrixOperation.TRANSPOSE).get_output(0) + scale = add_constant(network, (1, 1, 1, 1), np.full((1,), 1.0 / np.sqrt(head_dim)), + dtype=np.dtype(trt.nptype(scores.dtype))) + scores = network.add_elementwise(scores, scale, trt.ElementWiseOperation.PROD).get_output(0) + weights = network.add_softmax(scores) + weights.axes = 1 << 3 + context = network.add_matrix_multiply( + weights.get_output(0), trt.MatrixOperation.NONE, + _to_heads(network, value, num_heads, head_dim), trt.MatrixOperation.NONE).get_output(0) + back = network.add_shuffle(context) + back.first_transpose = (0, 2, 1, 3) + back.reshape_dims = (-1, num_heads * head_dim) + return back.get_output(0) diff --git a/families/siglip2/model.py b/families/siglip2/model.py new file mode 100644 index 0000000000..6c3e9ba7a1 --- /dev/null +++ b/families/siglip2/model.py @@ -0,0 +1,383 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +"""Build a SigLIP 2 NaFlex bundle. + +The bundle carries **two** engines, because SigLIP 2 is two towers that meet only at a +dot product: embedding an image runs the vision engine, embedding a text runs the text +engine, and scoring a pair runs both. + +The vision engine takes one image's patches with the patch count dynamic up to the +processor's budget, plus the taps that resample the position table to the image's +grid; the runtime owns the NaFlex resize, the patch cut and those taps. Neither engine +normalises its output or applies the scale and bias: the runtime owns the L2 +normalisation, ``exp(logit_scale)`` and ``logit_bias``, so that what comes out of an +engine stays comparable with what the reference returns. +""" + +from __future__ import annotations + +import json +import math +from pathlib import Path + +import numpy as np +import tensorrt as trt + +from . import config as config_module, text_builder, vision_builder + +_SUPPORTED_TASKS = ("image_to_embedding", "text_to_embedding", "text_image_to_relevance") +_SENTENCE_PIECE_SPACE = "▁" + + +def _open_checkpoint(model_dir: Path) -> dict: + """Load the safetensors checkpoint this family publishes.""" + try: + from safetensors.numpy import load_file + except ImportError as error: + raise RuntimeError("This family requires safetensors in the build environment") from error + + path = Path(model_dir) / "model.safetensors" + if not path.is_file(): + raise FileNotFoundError(f"Required safetensors checkpoint is missing: {path}") + return dict(load_file(str(path))) + + +def _require_weights(weights: dict) -> None: + required = ( + "logit_scale", + "logit_bias", + "text_model.embeddings.token_embedding.weight", + "text_model.embeddings.position_embedding.weight", + "text_model.final_layer_norm.weight", + "text_model.head.weight", + "vision_model.embeddings.patch_embedding.weight", + "vision_model.embeddings.patch_embedding.bias", + "vision_model.embeddings.position_embedding.weight", + "vision_model.post_layernorm.weight", + "vision_model.head.probe", + "vision_model.head.attention.in_proj_weight", + "vision_model.head.attention.in_proj_bias", + ) + missing = [key for key in required if key not in weights] + if missing: + raise KeyError("siglip2 checkpoint is missing expected tensors: " + ", ".join(missing)) + for key, value in weights.items(): + if np.asarray(value).dtype != np.float32: + raise NotImplementedError( + f"siglip2 is qualified for the float32 checkpoint; {key} is {value.dtype}") + + +_ADDED_TOKEN_OPTIONS = ("single_word", "lstrip", "rstrip", "normalized") + + +def _added_tokens(tokenizer: dict) -> list[dict]: + """Return the added tokens, each checked the way the runtime checks it on load. + + The runtime matches an added token as it is, anywhere in the raw text, and gives it + the record's id. The reference does the same only for a token without matching + options, and gives a token that is in the vocabulary the vocabulary's id. + """ + entries = tokenizer.get("added_tokens", []) + if not isinstance(entries, list): + raise ValueError("siglip2 tokenizer added_tokens must be a list") + vocab = tokenizer["model"]["vocab"] + for entry in entries: + if not isinstance(entry, dict) or not isinstance(entry.get("content"), str): + raise ValueError(f"siglip2 added token has no string content: {entry!r}") + content, token_id = entry["content"], entry.get("id") + if type(token_id) is not int or not 0 <= token_id <= 2**31 - 1: + raise ValueError(f"siglip2 added token {content!r} has no valid id") + for flag in (*_ADDED_TOKEN_OPTIONS, "special"): + if type(entry.get(flag)) is not bool: + raise ValueError(f"siglip2 added token {content!r} has no boolean {flag}") + options = [flag for flag in _ADDED_TOKEN_OPTIONS if entry[flag]] + if options: + raise NotImplementedError( + f"siglip2 matches added tokens as they are; {content!r} sets {', '.join(options)}") + if content not in vocab or type(vocab[content]) is not int or vocab[content] != token_id: + raise NotImplementedError( + f"siglip2 added token {content!r} is not the vocabulary entry with id {token_id}") + return entries + + +def _check_bpe_options(model: dict) -> None: + # The runtime merges the checkpoint's way: no dropout, no subword prefix or suffix, and + # also a word that is a vocabulary entry goes through the merges. + options = {key: model[key] for key in ("dropout", "continuing_subword_prefix", "end_of_word_suffix") + if model.get(key) is not None} + if model.get("ignore_merges", False) is not False: + options["ignore_merges"] = model["ignore_merges"] + if options: + raise NotImplementedError(f"siglip2 does not reproduce the BPE options {options}") + + +def _check_vocabulary(vocab: dict) -> None: + # The runtime keeps the vocabulary as ids 0..N-1 and encodes every space as U+2581. + size = len(vocab) + for token, token_id in vocab.items(): + if type(token_id) is not int: + raise ValueError(f"siglip2 vocabulary id of {token!r} is not an integer: {token_id!r}") + if not 0 <= token_id < size: + raise NotImplementedError( + f"siglip2 vocabulary ids must be integers in [0, {size}); {token!r} has {token_id}") + if _SENTENCE_PIECE_SPACE not in vocab: + raise NotImplementedError("siglip2 vocabulary has no U+2581 space marker") + + +def _check_merges(model: dict) -> None: + # Like the reference, a rule is one pair (two strings, or one string with one space) whose + # operands and result are vocabulary entries; the reference refuses any other table. + merges, vocab = model.get("merges"), model["vocab"] + if not isinstance(merges, list): + raise ValueError("siglip2 tokenizer model.merges must be a list") + for index, merge in enumerate(merges): + pair = merge.split(" ") if isinstance(merge, str) else merge + if not (isinstance(pair, list) and len(pair) == 2 and all(isinstance(p, str) for p in pair)): + raise ValueError(f"siglip2 tokenizer merge {index} is not one pair: {merge!r}") + left, right = pair + for part in pair: + if part not in vocab: + raise ValueError( + f"siglip2 tokenizer merge {left} {right}: {part} is not in the vocabulary") + if left + right not in vocab: + raise ValueError(f"siglip2 tokenizer merge {left} {right} makes {left + right}, " + "which is not in the vocabulary") + + +def _check_byte_fallback(vocab: dict) -> None: + # The reference falls back to bytes all or nothing (the unknown token otherwise), and + # the runtime has no unknown-token path: every byte that a character outside the + # vocabulary can need must have its token. An ASCII byte needs none when its character + # is a vocabulary entry itself (this checkpoint's tab). + missing = [f"<0x{byte:02X}>" for byte in range(256) + if f"<0x{byte:02X}>" not in vocab and not (byte < 0x80 and chr(byte) in vocab)] + if missing: + raise NotImplementedError( + "siglip2 byte fallback needs a token for every byte; missing " + ", ".join(missing[:4])) + + +def _token_id(tokenizer: dict, token: str) -> int: + for entry in tokenizer.get("added_tokens", []): + if entry.get("content") == token: + return entry["id"] + vocab = tokenizer["model"]["vocab"] + if token in vocab and type(vocab[token]) is int: + return vocab[token] + raise ValueError(f"siglip2 token {token!r} is not in the vocabulary") + + +def _named_token(config: dict, name: str) -> str: + token = config.get(name) + if isinstance(token, dict): + token = token.get("content") + if not token: + raise ValueError(f"siglip2 tokenizer declares no {name}") + return str(token) + + +def _tokenizer_contract(model_dir: Path, embedding_rows: int | None = None) -> int: + """Check the tokenizer is the one the runtime reproduces; return the pad id. + + The runtime tokenizer reproduces a SentencePiece-style BPE with byte fallback whose + only normalisation is the space marker, with no pre-tokenizer, and whose template + appends one end token. That is what this checkpoint ships and what the reference + tokenizer runs: it does not lowercase (``do_lower_case`` in + ``tokenizer_config.json`` is not applied by the reference), so neither does the + runtime. The checkpoint's files also never need what the runtime leaves out: no BPE + dropout, subword prefix or suffix, or skipped merges; vocabulary ids 0..N-1 with the + U+2581 marker; the byte fallback never needs the unknown token, no added token sets a + matching option or an id other than its vocabulary id, and the end token expands to its + own id alone. Anything + else is refused here rather than tokenised differently; the runtime checks the same + on load. + """ + path = model_dir / "tokenizer.json" + if not path.is_file(): + raise FileNotFoundError(f"missing siglip2 tokenizer: {path}") + tokenizer = json.loads(path.read_text(encoding="utf-8")) + model = tokenizer.get("model", {}) + if model.get("type") != "BPE" or model.get("byte_fallback") is not True: + raise NotImplementedError( + "siglip2 is qualified for a byte-fallback BPE tokenizer, not " + f"{model.get('type')!r}") + if not isinstance(model.get("vocab"), dict): + raise ValueError("siglip2 tokenizer model.vocab must be an object") + expected_normalizer = {"type": "Replace", "pattern": {"String": " "}, + "content": _SENTENCE_PIECE_SPACE} + if tokenizer.get("normalizer") != expected_normalizer: + raise NotImplementedError( + "siglip2 is qualified for a tokenizer whose only normalizer replaces spaces " + f"with U+2581, not {tokenizer.get('normalizer')!r}") + if tokenizer.get("pre_tokenizer") is not None: + raise NotImplementedError("siglip2 is qualified for a tokenizer without a pre-tokenizer") + template = (tokenizer.get("post_processor") or {}).get("single") or [] + if (tokenizer.get("post_processor") or {}).get("type") != "TemplateProcessing" or not all( + isinstance(item, dict) and len(item) == 1 for item in template) or [ + next(iter(item)) for item in template] != ["Sequence", "SpecialToken"]: + # The runtime truncates a long prompt to the window by keeping its head and + # re-appending the end token, which is what the reference's truncation does + # with exactly this template. + raise NotImplementedError( + "siglip2 is qualified for a template that appends one end token") + _check_bpe_options(model) + _check_vocabulary(model["vocab"]) + if embedding_rows is not None and len(model["vocab"]) > embedding_rows: + # The text engine gathers each id from the checkpoint's embedding rows without a range + # check, so every id the tokenizer can give must have its row. + raise ValueError(f"siglip2 tokenizer has {len(model['vocab'])} tokens but the text " + f"embedding table has {embedding_rows} rows") + _check_merges(model) + _check_byte_fallback(model["vocab"]) + added_tokens = _added_tokens(tokenizer) + + config_path = model_dir / "tokenizer_config.json" + if not config_path.is_file(): + raise FileNotFoundError(f"missing siglip2 tokenizer config: {config_path}") + tokenizer_config = json.loads(config_path.read_text(encoding="utf-8")) + eos_token = _named_token(tokenizer_config, "eos_token") + if template[1]["SpecialToken"].get("id") != eos_token: + raise NotImplementedError("siglip2 tokenizer template must append the end token") + eos_id = _token_id(tokenizer, eos_token) + # The runtime resolves template tokens only among the added tokens marked special; an + # end token that is not marked would be dropped from every prompt. + if not any(entry["content"] == eos_token and entry["special"] for entry in added_tokens): + raise NotImplementedError( + "siglip2 tokenizer must register its end token as a special token") + # The template appends the ids its special_tokens entry lists; the runtime appends the + # end token's one id, and keeps a window's last slot for it. + special_tokens = tokenizer["post_processor"].get("special_tokens") + entry = special_tokens.get(eos_token) if isinstance(special_tokens, dict) else None + expansion = entry.get("ids") if isinstance(entry, dict) else None + if not (isinstance(expansion, list) and len(expansion) == 1 + and type(expansion[0]) is int and expansion[0] == eos_id): + raise NotImplementedError( + f"siglip2 tokenizer template must expand {eos_token!r} to exactly its id {eos_id}") + return _token_id(tokenizer, _named_token(tokenizer_config, "pad_token")) + + +def _builder(verbose): + 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)) + config = builder.create_builder_config() + config.builder_optimization_level = 3 + # TF32 caps a matmul graph near 1e-4 relative error by default, which would hide + # real graph error behind a plausible number. + config.clear_flag(trt.BuilderFlag.TF32) + return builder, network, config + + +def _serialize(builder, network, config, what): + plan = builder.build_serialized_network(network, config) + if plan is None: + raise RuntimeError(f"siglip2 {what} engine build failed") + return bytes(plan) + + +def build_vision_engine(weights, cfg, *, verbose=False) -> bytes: + builder, network, config = _builder(verbose) + vision = cfg["vision"] + budget = vision["max_num_patches"] + patches = network.add_input("pixel_values", trt.float32, (-1, vision["patch_features"])) + taps = network.add_input("position_weights", trt.float32, (-1, vision["num_positions"])) + profile = builder.create_optimization_profile() + profile.set_shape("pixel_values", (1, vision["patch_features"]), + (budget, vision["patch_features"]), (budget, vision["patch_features"])) + profile.set_shape("position_weights", (1, vision["num_positions"]), + (budget, vision["num_positions"]), (budget, vision["num_positions"])) + config.add_optimization_profile(profile) + embeds = vision_builder.build_vision_tower(network, patches, taps, weights, vision, + dtype=np.float32) + embeds.name = "image_embeds" + network.mark_output(embeds) + return _serialize(builder, network, config, "vision") + + +def build_text_engine(weights, cfg, *, verbose=False) -> bytes: + builder, network, config = _builder(verbose) + text = cfg["text"] + input_ids = network.add_input("input_ids", trt.int32, (text["max_text_len"],)) + embeds = text_builder.build_text_tower(network, input_ids, weights, text, dtype=np.float32) + embeds.name = "text_embeds" + network.mark_output(embeds) + return _serialize(builder, network, config, "text") + + +def build(request, writer) -> None: + """Build one SigLIP 2 NaFlex bundle.""" + if request.task not in _SUPPORTED_TASKS: + raise ValueError("siglip2 supports only task=" + ", ".join(_SUPPORTED_TASKS)) + if request.backend != "trt": + raise ValueError("siglip2 supports only backend=trt") + if request.dynamic_kv_cache: + raise NotImplementedError("siglip2 does not support dynamic_kv_cache") + if request.max_batch_size != 1: + raise NotImplementedError("siglip2 does not support max_batch_size") + if request.tensor_parallel_size != 1: + raise NotImplementedError("siglip2 does not support tensor parallelism") + if request.context_parallel_size != 1: + raise NotImplementedError("siglip2 does not support context parallelism") + if request.video_num_frames is not None: + raise NotImplementedError("siglip2 does not support video_num_frames") + if request.quantization not in {None, "none"}: + raise NotImplementedError( + f"siglip2 does not support quantization; got {request.quantization!r}") + if request.fp32_layers: + raise NotImplementedError("siglip2 does not support mixed-precision layers") + if request.mtp_seq_len is not None: + raise NotImplementedError("siglip2 does not support MTP speculative decoding") + if request.image_height is not None or request.image_width is not None: + # NaFlex resizes every image to its own aspect-preserving grid within the + # patch budget; there is no fixed input size to build for. + raise NotImplementedError("siglip2 sizes each image itself; image_height/width are not used") + + # fp32, the checkpoint's own precision. A reduced-precision engine is not + # qualified for this family. + precision = str(request.precision).lower() + if precision != "fp32": + raise NotImplementedError( + f"siglip2 builds fp32 only; {precision} is not qualified for this family") + + model_dir = Path(request.model_dir) + weights = _open_checkpoint(model_dir) + _require_weights(weights) + cfg = config_module.resolve(model_dir, weights) + vision, text = cfg["vision"], cfg["text"] + + if request.max_sequence_length is not None: + if int(request.max_sequence_length) != text["max_text_len"]: + # Not a capacity: the pooled row is the last row of this window. + raise NotImplementedError( + "siglip2 prompt length is fixed at the checkpoint's window of " + f"{text['max_text_len']}") + + pad_token_id = _tokenizer_contract(model_dir, text["vocab_size"]) + + # Stored the way the reference applies them: the scale in log space, used as + # exp() of it, and the bias added after. + logit_scale = float(math.exp(float(np.asarray(weights["logit_scale"]).reshape(())))) + logit_bias = float(np.asarray(weights["logit_bias"]).reshape(())) + + writer.set_header(family="siglip2", task=request.task, backend=request.backend) + writer.add_bytes("vision.plan", build_vision_engine(weights, cfg, + verbose=bool(request.verbose))) + writer.add_bytes("text.plan", build_text_engine(weights, cfg, verbose=bool(request.verbose))) + writer.add_bytes("tokenizer.json", (model_dir / "tokenizer.json").read_bytes()) + writer.add_json( + "runtime.json", + { + "patch_size": vision["patch_size"], + "max_num_patches": vision["max_num_patches"], + "position_grid": vision["grid"], + "image_mean": cfg["image_mean"], + "image_std": cfg["image_std"], + "resample": cfg["resample"], + "rescale_factor": cfg["rescale_factor"], + "max_text_len": text["max_text_len"], + "pad_token_id": pad_token_id, + "embedding_dim": text["projection_size"], + "logit_scale": logit_scale, + "logit_bias": logit_bias, + }, + ) diff --git a/families/siglip2/requirements.txt b/families/siglip2/requirements.txt new file mode 100644 index 0000000000..d14b8f4a0c --- /dev/null +++ b/families/siglip2/requirements.txt @@ -0,0 +1,5 @@ +# Reference implementation this family is measured against. +transformers==5.2.0 +# The runtime reproduces Pillow 13's bilinear resize; Pillow 12 orders the two resize +# passes differently and lands one 8-bit step away on some images. +pillow==13.0.0 diff --git a/families/siglip2/runtime/CMakeLists.txt b/families/siglip2/runtime/CMakeLists.txt new file mode 100644 index 0000000000..5f2ee36ec0 --- /dev/null +++ b/families/siglip2/runtime/CMakeLists.txt @@ -0,0 +1,70 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +add_library(trtmc_model_siglip2 SHARED + bpe_tokenizer.cpp + naflex_preprocess.cpp + pipeline.cpp + plugin.cpp +) + +target_include_directories(trtmc_model_siglip2 + PRIVATE + ${PROJECT_SOURCE_DIR} + ${PROJECT_SOURCE_DIR}/core/runtime/include +) +target_include_directories(trtmc_model_siglip2 SYSTEM PRIVATE + ${TRTMC_CUDA_INCLUDE_DIR} +) +target_link_libraries(trtmc_model_siglip2 PRIVATE + trtmc_core + nlohmann_json::nlohmann_json + ${TRTMC_CUDART_LIBRARY} +) +target_compile_options(trtmc_model_siglip2 PRIVATE + "$<$:-Wall;-Wextra;-Wpedantic>" +) +set_target_properties(trtmc_model_siglip2 PROPERTIES + LIBRARY_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}" + BUILD_RPATH "\$ORIGIN" + INSTALL_RPATH "\$ORIGIN" +) +install(TARGETS trtmc_model_siglip2 + LIBRARY DESTINATION ${CMAKE_INSTALL_LIBDIR} +) + +if(TRTMC_BUILD_TESTS) + foreach(_test naflex_preprocess pipeline tokenizer) + add_executable(test_siglip2_${_test} + ${PROJECT_SOURCE_DIR}/families/siglip2/tests/cpp/test_${_test}.cpp + ) + target_include_directories(test_siglip2_${_test} PRIVATE + ${PROJECT_SOURCE_DIR} + ${PROJECT_SOURCE_DIR}/core/runtime/include + ) + target_include_directories(test_siglip2_${_test} SYSTEM PRIVATE + ${TRTMC_CUDA_INCLUDE_DIR} + ) + target_link_libraries(test_siglip2_${_test} PRIVATE + trtmc_model_siglip2 + trtmc_core + ${TRTMC_CUDART_LIBRARY} + ) + target_compile_options(test_siglip2_${_test} PRIVATE -Wall -Wextra -Wpedantic) + add_test(NAME test_siglip2_${_test} COMMAND test_siglip2_${_test}) + endforeach() + # Its miniature tokenizer.json variants are built as JSON values. + target_link_libraries(test_siglip2_tokenizer PRIVATE nlohmann_json::nlohmann_json) + + # Host preprocessing of one raw RGB image, written out for the exact parity check + # against the reference processor in tests/test_e2e.py, which builds it by name. + add_executable(siglip2_preprocess_dump + ${PROJECT_SOURCE_DIR}/families/siglip2/tests/cpp/preprocess_dump.cpp + ) + target_include_directories(siglip2_preprocess_dump PRIVATE ${PROJECT_SOURCE_DIR}) + target_link_libraries(siglip2_preprocess_dump PRIVATE trtmc_model_siglip2) + target_compile_options(siglip2_preprocess_dump PRIVATE -Wall -Wextra -Wpedantic) + set_target_properties(siglip2_preprocess_dump PROPERTIES + RUNTIME_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}" + ) +endif() diff --git a/families/siglip2/runtime/bpe_tokenizer.cpp b/families/siglip2/runtime/bpe_tokenizer.cpp new file mode 100644 index 0000000000..99100ebfa4 --- /dev/null +++ b/families/siglip2/runtime/bpe_tokenizer.cpp @@ -0,0 +1,1462 @@ +/* + * SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. + * SPDX-License-Identifier: Apache-2.0 + */ + +#include "families/siglip2/runtime/tokenizer.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace trtmc::siglip2 { +namespace { + +// ─── UTF-8 helpers ─── + +inline std::string utf32_to_utf8(char32_t cp) { + std::string r; + if (cp <= 0x7F) { + r.push_back(static_cast(cp)); + } else if (cp <= 0x7FF) { + r.push_back(static_cast(0xC0 | ((cp >> 6) & 0x1F))); + r.push_back(static_cast(0x80 | (cp & 0x3F))); + } else if (cp <= 0xFFFF) { + r.push_back(static_cast(0xE0 | ((cp >> 12) & 0x0F))); + r.push_back(static_cast(0x80 | ((cp >> 6) & 0x3F))); + r.push_back(static_cast(0x80 | (cp & 0x3F))); + } else if (cp <= 0x10FFFF) { + r.push_back(static_cast(0xF0 | ((cp >> 18) & 0x07))); + r.push_back(static_cast(0x80 | ((cp >> 12) & 0x3F))); + r.push_back(static_cast(0x80 | ((cp >> 6) & 0x3F))); + r.push_back(static_cast(0x80 | (cp & 0x3F))); + } + return r; +} + +inline bool is_continuation(char byte) { + return (static_cast(byte) & 0xC0) == 0x80; +} + +// Read one UTF-8 codepoint from raw bytes, advance ptr. Returns 0xFFFD on error. The bounds +// are checked on the remaining length, so no pointer past the end of the text is formed. A +// lead byte without all its continuation bytes is one byte of its own, so the bytes after it +// are read again: a tab or a letter there keeps its own token. +inline char32_t read_utf8(const char*& p, const char* end) { + if (p >= end) + return 0xFFFD; + unsigned char c = static_cast(*p); + if (c < 0x80) { + ++p; + return c; + } + if ((c & 0xE0) == 0xC0 && end - p > 1 && is_continuation(p[1])) { + char32_t cp = + (static_cast(c & 0x1F) << 6) | (static_cast(p[1]) & 0x3F); + p += 2; + return cp; + } + if ((c & 0xF0) == 0xE0 && end - p > 2 && is_continuation(p[1]) && is_continuation(p[2])) { + char32_t cp = (static_cast(c & 0x0F) << 12) | + (static_cast(static_cast(p[1]) & 0x3F) << 6) | + (static_cast(p[2]) & 0x3F); + p += 3; + return cp; + } + if ((c & 0xF8) == 0xF0 && end - p > 3 && is_continuation(p[1]) && is_continuation(p[2]) && + is_continuation(p[3])) { + char32_t cp = (static_cast(c & 0x07) << 18) | + (static_cast(static_cast(p[1]) & 0x3F) << 12) | + (static_cast(static_cast(p[2]) & 0x3F) << 6) | + (static_cast(p[3]) & 0x3F); + p += 4; + return cp; + } + ++p; + return 0xFFFD; +} + +// ─── GPT-2 byte encoder: byte value -> Unicode codepoint ─── + +struct ByteEncoderTables { + // byte -> UTF-8 encoded string (precomputed for speed) + std::string byte_to_utf8[256]; + + ByteEncoderTables() { + // GPT-2 byte encoder: printable bytes map to themselves, + // others map to 256+ to avoid control chars. + bool direct[256] = {}; + for (int b = 33; b <= 126; ++b) + direct[b] = true; // !"#$...~ + for (int b = 161; b <= 172; ++b) + direct[b] = true; // non-breaking space area + for (int b = 174; b <= 255; ++b) + direct[b] = true; // extended latin + + int n = 0; + for (int b = 0; b < 256; ++b) { + char32_t cp = direct[b] ? static_cast(b) : static_cast(256 + n++); + byte_to_utf8[b] = utf32_to_utf8(cp); + } + } +}; + +static const ByteEncoderTables& byte_tables() { + static ByteEncoderTables tables; + return tables; +} + +// ─── Hand-written BPE pre-tokenizer ─── +// +// Supports two regex variants: +// +// GPT-2 (used by GPT-2, Falcon, OPT): +// 'contractions| ?\p{L}+| ?\p{N}+| ?[^\s\p{L}\p{N}]+|\s+(?!\S)|\s+ +// +// Qwen3 (used by Qwen3, LLaMA-3, Mistral, Phi): +// (?i:contractions)|[^\r\n\p{L}\p{N}]?\p{L}+|\p{N}| +// ?[^\s\p{L}\p{N}]+[\r\n]*|\s*[\r\n]+|\s+(?!\S)|\s+ +// +// Key differences: Qwen3 allows any non-CR/LF/letter/digit as optional prefix before +// letters, matches single digits, and has explicit newline handling. + +namespace pretok { + +enum class Variant { kGemma, kQwen3, kBloom, kDeepSeek, kClip }; + +// ── Character classification ── + +struct UnicodeRange { + char32_t lo, hi; +}; + +constexpr UnicodeRange kLetterRanges[] = { + {'A', 'Z'}, {'a', 'z'}, {0xB5, 0xB5}, // µ (micro sign, treated as letter) + {0xC0, 0xD6}, {0xD8, 0xF6}, {0xF8, 0x1BA}, // Latin-1 + Extended A/B + {0x1BC, 0x1BF}, {0x1C4, 0x293}, {0x295, 0x2AF}, // Latin Extended B cont. + {0x370, 0x373}, {0x376, 0x377}, {0x37B, 0x37D}, {0x37F, 0x37F}, // Greek + {0x386, 0x386}, {0x388, 0x38A}, {0x38C, 0x38C}, {0x38E, 0x3A1}, + {0x3A3, 0x3F5}, {0x3F7, 0x481}, {0x48A, 0x52F}, // Greek + Cyrillic + {0x531, 0x556}, {0x559, 0x559}, // Armenian + {0x560, 0x588}, // Armenian lowercase + {0x600, 0x6FF}, // Arabic + {0x900, 0x97F}, // Devanagari + {0xE00, 0xE7F}, // Thai + {0x10A0, 0x10C5}, // Georgian + {0x13A0, 0x13F5}, // Cherokee + {0x1C90, 0x1CBA}, {0x1CBD, 0x1CBF}, // Georgian Extended + {0x1D00, 0x1D2B}, {0x1D6B, 0x1D77}, {0x1D79, 0x1D9A}, // Phonetic Extensions + {0x1E00, 0x1F15}, {0x1F18, 0x1F1D}, {0x1F20, 0x1F45}, // Latin Ext. Additional + Greek Ext. + {0x2C00, 0x2C5F}, // Glagolitic + {0x3040, 0x309F}, // Hiragana + {0x30A0, 0x30FF}, // Katakana + {0x3400, 0x4DBF}, // CJK Extension A + {0x4E00, 0x9FFF}, // CJK Unified Ideographs + {0xAC00, 0xD7AF}, // Hangul Syllables + {0xFB00, 0xFDFF}, // Alphabetic Presentation Forms + Arabic Forms + {0x10000, 0x1007F}, // Linear B Syllabary +}; + +inline bool is_letter(char32_t cp) { + for (const auto& r : kLetterRanges) { + if (cp >= r.lo && cp <= r.hi) + return true; + } + return false; +} + +inline bool is_digit(char32_t cp) { + return (cp >= '0' && cp <= '9'); +} + +inline bool is_whitespace(char32_t cp) { + return cp == ' ' || cp == '\t' || cp == '\n' || cp == '\r' || cp == 0x0B || cp == 0x0C // VT, FF + || cp == 0xA0 // non-breaking space + || cp == 0x2000 || cp == 0x200A // en space through hair space + || cp == 0x3000; // ideographic space +} + +// BLOOM punctuation set: .,!?... +constexpr char32_t kBloomPunct[] = { + '.', ',', '!', '?', + 0x2026, // ellipsis + 0x3002, // ideographic full stop + 0xFF0C, // fullwidth comma + 0x3001, // ideographic comma + 0x0964, // Devanagari danda + 0x06D4, // Arabic full stop + 0x060C, // Arabic comma +}; + +inline bool is_bloom_punct(char32_t cp) { + for (auto c : kBloomPunct) { + if (cp == c) + return true; + } + return false; +} + +inline bool is_newline(char32_t cp) { + return cp == '\n' || cp == '\r'; +} + +// Is this char a valid optional prefix before a word? +// GPT-2/BLOOM: only space (0x20) +// Qwen3: any char except CR, LF, letter, digit +// DeepSeek: any whitespace (\s?) +inline bool is_prefix(char32_t cp, Variant v) { + if (v == Variant::kClip) { + return false; + } + if (v == Variant::kQwen3) { + return !is_newline(cp) && !is_letter(cp) && !is_digit(cp); + } + if (v == Variant::kDeepSeek) { + return is_whitespace(cp); + } + return cp == ' '; +} + +// BLOOM word char: not whitespace and not BLOOM punctuation +inline bool is_bloom_word_char(char32_t cp) { + // The serialized regex is `[^(\s|[.,!?…。,、।۔،])]`. Parentheses and + // the pipe are literal members of that negated character class. + return !is_whitespace(cp) && !is_bloom_punct(cp) && cp != '(' && cp != ')' && cp != '|'; +} + +// ── Scanning helpers (advance pointer past matching chars) ── + +inline void scan_letters(const char*& p, const char* end) { + while (p < end) { + const char* peek = p; + if (!is_letter(read_utf8(peek, end))) + break; + p = peek; + } +} + +inline void scan_digits(const char*& p, const char* end, int max_group = 0) { + int count = 0; + while (p < end) { + if (max_group > 0 && count >= max_group) + break; + const char* peek = p; + if (!is_digit(read_utf8(peek, end))) + break; + p = peek; + ++count; + } +} + +inline void scan_others(const char*& p, const char* end) { + while (p < end) { + const char* peek = p; + char32_t nc = read_utf8(peek, end); + if (is_whitespace(nc) || is_letter(nc) || is_digit(nc)) + break; + p = peek; + } +} + +inline void scan_newlines(const char*& p, const char* end) { + while (p < end) { + const char* peek = p; + if (!is_newline(read_utf8(peek, end))) + break; + p = peek; + } +} + +inline void scan_all_whitespace(const char*& p, const char* end) { + while (p < end) { + const char* peek = p; + if (!is_whitespace(read_utf8(peek, end))) + break; + p = peek; + } +} + +// Qwen3 regex branch: \s*[\r\n]+ +// Consume any leading whitespace up to the first newline, then consume the +// contiguous newline run itself, but stop before whitespace that follows the +// last newline. +inline void scan_qwen3_newline_chunk(char32_t first_cp, const char*& p, const char* end) { + bool saw_newline = is_newline(first_cp); + while (p < end) { + const char* peek = p; + char32_t nc = read_utf8(peek, end); + if (!saw_newline) { + if (is_newline(nc)) { + saw_newline = true; + p = peek; + continue; + } + if (is_whitespace(nc)) { + p = peek; + continue; + } + break; + } + if (!is_newline(nc)) + break; + p = peek; + } +} + +inline void scan_bloom_words(const char*& p, const char* end) { + while (p < end) { + const char* peek = p; + if (!is_bloom_word_char(read_utf8(peek, end))) + break; + p = peek; + } +} + +// Emit whitespace run, leaving last ws char for next token's optional prefix +inline void emit_whitespace_leave_last(const char*& p, const char* end, const char* start, + std::vector& result) { + const char* last_ws_start = start; + while (p < end) { + const char* peek = p; + char32_t nc = read_utf8(peek, end); + if (!is_whitespace(nc)) + break; + last_ws_start = p; + p = peek; + } + if (p < end && last_ws_start > start) { + p = last_ws_start; + } + result.emplace_back(start, p); +} + +// ── Contraction matching ── + +inline bool is_two_char_contraction(char c1, char c2) { + return (c1 == 'r' && c2 == 'e') || (c1 == 'v' && c2 == 'e') || (c1 == 'l' && c2 == 'l'); +} + +// Returns length of contraction suffix after apostrophe ('s 't 'm 'd 're 've 'll) +inline int match_contraction_suffix(const char* p, const char* end) { + if (p >= end) + return 0; + char c = *p; + if (c == 's' || c == 't' || c == 'm' || c == 'd') + return 1; + if (p + 1 < end && is_two_char_contraction(c, p[1])) + return 2; + return 0; +} + +// ── GPT-2/Qwen3 pre-tokenize dispatch helpers ── + +// Handle apostrophe: either contraction or "other" chars run +inline bool try_contraction(char32_t cp, const char*& p, const char* end, const char* start, + std::vector& result) { + if (cp != '\'') + return false; + int suffix = match_contraction_suffix(p, end); + if (suffix > 0) { + p += suffix; + } else { + scan_others(p, end); + } + result.emplace_back(start, p); + return true; +} + +// Handle optional prefix + letter/digit/other run +inline bool try_prefix_run(char32_t cp, const char*& p, const char* end, const char* start, + Variant variant, std::vector& result) { + if (!is_prefix(cp, variant) || p >= end) + return false; + const char* after_prefix = p; + char32_t next_cp = read_utf8(p, end); + + if (is_letter(next_cp)) { + scan_letters(p, end); + result.emplace_back(start, p); + return true; + } + if (is_digit(next_cp)) { + // The regex prefix [^\r\n\p{L}\p{N}]? only applies before \p{L}+ (letters). + // Digits are matched by standalone \p{N} — no prefix. Back up so the + // digit is handled by try_simple_run instead. + if (variant == Variant::kQwen3) { + p = after_prefix; + return false; + } + scan_digits(p, end); + result.emplace_back(start, p); + return true; + } + if (!is_whitespace(next_cp)) { + scan_others(p, end); + if (variant == Variant::kQwen3) + scan_newlines(p, end); + result.emplace_back(start, p); + return true; + } + // Prefix followed by whitespace — back up, let whitespace handler deal with it + p = after_prefix; + return false; +} + +// Check if a whitespace run contains any newline character +inline bool has_newline_in_ws(char32_t first_cp, const char* p, const char* end) { + if (is_newline(first_cp)) + return true; + const char* scan = p; + while (scan < end) { + const char* peek = scan; + char32_t nc = read_utf8(peek, end); + if (!is_whitespace(nc)) + break; + if (is_newline(nc)) + return true; + scan = peek; + } + return false; +} + +// Handle whitespace (Qwen3 newline sequences + general whitespace) +inline bool try_whitespace_run(char32_t cp, const char*& p, const char* end, const char* start, + Variant variant, std::vector& result) { + if (!is_whitespace(cp)) + return false; + + // kClip is selected only for CLIP's Removed + inverted Split contract, + // which retains regex matches and removes the gaps. Whitespace therefore + // never reaches ByteLevel. + if (variant == Variant::kClip) { + scan_all_whitespace(p, end); + return true; + } + + // Qwen3: \s*[\r\n]+ — newline sequences take priority + if (variant == Variant::kQwen3 && has_newline_in_ws(cp, p, end)) { + scan_qwen3_newline_chunk(cp, p, end); + result.emplace_back(start, p); + return true; + } + + // General whitespace: leave last ws char for next token's prefix + emit_whitespace_leave_last(p, end, start, result); + return true; +} + +// Handle letter or digit run (no prefix) +inline bool try_simple_run(char32_t cp, const char*& p, const char* end, const char* start, + Variant variant, std::vector& result, int digit_group = 0) { + if (is_letter(cp)) { + scan_letters(p, end); + result.emplace_back(start, p); + return true; + } + if (is_digit(cp)) { + if (variant == Variant::kQwen3) { + if (digit_group > 1) + scan_digits(p, end, digit_group - 1); + } else if (variant != Variant::kClip) { + scan_digits(p, end); + } + result.emplace_back(start, p); + return true; + } + return false; +} + +// ── Main pre-tokenize functions ── + +std::vector pre_tokenize(const std::string& text, Variant variant, + int digit_group = 0) { + std::vector result; + if (text.empty()) + return result; + + const char* p = text.data(); + const char* end = p + text.size(); + + while (p < end) { + const char* start = p; + char32_t cp = read_utf8(p, end); + + if (try_contraction(cp, p, end, start, result)) + continue; + if (try_prefix_run(cp, p, end, start, variant, result)) + continue; + if (try_whitespace_run(cp, p, end, start, variant, result)) + continue; + if (try_simple_run(cp, p, end, start, variant, result, digit_group)) + continue; + + // Other chars (punctuation/symbols) + scan_others(p, end); + if (variant == pretok::Variant::kQwen3) { + // Qwen3's ` ?[^\s\p{L}\p{N}]+[\r\n]*` keeps trailing newlines + // attached to punctuation/symbol runs even without an optional prefix. + scan_newlines(p, end); + } + result.emplace_back(start, p); + } + + return result; +} + +// Return the end of a BLOOM Split-regex match beginning at `start`. +// The regex is " ?[^(\s|[.,!?...])]+": an optional ASCII space followed by +// one or more non-whitespace, non-punctuation characters. +const char* bloom_match_end(const char* start, const char* end) { + const char* p = start; + char32_t cp = read_utf8(p, end); + if (cp == ' ') { + if (p >= end) + return nullptr; + cp = read_utf8(p, end); + if (!is_bloom_word_char(cp)) + return nullptr; + } else if (!is_bloom_word_char(cp)) { + return nullptr; + } + scan_bloom_words(p, end); + return p; +} + +// BLOOM uses Split(..., behavior="Isolated", invert=false) followed by +// ByteLevel(use_regex=false). Regex matches are isolated, while every +// contiguous unmatched span remains a single pre-token. In particular, +// punctuation and adjacent newlines must stay together so BPE can merge +// strings such as ".\n\n". +std::vector bloom_pre_tokenize(const std::string& text) { + std::vector result; + if (text.empty()) + return result; + + const char* p = text.data(); + const char* end = p + text.size(); + + while (p < end) { + const char* start = p; + if (const char* match_end = bloom_match_end(start, end)) { + result.emplace_back(start, match_end); + p = match_end; + continue; + } + + // Preserve one contiguous unmatched span until the next regex match. + read_utf8(p, end); + while (p < end && bloom_match_end(p, end) == nullptr) + read_utf8(p, end); + result.emplace_back(start, p); + } + + return result; +} + +} // namespace pretok + +// ─── BpeTokenizer implementation ─── + +class BpeTokenizer final : public ITokenizer { + public: + static std::unique_ptr Create(const char* tokenizer_json_data, + std::size_t tokenizer_json_size, + bool add_special_tokens = false) { + auto tokenizer = std::unique_ptr(new BpeTokenizer()); + tokenizer->mAddSpecialTokens = add_special_tokens; + tokenizer->parse_tokenizer_json(tokenizer_json_data, tokenizer_json_size); + return tokenizer; + } + + void encode_segment(const std::string& text, std::vector& result) const { + const auto normalized = normalize_text(text); + if (mIsSentencePiece) { + encode_sentencepiece(normalized, result); + } else if (mIsMetaspace) { + encode_metaspace(normalized, result); + } else { + encode_bytelevel(normalized, result); + } + } + + std::vector encode(const std::string& text) const override { + std::vector result; + + if (mAddSpecialTokens) { + for (int32_t bos_id : mPostBosIds) + result.push_back(bos_id); + } + + auto segments = split_added_tokens(text); + for (const auto& seg : segments) { + if (seg.added_id >= 0) + result.push_back(seg.added_id); + else + encode_segment(seg.text, result); + } + + if (mAddSpecialTokens) { + for (int32_t eos_id : mPostEosIds) + result.push_back(eos_id); + } + + return result; + } + + int32_t id_for_token(std::string_view token) const override { + auto it = mTokenToId.find(std::string(token)); + return it != mTokenToId.end() ? it->second : -1; + } + + std::string token_for_id(int32_t id) const override { + if (id >= 0 && static_cast(id) < mVocab.size()) { + return mVocab[id]; + } + return ""; + } + + private: + BpeTokenizer() = default; + + std::string normalize_text(const std::string& text) const { + if (!mNormalizeLowercase && !mNormalizeWhitespace) { + return text; + } + + std::string normalized; + normalized.reserve(text.size()); + const char* cursor = text.data(); + const char* end = cursor + text.size(); + bool previous_was_whitespace = false; + while (cursor < end) { + const char* char_start = cursor; + const char32_t cp = read_utf8(cursor, end); + if (mNormalizeWhitespace && pretok::is_whitespace(cp)) { + if (!previous_was_whitespace) { + normalized.push_back(' '); + } + previous_was_whitespace = true; + continue; + } + previous_was_whitespace = false; + if (mNormalizeLowercase && cp >= 'A' && cp <= 'Z') { + normalized.push_back(static_cast(cp - 'A' + 'a')); + } else { + normalized.append(char_start, cursor); + } + } + return normalized; + } + + // ─── Added token segmentation ─── + + struct Segment { + std::string text; + int32_t added_id; /* -1 = normal */ + }; + + std::pair find_longest_added_token(const std::string& text, size_t pos) const { + int32_t best_id = -1; + size_t best_len = 0; + for (const auto& [content, id] : mAddedTokenPatterns) { + if (pos + content.size() <= text.size() && content.size() > best_len && + text.compare(pos, content.size(), content) == 0) { + best_id = id; + best_len = content.size(); + } + } + return {best_id, best_len}; + } + + std::vector split_added_tokens(const std::string& text) const { + std::vector segments; + if (mAddedTokenPatterns.empty()) { + segments.push_back({text, -1}); + return segments; + } + size_t pos = 0; + while (pos < text.size()) { + auto [best_id, best_len] = find_longest_added_token(text, pos); + if (best_id >= 0) { + segments.push_back({text.substr(pos, best_len), best_id}); + pos += best_len; + } else { + if (segments.empty() || segments.back().added_id >= 0) { + segments.push_back({"", -1}); + } + segments.back().text.push_back(text[pos]); + ++pos; + } + } + return segments; + } + + // ─── Encoding helpers ─── + + // Metaspace encode (DeepSeek style): raw UTF-8 char split, BPE merge. + // Spaces are dropped (not in vocab), Ġ (U+0120) used as separator. + void encode_metaspace(const std::string& text, std::vector& result) const { + std::vector chars; + const char* cp = text.data(); + const char* ce = cp + text.size(); + while (cp < ce) { + const char* cs = cp; + read_utf8(cp, ce); + std::string ch(cs, cp); + if (mTokenToId.count(ch)) { + chars.push_back(std::move(ch)); + } + } + auto tokens = apply_merges(std::move(chars)); + for (const auto& token : tokens) { + auto it = mTokenToId.find(token); + if (it != mTokenToId.end()) { + result.push_back(it->second); + } + } + } + + // SentencePiece-style encode: replace spaces with ▁, split to chars, BPE merge. + // Used when the vocabulary marks spaces with ▁ (SentencePiece BPE vocabularies). + // Normalize text for SentencePiece: replace spaces with ▁, handle prepend + std::string normalize_sentencepiece(const std::string& text) const { + static const std::string sp = "\xe2\x96\x81"; // U+2581 + std::string out; + if (mSentencePiecePrependAlways) { + out = sp; + } + for (char c : text) { + out += (c == ' ') ? sp : std::string(1, c); + } + // Metaspace prepend_scheme=first: prepend if not already starting with ▁ + if (!mSentencePiecePrependAlways && mSentencePiecePrependIfMissing && + (out.empty() || out.compare(0, sp.size(), sp) != 0)) { + out = sp + out; + } + return out; + } + + void encode_sentencepiece(const std::string& text, std::vector& result) const { + std::string normalized = normalize_sentencepiece(text); + + // Split into UTF-8 characters + std::vector chars; + const char* cp = normalized.data(); + const char* ce = cp + normalized.size(); + while (cp < ce) { + const char* cs = cp; + read_utf8(cp, ce); + chars.emplace_back(cs, cp); + } + + // byte_fallback: replace unknown chars with <0xXX> + if (mByteFallback) { + chars = apply_byte_fallback_encode(std::move(chars)); + } + + // BPE merge and lookup + auto tokens = apply_merges(std::move(chars)); + for (const auto& token : tokens) { + auto it = mTokenToId.find(token); + if (it != mTokenToId.end()) { + result.push_back(it->second); + } + } + } + + // For byte_fallback: replace chars not in vocab with <0xXX> byte tokens + std::vector apply_byte_fallback_encode(std::vector chars) const { + std::vector result; + for (auto& ch : chars) { + if (mTokenToId.count(ch)) { + result.push_back(std::move(ch)); + } else { + // Split into individual bytes as <0xXX> + for (unsigned char byte : ch) { + char buf[8]; + std::snprintf(buf, sizeof(buf), "<0x%02X>", byte); + result.push_back(std::string(buf)); + } + } + } + return result; + } + + void encode_bytelevel(const std::string& text, std::vector& result) const { + std::vector words; + if (!mUsePreTokenizer) { + words = fallback_pre_tokenize(text); + } else if (mPreTokenizerVariant == pretok::Variant::kBloom) { + words = pretok::bloom_pre_tokenize(text); + } else { + words = pretok::pre_tokenize(text, mPreTokenizerVariant, mPreTokenizerDigitGroup); + } + + for (const auto& word : words) { + auto chars = byte_encode(word); + if (!chars.empty() && !mEndOfWordSuffix.empty()) { + chars.back() += mEndOfWordSuffix; + } + auto tokens = apply_merges(std::move(chars)); + for (const auto& token : tokens) { + auto it = mTokenToId.find(token); + if (it != mTokenToId.end()) { + result.push_back(it->second); + } + } + } + } + + // ─── Byte-level encoding ─── + + static std::vector byte_encode(const std::string& text) { + const auto& tables = byte_tables(); + std::vector result; + result.reserve(text.size()); + for (unsigned char byte : text) { + result.push_back(tables.byte_to_utf8[byte]); + } + return result; + } + + // Generic pre-tokenizer used when no GPT-2 pattern is declared. + + static std::vector fallback_pre_tokenize(const std::string& text) { + std::vector result; + if (text.empty()) + return result; + result.push_back(text); + return result; + } + + // ─── BPE merge algorithm ─── + + // The merge rank of an adjacent pair, or -1 if no merge joins it. + int merge_rank(const std::string& first, const std::string& second) const { + const auto it = mMergeRank.find(std::make_pair(first, second)); + return it != mMergeRank.end() ? it->second : -1; + } + + // Merges in the reference's order: always the adjacent pair with the lowest rank, the + // leftmost one on a tie, one merge at a time. A pair that a merge forms competes at once + // with the pairs already waiting, even when it outranks the pair just merged. + std::vector apply_merges(std::vector tokens) const { + const int count = static_cast(tokens.size()); + if (count <= 1) + return tokens; + + // Symbols form a list; a merge grows the left symbol and unlinks the right one. + std::vector prev(count); + std::vector next(count); + for (int i = 0; i < count; ++i) { + prev[i] = i - 1; + next[i] = i + 1 < count ? i + 1 : -1; + } + std::vector unlinked(count, false); + // (rank, index of the pair's left symbol), smallest first. + using Candidate = std::pair; + std::priority_queue, std::greater> queue; + const auto enqueue = [&](int left) { + if (left < 0 || next[left] < 0) + return; + const int rank = merge_rank(tokens[left], tokens[next[left]]); + if (rank >= 0) + queue.emplace(rank, left); + }; + for (int i = 0; i + 1 < count; ++i) + enqueue(i); + + while (!queue.empty()) { + const auto [rank, left] = queue.top(); + queue.pop(); + // A queued pair is gone once its left symbol was merged into its own left + // neighbour or either symbol has grown; a rank names one pair. + if (unlinked[left] || next[left] < 0 || + merge_rank(tokens[left], tokens[next[left]]) != rank) + continue; + const int right = next[left]; + tokens[left] += tokens[right]; + unlinked[right] = true; + next[left] = next[right]; + if (next[right] >= 0) + prev[next[right]] = left; + enqueue(prev[left]); + enqueue(left); + } + + // The first symbol is never a right symbol, so the list starts there. + std::vector merged; + for (int i = 0; i >= 0; i = next[i]) + merged.push_back(std::move(tokens[i])); + return merged; + } + + // ─── JSON parsing helpers ─── + + // The checkpoint's settings are the only ones the runtime reproduces (the builder refuses + // the others first): any other normaliser, pre-tokenizer, template shape or BPE option + // makes the reference tokenise differently. + static void check_settings(const nlohmann::json& j) { + const auto unsupported = [](const std::string& what) { + return std::runtime_error("Unsupported tokenizer.json: " + what); + }; + const auto& model = j["model"]; + if (model.value("type", "") != "BPE") + throw unsupported("model.type must be BPE"); + for (const char* key : {"dropout", "continuing_subword_prefix", "end_of_word_suffix"}) { + const auto option = model.find(key); + if (option != model.end() && !option->is_null()) + throw unsupported(std::string("model.") + key + " must be null"); + } + const auto ignore_merges = model.find("ignore_merges"); + if (ignore_merges != model.end() && + !(ignore_merges->is_boolean() && !ignore_merges->get())) + throw unsupported("model.ignore_merges must be false"); + const nlohmann::json space_marker = { + {"type", "Replace"}, {"pattern", {{"String", " "}}}, {"content", "\xe2\x96\x81"}}; + const auto normalizer = j.find("normalizer"); + if (normalizer == j.end() || *normalizer != space_marker) + throw unsupported("the normalizer must only replace spaces with U+2581"); + const auto pre_tokenizer = j.find("pre_tokenizer"); + if (pre_tokenizer != j.end() && !pre_tokenizer->is_null()) + throw unsupported("pre_tokenizer must be null"); + // The window keeps the end token in its last slot, so the template is the sequence + // followed by one special token (its id is checked with the added tokens). + const auto post = j.find("post_processor"); + const bool one_end_token = + post != j.end() && post->is_object() && + post->value("type", "") == "TemplateProcessing" && post->contains("single") && + (*post)["single"].is_array() && (*post)["single"].size() == 2 && + (*post)["single"][0].size() == 1 && (*post)["single"][0].contains("Sequence") && + (*post)["single"][1].size() == 1 && (*post)["single"][1].contains("SpecialToken"); + if (!one_end_token) + throw unsupported("the template must be the sequence followed by one special token"); + } + + // The reference falls back to bytes all or nothing: a character outside the vocabulary + // becomes its byte tokens only when every one of them is in the vocabulary, and the + // unknown token otherwise. The runtime has no unknown-token path, so it takes only a + // vocabulary in which every byte that such a character can need has its token: all of + // them, except an ASCII byte whose character is a vocabulary entry itself (the only + // character that holds that byte). + void check_byte_fallback_coverage() const { + if (!mByteFallback) + throw std::runtime_error( + "Unsupported tokenizer.json: the model must fall back to bytes"); + for (int byte = 0; byte < 256; ++byte) { + char name[8]; + std::snprintf(name, sizeof(name), "<0x%02X>", byte); + if (mTokenToId.count(name) != 0) + continue; + if (byte < 0x80 && mTokenToId.count(std::string(1, static_cast(byte))) != 0) + continue; + throw std::runtime_error(std::string("Unsupported tokenizer.json: no byte token ") + + name + " for the byte fallback"); + } + } + + void parse_vocab(const nlohmann::json& j) { + auto& vocab_obj = j["model"]["vocab"]; + size_t vocab_size = vocab_obj.size(); + if (vocab_size > static_cast(INT32_MAX)) + throw std::runtime_error( + "Unsupported tokenizer.json: more vocabulary entries than int32 ids"); + mVocab.resize(vocab_size); + + for (auto& [token, id] : vocab_obj.items()) { + // The vocabulary is kept as ids 0..N-1; the reference takes any id, so a token + // with another id would be lost here. + if (!id.is_number_unsigned() || id.get() >= vocab_size) + throw std::runtime_error("Unsupported tokenizer.json: vocabulary id of " + token + + " is not in 0.." + std::to_string(vocab_size - 1)); + const auto token_id = static_cast(id.get()); + mVocab[token_id] = token; + mTokenToId[token] = token_id; + } + // The normaliser turns every space into U+2581; without that marker the runtime would + // encode on another path than the reference's. + if (mTokenToId.count("\xe2\x96\x81") == 0) + throw std::runtime_error( + "Unsupported tokenizer.json: no U+2581 space marker in the vocabulary"); + } + + void parse_merges(const nlohmann::json& j) { + if (!j["model"].contains("merges")) + throw std::runtime_error("Invalid tokenizer.json: missing model.merges"); + + auto& merges_arr = j["model"]["merges"]; + mMergeRank.reserve(merges_arr.size()); + + // Like the reference, a rule is one pair (two strings, or one string with one space) + // whose operands and result are vocabulary entries; any other rule is a load error, + // never skipped. + for (size_t i = 0; i < merges_arr.size(); ++i) { + const auto& merge = merges_arr[i]; + std::string first, second; + bool pair = false; + if (merge.is_array() && merge.size() == 2 && merge[0].is_string() && + merge[1].is_string()) { + first = merge[0].get(); + second = merge[1].get(); + pair = true; + } else if (merge.is_string()) { + const std::string text = merge.get(); + const auto space = text.find(' '); + if (space != std::string::npos && text.find(' ', space + 1) == std::string::npos) { + first = text.substr(0, space); + second = text.substr(space + 1); + pair = true; + } + } + if (!pair) + throw std::runtime_error("Invalid tokenizer.json: merge " + std::to_string(i) + + " is not one pair"); + for (const std::string* part : {&first, &second}) { + if (mTokenToId.count(*part) == 0) + throw std::runtime_error("Invalid tokenizer.json: merge " + first + " " + + second + ": " + *part + " is not in the vocabulary"); + } + if (mTokenToId.count(first + second) == 0) + throw std::runtime_error("Invalid tokenizer.json: merge " + first + " " + second + + " makes " + first + second + + ", which is not in the vocabulary"); + mMergeRank[std::make_pair(first, second)] = static_cast(i); + } + } + + // One added_tokens record, read with checked access: a record without its fields is a + // load error, never a lookup of a missing key. + static std::pair read_added_token(const nlohmann::json& tok) { + if (!tok.is_object()) + throw std::runtime_error( + "Invalid tokenizer.json: an added_tokens entry is not an object"); + const auto content = tok.find("content"); + if (content == tok.end() || !content->is_string()) + throw std::runtime_error( + "Invalid tokenizer.json: an added_tokens entry has no string content"); + const std::string text = content->get(); + const auto id = tok.find("id"); + if (id == tok.end() || !id->is_number_unsigned() || + id->get() > static_cast(INT32_MAX)) + throw std::runtime_error("Invalid tokenizer.json: added token " + text + + " has no valid id"); + for (const char* flag : {"single_word", "lstrip", "rstrip", "normalized", "special"}) { + const auto value = tok.find(flag); + if (value == tok.end() || !value->is_boolean()) + throw std::runtime_error("Invalid tokenizer.json: added token " + text + + " has no boolean " + flag); + } + // The runtime matches an added token as it is, anywhere in the raw text, which is + // the reference's behaviour only when none of these options is set. + for (const char* flag : {"single_word", "lstrip", "rstrip", "normalized"}) { + if (tok.at(flag).get()) + throw std::runtime_error("Unsupported tokenizer.json: added token " + text + + " sets " + flag); + } + return {text, static_cast(id->get())}; + } + + void parse_added_tokens(const nlohmann::json& j) { + const auto list = j.find("added_tokens"); + if (list == j.end()) + return; + if (!list->is_array()) + throw std::runtime_error("Invalid tokenizer.json: added_tokens must be an array"); + for (const auto& tok : *list) { + const auto [content, id] = read_added_token(tok); + // The reference gives an added token that is in the vocabulary the vocabulary's + // id; the runtime uses the record's, so the two must agree. + const auto in_vocab = mTokenToId.find(content); + if (in_vocab == mTokenToId.end() || in_vocab->second != id) + throw std::runtime_error("Unsupported tokenizer.json: added token " + content + + " is not the vocabulary entry with id " + + std::to_string(id)); + if (tok.at("special").get()) { + mSpecialTokens[content] = id; + } + // All added tokens (special and non-special) participate in pre-split + // matching during encode, matching HuggingFace's AddedToken behavior. + // The special flag only controls post_processor BOS/EOS insertion. + mAddedTokenPatterns.push_back({content, id}); + } + // Sort by length descending for longest-match-first + std::sort(mAddedTokenPatterns.begin(), mAddedTokenPatterns.end(), + [](const auto& a, const auto& b) { return a.first.size() > b.first.size(); }); + } + + // Parse digit group size from regex pattern like \p{N}{1,3} → 3. + // Returns 0 if no digit grouping found (single digit or unlimited). + static int parse_digit_group(const std::string& regex) { + // Search for "\p{N}{" — the standalone grouped variant, not [^\p{N}] + auto pos = regex.find("\\p{N}{"); + if (pos == std::string::npos) + return 0; + auto open = pos + 6; // after "\\p{N}{" + auto close = regex.find('}', open); + if (close == std::string::npos) + return 0; + auto comma = regex.find(',', open); + if (comma == std::string::npos || comma >= close) + return 0; + return std::stoi(regex.substr(comma + 1, close - comma - 1)); + } + + static bool is_clip_split_regex(const std::string& regex) { + const bool has_boundary_token = regex.find("startoftext") != std::string::npos || + regex.find("endoftext") != std::string::npos; + return has_boundary_token && regex.find("\\p{L}") != std::string::npos && + regex.find("\\p{N}") != std::string::npos; + } + + static pretok::Variant classify_clip_split(const nlohmann::json& split) { + const auto behavior = split.value("behavior", ""); + const bool invert = split.value("invert", false); + if (behavior == "Removed" && invert) + return pretok::Variant::kClip; + if (behavior == "Isolated" && invert) + return pretok::Variant::kGemma; + throw std::runtime_error("Unsupported CLIP Split contract: behavior=" + behavior + + ", invert=" + (invert ? "true" : "false")); + } + + static bool is_qwen3_split_regex(const std::string& regex) { + return regex.find("[^\r\n") != std::string::npos || + regex.find("[^\\r\\n") != std::string::npos; + } + + static bool is_bloom_split_regex(const std::string& regex) { + return regex.find("[^(\\s") != std::string::npos || + regex.find("[^(\\\\s") != std::string::npos; + } + + // Classify one Split pre-tokenizer from both its pattern and contract. + static pretok::Variant classify_split(const nlohmann::json& split, int& digit_group_out) { + const auto regex = split["pattern"]["Regex"].get(); + if (is_clip_split_regex(regex)) + return classify_clip_split(split); + if (is_qwen3_split_regex(regex)) { + digit_group_out = parse_digit_group(regex); + return pretok::Variant::kQwen3; + } + if (is_bloom_split_regex(regex)) { + return pretok::Variant::kBloom; + } + if (regex.find("\\s?[A-Za-z") != std::string::npos) { + return pretok::Variant::kDeepSeek; + } + return pretok::Variant::kGemma; + } + + // Detect variant from the Split inside a Sequence pre_tokenizer. + static pretok::Variant detect_split_variant(const nlohmann::json& pt, int& digit_group_out) { + digit_group_out = 0; + if (!pt.contains("pretokenizers")) + return pretok::Variant::kGemma; + for (auto& sub : pt["pretokenizers"]) { + if (sub.value("type", "") != "Split") + continue; + if (!sub.contains("pattern") || !sub["pattern"].contains("Regex")) + continue; + return classify_split(sub, digit_group_out); + } + return pretok::Variant::kGemma; + } + + static bool is_space_split_pre_tokenizer(const nlohmann::json& pt, const std::string& pt_type) { + if (pt_type != "Split") + return false; + if (!pt.contains("pattern") || !pt["pattern"].contains("String")) + return false; + return pt["pattern"]["String"].get() == " "; + } + + void detect_pre_tokenizer(const nlohmann::json& j) { + mUsePreTokenizer = true; + mPreTokenizerVariant = pretok::Variant::kGemma; + + if (!j.contains("pre_tokenizer") || j["pre_tokenizer"].is_null()) + return; + auto& pt = j["pre_tokenizer"]; + std::string pt_type = pt.value("type", ""); + + if (pt_type == "ByteLevel") { + mPreTokenizerVariant = pretok::Variant::kGemma; + } else if (pt_type == "Sequence") { + int digit_group = 0; + mPreTokenizerVariant = detect_split_variant(pt, digit_group); + mPreTokenizerDigitGroup = digit_group; + } else if (is_space_split_pre_tokenizer(pt, pt_type)) { + // Gemma SentencePiece-BPE tokenizers use a direct Split(" ") + // pre-tokenizer with spaces already normalized to U+2581. + mUsePreTokenizer = false; + } else if (pt_type == "Metaspace") { + mIsMetaspace = true; + mUsePreTokenizer = false; + } else if (pt_type.empty()) { + mUsePreTokenizer = false; + } else { + throw std::runtime_error("Unsupported pre_tokenizer type: " + pt_type); + } + } + + // SentencePiece encode: vocab uses ▁ (U+2581) for spaces. + // Detect by: (1) ▁ in vocabulary, or (2) normalizer prepends ▁. + void detect_sentencepiece() { + static const std::string spiece_marker = "\xe2\x96\x81"; // U+2581 + mIsSentencePiece = mTokenToId.count(spiece_marker) > 0 || mSentencePiecePrependAlways; + } + + static std::string optional_model_string(const nlohmann::json& model, const char* key) { + auto it = model.find(key); + if (it != model.end() && it->is_string()) + return it->get(); + return {}; + } + + void parse_tokenizer_json(const char* json_data, std::size_t json_size) { + nlohmann::json j; + try { + j = nlohmann::json::parse(json_data, json_data + json_size); + } catch (const std::exception& e) { + throw std::runtime_error(std::string("Failed to parse tokenizer.json: ") + e.what()); + } + + if (!j.contains("model")) + throw std::runtime_error("Invalid tokenizer.json: missing model"); + auto& model = j["model"]; + if (!model.contains("vocab") || !model["vocab"].is_object()) + throw std::runtime_error("Invalid tokenizer.json: model.vocab must be an object"); + if (!model.contains("merges") || !model["merges"].is_array()) + throw std::runtime_error("Invalid tokenizer.json: model.merges must be an array"); + check_settings(j); + + mByteFallback = model.value("byte_fallback", false); + mEndOfWordSuffix = optional_model_string(model, "end_of_word_suffix"); + parse_vocab(j); + check_byte_fallback_coverage(); + parse_merges(j); + parse_added_tokens(j); + parse_post_processor(j); + detect_normalizer(j); + detect_pre_tokenizer(j); + detect_sentencepiece(); + } + + // Detect normalizer: check for Prepend (always prepend ▁) vs none + static bool normalizer_sequence_prepends(const nlohmann::json& norm, + const std::string& norm_type) { + if (norm_type != "Sequence" || !norm.contains("normalizers")) + return false; + for (auto& sub : norm["normalizers"]) { + if (sub.value("type", "") == "Prepend") + return true; + } + return false; + } + + static bool normalizer_replaces_space_with_sentence_piece(const nlohmann::json& norm, + const std::string& norm_type) { + if (norm_type == "Sequence" && norm.contains("normalizers")) { + for (const auto& sub : norm["normalizers"]) { + if (normalizer_replaces_space_with_sentence_piece(sub, sub.value("type", ""))) { + return true; + } + } + return false; + } + if (norm_type != "Replace") + return false; + if (!norm.contains("pattern") || !norm["pattern"].contains("String")) + return false; + if (norm["pattern"]["String"].get() != " ") + return false; + return norm.value("content", "") == "\xe2\x96\x81"; + } + + void detect_normalizer(const nlohmann::json& j) { + if (!j.contains("normalizer") || j["normalizer"].is_null()) + return; + auto& norm = j["normalizer"]; + std::string norm_type = norm.value("type", ""); + detect_text_normalizers(norm); + if (normalizer_sequence_prepends(norm, norm_type)) { + mSentencePiecePrependAlways = true; + } else if (normalizer_replaces_space_with_sentence_piece(norm, norm_type)) { + // Gemma replaces spaces with ▁ but does not prepend ▁ to the + // first token. Preserve the old prepend-if-missing behavior for + // Metaspace-style SentencePiece models. + mSentencePiecePrependIfMissing = false; + } + } + + void detect_text_normalizers(const nlohmann::json& normalizer) { + const std::string type = normalizer.value("type", ""); + if (type == "Sequence" && normalizer.contains("normalizers")) { + for (const auto& child : normalizer["normalizers"]) { + detect_text_normalizers(child); + } + return; + } + if (type == "Lowercase") { + mNormalizeLowercase = true; + return; + } + if (type == "Replace" && normalizer.contains("pattern") && + normalizer["pattern"].contains("Regex") && + normalizer["pattern"]["Regex"].get() == "\\s+" && + normalizer.value("content", "") == " ") { + mNormalizeWhitespace = true; + } + } + + // Parse post_processor to extract BOS/EOS tokens for add_special_tokens + void parse_post_processor(const nlohmann::json& j) { + if (!j.contains("post_processor") || j["post_processor"].is_null()) + return; + auto& pp = j["post_processor"]; + std::string pp_type = pp.value("type", ""); + + if (pp_type == "TemplateProcessing") { + parse_template_post_processor(pp); + } else if (pp_type == "Sequence") { + parse_sequence_post_processor(pp); + } else if (pp_type == "RobertaProcessing") { + parse_roberta_post_processor(pp); + } + // ByteLevel post_processor doesn't add tokens, nothing to do + } + + // Iterate Sequence post_processor's processors array to find TemplateProcessing + void parse_sequence_post_processor(const nlohmann::json& pp) { + if (!pp.contains("processors")) + return; + for (auto& sub : pp["processors"]) { + if (sub.value("type", "") == "TemplateProcessing") { + parse_template_post_processor(sub); + return; // first TemplateProcessing wins + } + } + } + + // RobertaProcessing: {"type":"RobertaProcessing","cls":["",0],"sep":["",2],...} + void parse_roberta_post_processor(const nlohmann::json& pp) { + if (pp.contains("cls") && pp["cls"].is_array() && pp["cls"].size() >= 2) { + int32_t cls_id = pp["cls"][1].get(); + mPostBosIds.push_back(cls_id); + } + if (pp.contains("sep") && pp["sep"].is_array() && pp["sep"].size() >= 2) { + int32_t sep_id = pp["sep"][1].get(); + mPostEosIds.push_back(sep_id); + } + } + + // A template token expands to the ids that its special_tokens entry lists. The runtime + // appends one id for it, that of the special added token of the same name, so the + // entry must list exactly that id. + int32_t template_token_id(const nlohmann::json& pp, const nlohmann::json& piece) const { + const std::string name = piece.value("id", ""); + const auto registered = mSpecialTokens.find(name); + if (registered == mSpecialTokens.end()) + throw std::runtime_error("Unsupported tokenizer.json: template token " + name + + " is not a special added token"); + bool exact = false; + const auto table = pp.find("special_tokens"); + if (table != pp.end() && table->is_object()) { + const auto entry = table->find(name); + if (entry != table->end() && entry->is_object()) { + const auto ids = entry->find("ids"); + exact = ids != entry->end() && ids->is_array() && ids->size() == 1 && + ids->front().is_number_unsigned() && + ids->front().get() == + static_cast(registered->second); + } + } + if (!exact) + throw std::runtime_error("Unsupported tokenizer.json: template token " + name + + " must expand to exactly its id " + + std::to_string(registered->second)); + return registered->second; + } + + void parse_template_post_processor(const nlohmann::json& pp) { + const auto single = pp.find("single"); + if (single == pp.end()) + return; + bool seen_sequence = false; + for (const auto& entry : *single) { + if (entry.contains("Sequence")) { + seen_sequence = true; + continue; + } + const auto piece = entry.find("SpecialToken"); + if (piece == entry.end()) + continue; + const int32_t id = template_token_id(pp, *piece); + if (seen_sequence) { + mPostEosIds.push_back(id); + } else { + mPostBosIds.push_back(id); + } + } + } + + // ─── Data members ─── + + std::vector mVocab; + std::unordered_map mTokenToId; + + struct PairHash { + size_t operator()(const std::pair& p) const { + size_t h1 = std::hash{}(p.first); + size_t h2 = std::hash{}(p.second); + return h1 ^ (h2 * 0x9e3779b97f4a7c15ULL + 0x9e3779b9 + (h1 << 6) + (h1 >> 2)); + } + }; + + std::unordered_map, int, PairHash> mMergeRank; + + std::unordered_map mSpecialTokens; + + // Non-special added tokens: matched before pre-tokenization (longest first) + std::vector> mAddedTokenPatterns; + + bool mAddSpecialTokens = false; + bool mUsePreTokenizer = true; + bool mIsMetaspace = false; // Set by detect_pre_tokenizer. + bool mIsSentencePiece = false; + bool mSentencePiecePrependAlways = + false; // true for Normalizer Prepend, false for Metaspace first + bool mSentencePiecePrependIfMissing = true; + bool mByteFallback = false; + bool mNormalizeLowercase = false; + bool mNormalizeWhitespace = false; + std::string mEndOfWordSuffix; + + // Post-processor: BOS/EOS token IDs to add when add_special_tokens=true + // Vectors to support multiple BOS/EOS tokens (e.g. GLM-4: [gMASK] + ) + std::vector mPostBosIds; + std::vector mPostEosIds; + pretok::Variant mPreTokenizerVariant = pretok::Variant::kGemma; + int mPreTokenizerDigitGroup = 0; // 0=unlimited, 3=\p{N}{1,3} (LLaMA 3.1/GLM-4) +}; + +} // namespace + +std::unique_ptr CreateSiglip2Tokenizer(const char* tokenizer_json_data, + std::size_t tokenizer_json_size, + bool add_special_tokens) { + return BpeTokenizer::Create(tokenizer_json_data, tokenizer_json_size, add_special_tokens); +} + +} // namespace trtmc::siglip2 diff --git a/families/siglip2/runtime/naflex_preprocess.cpp b/families/siglip2/runtime/naflex_preprocess.cpp new file mode 100644 index 0000000000..cea01182b1 --- /dev/null +++ b/families/siglip2/runtime/naflex_preprocess.cpp @@ -0,0 +1,343 @@ +/* + * SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. + * SPDX-License-Identifier: Apache-2.0 + */ + +// Adapted from transformers v5.2.0 (patch-budget size search, patch layout), Pillow 13.0.0 +// src/libImaging/Resample.c (8-bit bilinear resize) and PyTorch v2.12.0 +// aten/src/ATen/native/cpu/UpSampleKernel.cpp (antialiased taps); see ../NOTICE. + +#include "families/siglip2/runtime/naflex_preprocess.h" + +#include +#include +#include +#include +#include +#include +#include +#include + +namespace trtmc { + +namespace { + +constexpr std::int32_t kChannels = 3; + +// ---- Target size: transformers get_image_size_for_max_num_patches ----------------- + +// One side scaled, rounded up to whole patches, never below one patch. The reference +// computes this in Python floats; every operation here is the same IEEE double one. +std::int64_t scaled_side(double scale, std::int32_t size, std::int32_t patch) { + const double scaled = static_cast(size) * scale; + const auto patches = static_cast(std::ceil(scaled / static_cast(patch))); + return std::max(patch, patches * patch); +} + +// ---- Pillow 13.0.0 bilinear resize (Resample.c) ------------------------------------- + +// Pillow's Resample.c: 8-bit passes use 22 fractional bits and round half up. +constexpr std::int32_t kPrecisionBits = 32 - 8 - 2; + +struct ResampleAxis { + std::int32_t taps{0}; // stride of `weights` per output index + std::vector first; + std::vector count; + std::vector weights; +}; + +double pillow_bilinear(double x) { + if (x < 0.0) + x = -x; + if (x < 1.0) + return 1.0 - x; + return 0.0; +} + +// precompute_coeffs + normalize_coeffs_8bpc for the default box (0, size). +ResampleAxis pillow_axis(std::int32_t in_size, std::int32_t out_size) { + const double scale = static_cast(static_cast(in_size)) / out_size; + const double filter_scale = std::max(scale, 1.0); + const double support = 1.0 * filter_scale; + ResampleAxis axis; + axis.taps = static_cast(std::ceil(support)) * 2 + 1; + axis.first.resize(static_cast(out_size)); + axis.count.resize(static_cast(out_size)); + axis.weights.assign(static_cast(out_size) * axis.taps, 0); + std::vector floating(static_cast(axis.taps)); + for (std::int32_t out = 0; out < out_size; ++out) { + const double center = 0.0 + (out + 0.5) * scale; + const double inverse = 1.0 / filter_scale; + auto first = static_cast(center - support + 0.5); + first = std::max(first, 0); + auto last = static_cast(center + support + 0.5); + last = std::min(last, in_size); + const std::int32_t count = std::min(last - first, axis.taps); + double total = 0.0; + for (std::int32_t tap = 0; tap < count; ++tap) { + const double weight = pillow_bilinear((tap + first - center + 0.5) * inverse); + floating[static_cast(tap)] = weight; + total += weight; + } + for (std::int32_t tap = 0; tap < count; ++tap) { + double weight = floating[static_cast(tap)]; + if (total != 0.0) + weight /= total; + const double scaled = weight * (1 << kPrecisionBits); + axis.weights[static_cast(out) * axis.taps + tap] = + static_cast(scaled < 0 ? -0.5 + scaled : 0.5 + scaled); + } + axis.first[static_cast(out)] = first; + axis.count[static_cast(out)] = std::max(count, 0); + } + return axis; +} + +std::uint8_t pillow_clip(std::int64_t sum) { + const std::int64_t value = sum >> kPrecisionBits; + return static_cast(std::clamp(value, 0, 255)); +} + +// One output value of a pass: `stride` is the step between consecutive source taps. +std::uint8_t pillow_tap_sum(const std::uint8_t* source, std::size_t stride, + const ResampleAxis& axis, std::int32_t out) { + std::int64_t sum = std::int64_t{1} << (kPrecisionBits - 1); + const auto base = static_cast(out) * axis.taps; + const auto first = static_cast(axis.first[static_cast(out)]); + for (std::int32_t tap = 0; tap < axis.count[static_cast(out)]; ++tap) { + sum += static_cast(source[(first + static_cast(tap)) * stride]) * + axis.weights[base + static_cast(tap)]; + } + return pillow_clip(sum); +} + +std::vector resize_horizontal(const std::vector& image, + std::int32_t height, std::int32_t width, + std::int32_t out_width) { + const auto axis = pillow_axis(width, out_width); + std::vector output(static_cast(height) * out_width * kChannels); + for (std::int32_t y = 0; y < height; ++y) { + const auto* row = image.data() + static_cast(y) * width * kChannels; + for (std::int32_t x = 0; x < out_width; ++x) { + for (std::int32_t c = 0; c < kChannels; ++c) { + output[(static_cast(y) * out_width + x) * kChannels + c] = + pillow_tap_sum(row + c, kChannels, axis, x); + } + } + } + return output; +} + +std::vector resize_vertical(const std::vector& image, + std::int32_t height, std::int32_t width, + std::int32_t out_height) { + const auto axis = pillow_axis(height, out_height); + const auto row_stride = static_cast(width) * kChannels; + std::vector output(static_cast(out_height) * row_stride); + for (std::int32_t y = 0; y < out_height; ++y) { + for (std::size_t column = 0; column < row_stride; ++column) { + output[static_cast(y) * row_stride + column] = + pillow_tap_sum(image.data() + column, row_stride, axis, y); + } + } + return output; +} + +// ---- Position-table taps: PyTorch _compute_indices_min_size_weights_aa ------------- + +double torch_bilinear(double x) { + x = std::abs(x); + return x < 1.0 ? 1.0 - x : 0.0; +} + +void require_positive(std::int32_t value, const char* what) { + if (value <= 0) + throw std::invalid_argument(std::string("siglip2 ") + what + " must be positive"); +} + +void validate(const Siglip2PreprocessConfig& config) { + require_positive(config.patch_size, "patch size"); + require_positive(config.max_num_patches, "patch budget"); + require_positive(config.position_grid, "position grid"); + if (config.image_mean.size() != kChannels || config.image_std.size() != kChannels) + throw std::invalid_argument("siglip2 image mean/std must have three channels"); + for (const float value : config.image_std) { + if (value == 0.0F) + throw std::invalid_argument("siglip2 image std must be non-zero"); + } + if (!(config.rescale_factor > 0.0)) + throw std::invalid_argument("siglip2 rescale factor must be positive"); +} + +std::vector to_bytes(const float* rgb, std::int32_t height, std::int32_t width) { + std::vector image(static_cast(height) * width * kChannels); + for (std::size_t index = 0; index < image.size(); ++index) { + const float value = std::clamp(rgb[index], 0.0F, 1.0F); + image[index] = static_cast(std::lround(value * 255.0F)); + } + return image; +} + +std::vector patchify(const std::vector& image, std::int32_t grid_height, + std::int32_t grid_width, const Siglip2PreprocessConfig& config) { + const std::int32_t patch = config.patch_size; + const std::int32_t width = grid_width * patch; + const auto features = static_cast(patch) * patch * kChannels; + std::vector values(static_cast(grid_height) * grid_width * features); + std::size_t out = 0; + for (std::int32_t py = 0; py < grid_height; ++py) { + for (std::int32_t px = 0; px < grid_width; ++px) { + for (std::int32_t ry = 0; ry < patch; ++ry) { + const auto row = static_cast(py * patch + ry) * width; + for (std::int32_t rx = 0; rx < patch; ++rx) { + const auto pixel = + (row + static_cast(px * patch + rx)) * kChannels; + for (std::int32_t c = 0; c < kChannels; ++c) { + // rescale in double then store float32, as numpy does; normalise + // in float32. + const auto scaled = static_cast( + static_cast(image[pixel + static_cast(c)]) * + config.rescale_factor); + values[out++] = (scaled - config.image_mean[static_cast(c)]) / + config.image_std[static_cast(c)]; + } + } + } + } + } + return values; +} + +std::vector position_taps(std::int32_t grid_height, std::int32_t grid_width, + std::int32_t table_grid) { + const auto rows = siglip2_axis_taps(table_grid, grid_height); + const auto columns = siglip2_axis_taps(table_grid, grid_width); + const auto table = static_cast(table_grid) * table_grid; + std::vector taps(static_cast(grid_height) * grid_width * table, 0.0F); + for (std::int32_t y = 0; y < grid_height; ++y) { + for (std::int32_t x = 0; x < grid_width; ++x) { + float* out = taps.data() + (static_cast(y) * grid_width + x) * table; + for (std::int32_t sy = 0; sy < table_grid; ++sy) { + const double wy = rows[static_cast(y) * table_grid + sy]; + if (wy == 0.0) + continue; + for (std::int32_t sx = 0; sx < table_grid; ++sx) { + const double wx = columns[static_cast(x) * table_grid + sx]; + out[static_cast(sy) * table_grid + sx] = + static_cast(wy * wx); + } + } + } + } + return taps; +} + +} // namespace + +std::pair siglip2_target_size(std::int32_t height, std::int32_t width, + std::int32_t patch_size, + std::int32_t max_num_patches) { + if (height <= 0 || width <= 0 || patch_size <= 0 || max_num_patches <= 0) + throw std::invalid_argument("siglip2 target size needs positive dimensions"); + constexpr double kEps = 1e-5; + double scale_min = kEps / 10; + double scale_max = 100.0; + while ((scale_max - scale_min) >= kEps) { + const double scale = (scale_min + scale_max) / 2; + const auto rows = scaled_side(scale, height, patch_size) / patch_size; + const auto columns = scaled_side(scale, width, patch_size) / patch_size; + if (static_cast(rows) * static_cast(columns) <= max_num_patches) + scale_min = scale; + else + scale_max = scale; + } + const auto target_height = scaled_side(scale_min, height, patch_size); + const auto target_width = scaled_side(scale_min, width, patch_size); + if (target_height > std::numeric_limits::max() || + target_width > std::numeric_limits::max()) { + throw std::invalid_argument("siglip2 image is too large to resize"); + } + return {static_cast(target_height), static_cast(target_width)}; +} + +std::vector siglip2_resize_bilinear(const std::uint8_t* rgb, std::int32_t height, + std::int32_t width, std::int32_t out_height, + std::int32_t out_width) { + if (rgb == nullptr || height <= 0 || width <= 0 || out_height <= 0 || out_width <= 0) + throw std::invalid_argument("siglip2 resize needs a non-empty image"); + std::vector image(rgb, + rgb + static_cast(height) * width * kChannels); + // Pillow skips an axis whose size does not change. Each pass rounds to 8 bits, so the + // order matters: Pillow 13 resamples vertically first when the height shrinks by more + // than twice as many pixels as the width (Pillow 12 always went horizontally first). + const std::int64_t shrink_height = static_cast(height) - out_height; + const std::int64_t shrink_width = static_cast(width) - out_width; + const bool horizontal_first = !(shrink_height > 0 && shrink_height > shrink_width * 2); + if (horizontal_first) { + if (out_width != width) + image = resize_horizontal(image, height, width, out_width); + if (out_height != height) + image = resize_vertical(image, height, out_width, out_height); + } else { + if (out_height != height) + image = resize_vertical(image, height, width, out_height); + if (out_width != width) + image = resize_horizontal(image, out_height, width, out_width); + } + return image; +} + +std::vector siglip2_axis_taps(std::int32_t input, std::int32_t output) { + if (input <= 0 || output <= 0) + throw std::invalid_argument("siglip2 position taps need positive sizes"); + const double scale = static_cast(input) / output; + const double support = scale >= 1.0 ? scale : 1.0; + const double inverse = scale >= 1.0 ? 1.0 / scale : 1.0; + std::vector taps(static_cast(output) * input, 0.0); + for (std::int32_t out = 0; out < output; ++out) { + const double center = scale * (out + 0.5); + const auto first = + std::max(static_cast(center - support + 0.5), 0); + const auto last = + std::min(static_cast(center + support + 0.5), input); + double total = 0.0; + double* row = taps.data() + static_cast(out) * input; + for (std::int64_t index = first; index < last; ++index) { + const double weight = + torch_bilinear((static_cast(index) - center + 0.5) * inverse); + row[index] = weight; + total += weight; + } + if (total != 0.0) { + for (std::int64_t index = first; index < last; ++index) + row[index] /= total; + } + } + return taps; +} + +Siglip2Patches preprocess_siglip2_image(const float* rgb, std::int32_t height, std::int32_t width, + const Siglip2PreprocessConfig& config) { + if (rgb == nullptr || height <= 0 || width <= 0) + throw std::invalid_argument("siglip2 source image must be non-empty"); + validate(config); + + const auto [target_height, target_width] = + siglip2_target_size(height, width, config.patch_size, config.max_num_patches); + const auto source = to_bytes(rgb, height, width); + const auto resized = + siglip2_resize_bilinear(source.data(), height, width, target_height, target_width); + + Siglip2Patches patches; + patches.grid_height = target_height / config.patch_size; + patches.grid_width = target_width / config.patch_size; + if (static_cast(patches.grid_height) * patches.grid_width > + config.max_num_patches) + throw std::runtime_error("siglip2 resize exceeded the patch budget"); + patches.pixel_values = patchify(resized, patches.grid_height, patches.grid_width, config); + patches.position_weights = + position_taps(patches.grid_height, patches.grid_width, config.position_grid); + return patches; +} + +} // namespace trtmc diff --git a/families/siglip2/runtime/naflex_preprocess.h b/families/siglip2/runtime/naflex_preprocess.h new file mode 100644 index 0000000000..cb28ee8458 --- /dev/null +++ b/families/siglip2/runtime/naflex_preprocess.h @@ -0,0 +1,59 @@ +/* + * SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. + * SPDX-License-Identifier: Apache-2.0 + */ + +#pragma once + +// Adapted from transformers, Pillow and PyTorch; see families/siglip2/NOTICE. + +#include +#include +#include + +namespace trtmc { + +struct Siglip2PreprocessConfig { + std::int32_t patch_size{16}; + std::int32_t max_num_patches{256}; + // Side of the square position table the vision engine carries. + std::int32_t position_grid{16}; + double rescale_factor{1.0 / 255.0}; + std::vector image_mean{0.5F, 0.5F, 0.5F}; + std::vector image_std{0.5F, 0.5F, 0.5F}; +}; + +// One image cut into its NaFlex grid of patches. +struct Siglip2Patches { + std::int32_t grid_height{0}; + std::int32_t grid_width{0}; + // [grid_height * grid_width, patch * patch * 3], patches in row-major grid order and + // each patch in (row, column, channel) order: the layout the patch Linear expects. + std::vector pixel_values; + // [grid_height * grid_width, position_grid^2]: the antialiased bilinear taps that + // resample the square position table to this grid. + std::vector position_weights; +}; + +// The reference processor's binary search: the largest aspect-preserving size whose +// sides are whole patches and whose patch count fits the budget. Returns (height, width) +// in pixels. +std::pair siglip2_target_size(std::int32_t height, std::int32_t width, + std::int32_t patch_size, + std::int32_t max_num_patches); + +// Pillow 13's 8-bit bilinear resize of interleaved RGB, reproduced coefficient for +// coefficient (fixed point, with Pillow 13's choice of which pass runs first). +std::vector siglip2_resize_bilinear(const std::uint8_t* rgb, std::int32_t height, + std::int32_t width, std::int32_t out_height, + std::int32_t out_width); + +// The taps of torch.nn.functional.interpolate(mode="bilinear", align_corners=False, +// antialias=True) along one axis, as a dense [output, input] matrix. +std::vector siglip2_axis_taps(std::int32_t input, std::int32_t output); + +// Float RGB in [0, 1], interleaved [height, width, 3], to the vision engine's inputs. +Siglip2Patches preprocess_siglip2_image(const float* rgb, std::int32_t height, std::int32_t width, + const Siglip2PreprocessConfig& config); + +} // namespace trtmc diff --git a/families/siglip2/runtime/pipeline.cpp b/families/siglip2/runtime/pipeline.cpp new file mode 100644 index 0000000000..07d25c02ca --- /dev/null +++ b/families/siglip2/runtime/pipeline.cpp @@ -0,0 +1,201 @@ +/* + * SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. + * SPDX-License-Identifier: Apache-2.0 + */ + +#include "families/siglip2/runtime/pipeline.h" + +#include +#include +#include +#include +#include +#include + +namespace trtmc { + +namespace { + +// Both towers land in one space, which is the only reason a dot product between them +// means anything. Naming it lets a caller see that two results are comparable; it +// claims nothing about any other checkpoint. +constexpr const char* kEmbeddingSpace = "siglip2"; + +const Tensor& require_output(const TensorMap& outputs, const char* name, + std::int32_t expected_width) { + const auto found = outputs.find(name); + if (found == outputs.end()) + throw std::runtime_error(std::string("siglip2 engine did not return ") + name); + const auto& tensor = found->second; + if (tensor.data == nullptr || tensor.dtype != DType::kFloat32 || + tensor.numel() != static_cast(expected_width)) { + throw std::runtime_error(std::string("siglip2 engine returned an unusable ") + name); + } + return tensor; +} + +std::vector l2_normalise(const Tensor& tensor) { + std::vector values(tensor.numel()); + std::memcpy(values.data(), tensor.data, values.size() * sizeof(float)); + const double total = std::inner_product(values.begin(), values.end(), values.begin(), 0.0); + const double norm = std::sqrt(total); + if (!std::isfinite(norm) || norm <= 0.0) + throw std::runtime_error("siglip2 produced an embedding with no direction"); + for (float& value : values) + value = static_cast(value / norm); + return values; +} + +float dot(const std::vector& left, const std::vector& right) { + if (left.size() != right.size()) + throw std::runtime_error("siglip2 embeddings have mismatched widths"); + return static_cast(std::inner_product(left.begin(), left.end(), right.begin(), 0.0)); +} + +void validate_image(const internal::ImageView& image) { + const bool shaped = image.format == internal::ImageFormat::Float32 && image.channels == 3 && + image.data != nullptr && image.height != 0 && image.width != 0; + const auto limit = static_cast(std::numeric_limits::max()); + if (!shaped || image.height > limit || image.width > limit || + static_cast(image.height) > + std::numeric_limits::max() / image.width / 3 / sizeof(float) || + image.byte_size != + static_cast(image.height) * image.width * 3 * sizeof(float)) { + throw std::invalid_argument("siglip2 requires contiguous float32 RGB input"); + } +} + +} // namespace + +Siglip2Pipeline::Siglip2Pipeline(std::unique_ptr vision, + std::unique_ptr text, + std::shared_ptr tokenizer, + Siglip2RuntimeConfig config, std::string primary_task) + : vision_(std::move(vision)), text_(std::move(text)), tokenizer_(std::move(tokenizer)), + config_(std::move(config)), primary_task_(std::move(primary_task)) { + if (!vision_ || !vision_->ok() || !text_ || !text_->ok()) + throw std::runtime_error("Siglip2Pipeline: invalid model"); + if (!tokenizer_) + throw std::runtime_error("Siglip2Pipeline: missing tokenizer"); + // The window is padded with this id, which the text engine looks up like any token. + if (tokenizer_->token_for_id(config_.pad_token_id).empty()) + throw std::runtime_error("siglip2 pad_token_id is not an id of the bundle's tokenizer"); + if (config_.max_text_len <= 0 || config_.embedding_dim <= 0 || config_.pad_token_id < 0 || + !std::isfinite(config_.logit_scale) || config_.logit_scale <= 0.0F || + !std::isfinite(config_.logit_bias)) { + throw std::runtime_error("siglip2 runtime config has invalid dimensions"); + } + if (config_.resample != 2) { + // The runtime reproduces Pillow's bilinear resize only; another filter would move + // every pixel a little and nothing loudly. + throw std::runtime_error("siglip2 is qualified for bilinear resize only"); + } +} + +std::vector Siglip2Pipeline::task_bindings() { + return {internal::bind(*this), + internal::bind(*this), + internal::bind(*this)}; +} + +std::vector Siglip2Pipeline::embed_image(const internal::ImageView& image) { + validate_image(image); + auto patches = preprocess_siglip2_image( + static_cast(image.data), static_cast(image.height), + static_cast(image.width), config_.preprocess); + const auto count = static_cast(patches.grid_height) * + static_cast(patches.grid_width); + const auto table = static_cast(config_.preprocess.position_grid) * + config_.preprocess.position_grid; + + Tensor pixels; + pixels.data = patches.pixel_values.data(); + pixels.shape = {count, static_cast(patches.pixel_values.size()) / count}; + pixels.dtype = DType::kFloat32; + Tensor taps; + taps.data = patches.position_weights.data(); + taps.shape = {count, table}; + taps.dtype = DType::kFloat32; + + auto outputs = vision_->forward({{"pixel_values", pixels}, {"position_weights", taps}}); + return l2_normalise(require_output(outputs, "image_embeds", config_.embedding_dim)); +} + +std::vector Siglip2Pipeline::text_window(std::string_view text) const { + auto ids = tokenizer_->encode(std::string(text)); + if (ids.empty()) + throw std::runtime_error("siglip2 tokenizer returned no tokens"); + + // The window is always filled: the engine pools its LAST row, so an unpadded short + // prompt would be pooled at a different row than the reference pools. An over-long + // prompt keeps its head and its end token, as the reference's truncation does. + const auto limit = static_cast(config_.max_text_len); + const auto end_id = ids.back(); + if (ids.size() > limit) { + ids.resize(limit); + ids.back() = end_id; + } + ids.resize(limit, config_.pad_token_id); + return ids; +} + +std::vector Siglip2Pipeline::embed_text(std::string_view text) { + auto ids = text_window(text); + Tensor input_ids; + input_ids.data = ids.data(); + input_ids.shape = {config_.max_text_len}; + input_ids.dtype = DType::kInt32; + + auto outputs = text_->forward({{"input_ids", input_ids}}); + return l2_normalise(require_output(outputs, "text_embeds", config_.embedding_dim)); +} + +internal::SemanticEmbeddingResult +Siglip2Pipeline::run(const internal::ImageToEmbeddingRequest& request, + internal::ConfigView config) { + if (!config.empty()) + throw internal::ConfigError("siglip2 has no runtime configuration"); + internal::SemanticEmbeddingResult result; + result.values = embed_image(request.image); + result.embedding_space = kEmbeddingSpace; + // Not a row of the sequence: a learned query attends over every patch. + result.pooling = "attention_probe"; + result.normalization = "l2"; + return result; +} + +internal::SemanticEmbeddingResult +Siglip2Pipeline::run(const internal::TextToEmbeddingRequest& request, internal::ConfigView config) { + if (!config.empty()) + throw internal::ConfigError("siglip2 has no runtime configuration"); + if (request.role != internal::EmbeddingRole::Default) { + // One text tower, trained without role prompts: a query and a document + // embedding would be the same vector. + throw std::invalid_argument("siglip2 embeds queries and documents the same way"); + } + internal::SemanticEmbeddingResult result; + result.values = embed_text(request.text); + result.embedding_space = kEmbeddingSpace; + // The last row of the padded window, which is padding for a short prompt. That is + // the checkpoint's rule, not an accident of how this runtime pads. + result.pooling = "last_token"; + result.normalization = "l2"; + return result; +} + +internal::RelevanceResult Siglip2Pipeline::run(const internal::TextImageToRelevanceRequest& request, + internal::ConfigView config) { + if (!config.empty()) + throw internal::ConfigError("siglip2 has no runtime configuration"); + const auto image = embed_image(request.document); + const auto text = embed_text(request.query); + internal::RelevanceResult result; + // SigLIP 2 is trained with a per-pair sigmoid, so its scale and bias calibrate one + // pair on its own: the score is a probability that needs no other candidate. + const float logit = config_.logit_scale * dot(image, text) + config_.logit_bias; + result.score = 1.0F / (1.0F + std::exp(-logit)); + result.kind = internal::ScoreKind::Probability; + return result; +} + +} // namespace trtmc diff --git a/families/siglip2/runtime/pipeline.h b/families/siglip2/runtime/pipeline.h new file mode 100644 index 0000000000..17e05c1b79 --- /dev/null +++ b/families/siglip2/runtime/pipeline.h @@ -0,0 +1,71 @@ +/* + * SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. + * SPDX-License-Identifier: Apache-2.0 + */ + +#pragma once + +#include "families/siglip2/runtime/naflex_preprocess.h" +#include "families/siglip2/runtime/tokenizer.h" +#include "trtmc/internal/features.h" +#include "trtmc/internal/model.h" +#include "trtmc/runtime/trt_module.h" + +#include +#include +#include + +namespace trtmc { + +struct Siglip2RuntimeConfig { + Siglip2PreprocessConfig preprocess; + std::int32_t resample{2}; + std::int32_t max_text_len{64}; + std::int32_t embedding_dim{768}; + std::int32_t pad_token_id{0}; + float logit_scale{1.0F}; + float logit_bias{0.0F}; +}; + +namespace siglip2 { +// Reads the bundle's runtime.json; a field of another JSON type or out of range is refused. +Siglip2RuntimeConfig parse_runtime_config(const std::vector& data); +} // namespace siglip2 + +// One model, three tasks: either tower can be asked for its own embedding, or the two +// can be scored against each other. Each task runs only the towers it needs, which is +// why the bundle keeps the engines apart. +class Siglip2Pipeline final : public internal::IModel, + public internal::IImageToEmbedding, + public internal::ITextToEmbedding, + public internal::ITextImageToRelevance { + public: + Siglip2Pipeline(std::unique_ptr vision, std::unique_ptr text, + std::shared_ptr tokenizer, Siglip2RuntimeConfig config, + std::string primary_task); + + const char* task() const noexcept override { return primary_task_.c_str(); } + std::vector task_bindings() override; + + internal::SemanticEmbeddingResult run(const internal::ImageToEmbeddingRequest& request, + internal::ConfigView config) override; + internal::SemanticEmbeddingResult run(const internal::TextToEmbeddingRequest& request, + internal::ConfigView config) override; + internal::RelevanceResult run(const internal::TextImageToRelevanceRequest& request, + internal::ConfigView config) override; + + // The padded window the text engine receives for `text`; exposed for unit tests. + std::vector text_window(std::string_view text) const; + + private: + std::vector embed_image(const internal::ImageView& image); + std::vector embed_text(std::string_view text); + + std::unique_ptr vision_; + std::unique_ptr text_; + std::shared_ptr tokenizer_; + Siglip2RuntimeConfig config_; + std::string primary_task_; +}; + +} // namespace trtmc diff --git a/families/siglip2/runtime/plugin.cpp b/families/siglip2/runtime/plugin.cpp new file mode 100644 index 0000000000..f3f7be7cc2 --- /dev/null +++ b/families/siglip2/runtime/plugin.cpp @@ -0,0 +1,137 @@ +/* + * SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. + * SPDX-License-Identifier: Apache-2.0 + */ + +#include "families/siglip2/runtime/pipeline.h" +#include "trtmc/runtime/family_factory.h" +#include "trtmc/runtime/trt_backend.h" + +#include +#include +#include +#include +#include +#include +#include +#include + +namespace trtmc::siglip2 { +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); +} + +// The fields of runtime.json are taken only with their own JSON type and range: a fraction, a +// bool, a string or a wider value is refused, never converted into the field. +std::int32_t int32_field(const nlohmann::json& json, const char* name) { + const auto& value = json.at(name); + const bool fits = value.is_number_unsigned() + ? value.get() <= static_cast(INT32_MAX) + : value.is_number_integer() && value.get() >= INT32_MIN && + value.get() <= INT32_MAX; + if (!fits) + throw std::runtime_error(std::string("siglip2 runtime.json ") + name + + " is not an int32 integer"); + return static_cast(value.get()); +} + +template +T number_field(const nlohmann::json& value, const char* name) { + if (!value.is_number() || + !(std::fabs(value.get()) <= static_cast(std::numeric_limits::max()))) + throw std::runtime_error(std::string("siglip2 runtime.json ") + name + + " is not a finite number in range"); + return static_cast(value.get()); +} + +std::vector triple(const nlohmann::json& json, const char* name) { + const auto& values = json.at(name); + if (!values.is_array() || values.size() != 3) + throw std::runtime_error(std::string("siglip2 runtime.json has invalid ") + name); + std::vector result; + for (const auto& value : values) + result.push_back(number_field(value, name)); + return result; +} + +} // namespace + +Siglip2RuntimeConfig parse_runtime_config(const std::vector& data) { + const auto json = nlohmann::json::parse(data.begin(), data.end()); + Siglip2RuntimeConfig config; + config.preprocess.patch_size = int32_field(json, "patch_size"); + config.preprocess.max_num_patches = int32_field(json, "max_num_patches"); + config.preprocess.position_grid = int32_field(json, "position_grid"); + config.preprocess.rescale_factor = + number_field(json.at("rescale_factor"), "rescale_factor"); + config.preprocess.image_mean = triple(json, "image_mean"); + config.preprocess.image_std = triple(json, "image_std"); + config.resample = int32_field(json, "resample"); + config.max_text_len = int32_field(json, "max_text_len"); + config.embedding_dim = int32_field(json, "embedding_dim"); + config.pad_token_id = int32_field(json, "pad_token_id"); + config.logit_scale = number_field(json.at("logit_scale"), "logit_scale"); + config.logit_bias = number_field(json.at("logit_bias"), "logit_bias"); + if (config.preprocess.patch_size <= 0 || config.preprocess.max_num_patches <= 0 || + config.preprocess.position_grid <= 0 || !(config.preprocess.rescale_factor > 0.0) || + config.max_text_len <= 0 || config.embedding_dim <= 0 || config.pad_token_id < 0 || + !(config.logit_scale > 0.0F)) { + throw std::runtime_error("siglip2 runtime.json does not match its runtime contract"); + } + for (const float deviation : config.preprocess.image_std) { + if (deviation == 0.0F) + throw std::runtime_error("siglip2 runtime.json image_std must be nonzero"); + } + return config; +} + +namespace { + +std::unique_ptr load_engine(IBackend& backend, const std::vector& plan, + const char* what) { + ModuleCreateOptions options{}; + auto engine = backend.create_module(plan.data(), plan.size(), options); + if (!engine || !engine->ok()) + throw std::runtime_error(std::string("siglip2 ") + what + " engine failed to load"); + return engine; +} + +std::string require_task(const BundleReader& bundle) { + const auto& task = bundle.info().task; + if (task != internal::IImageToEmbedding::kTask && task != internal::ITextToEmbedding::kTask && + task != internal::ITextImageToRelevance::kTask) { + throw std::runtime_error("siglip2 bundle declares an unsupported task: " + task); + } + return task; +} + +} // namespace +} // namespace trtmc::siglip2 + +extern "C" trtmc::ITask* trtmc_create_family(const trtmc::FamilyContext& context) { + if (context.kv_cache_size_bytes != 0) + throw std::invalid_argument("siglip2 does not support --kv-cache-size"); + const auto config_data = trtmc::siglip2::require_section(context.reader, "runtime.json"); + const auto vision_plan = trtmc::siglip2::require_section(context.reader, "vision.plan"); + const auto text_plan = trtmc::siglip2::require_section(context.reader, "text.plan"); + const auto tokenizer_data = trtmc::siglip2::require_section(context.reader, "tokenizer.json"); + + auto config = trtmc::siglip2::parse_runtime_config(config_data); + auto primary_task = trtmc::siglip2::require_task(context.reader); + auto tokenizer = + trtmc::siglip2::CreateSiglip2Tokenizer(tokenizer_data.data(), tokenizer_data.size(), + /*add_special_tokens=*/true); + if (!tokenizer) + throw std::runtime_error("siglip2 tokenizer failed to load"); + auto vision = trtmc::siglip2::load_engine(context.backend, vision_plan, "vision"); + auto text = trtmc::siglip2::load_engine(context.backend, text_plan, "text"); + return new trtmc::Siglip2Pipeline( + std::move(vision), std::move(text), + std::shared_ptr(std::move(tokenizer)), std::move(config), + std::move(primary_task)); +} diff --git a/families/siglip2/runtime/tokenizer.h b/families/siglip2/runtime/tokenizer.h new file mode 100644 index 0000000000..9e2fa31c62 --- /dev/null +++ b/families/siglip2/runtime/tokenizer.h @@ -0,0 +1,28 @@ +/* + * SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. + * SPDX-License-Identifier: Apache-2.0 + */ + +#pragma once + +#include +#include +#include +#include +#include + +namespace trtmc::siglip2 { + +class ITokenizer { + public: + virtual ~ITokenizer() = default; + virtual std::vector encode(const std::string& text) const = 0; + virtual std::int32_t id_for_token(std::string_view token) const = 0; + virtual std::string token_for_id(std::int32_t id) const = 0; +}; + +std::unique_ptr CreateSiglip2Tokenizer(const char* tokenizer_json_data, + std::size_t tokenizer_json_size, + bool add_special_tokens = false); + +} // namespace trtmc::siglip2 diff --git a/families/siglip2/support.py b/families/siglip2/support.py new file mode 100644 index 0000000000..8aa0f1e061 --- /dev/null +++ b/families/siglip2/support.py @@ -0,0 +1,14 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +"""Family-owned model and task support for SigLIP 2 NaFlex (``Siglip2Model``).""" + +from tensorrt_model_connect.model_support import family_support + + +describe = family_support( + model_types=("siglip2",), + architectures=("Siglip2Model",), + tasks=("image_to_embedding", "text_to_embedding", "text_image_to_relevance"), + default_task="text_image_to_relevance", +) diff --git a/families/siglip2/tests/__init__.py b/families/siglip2/tests/__init__.py new file mode 100644 index 0000000000..537cf769bb --- /dev/null +++ b/families/siglip2/tests/__init__.py @@ -0,0 +1,4 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +"""siglip2 family tests.""" diff --git a/families/siglip2/tests/cpp/preprocess_dump.cpp b/families/siglip2/tests/cpp/preprocess_dump.cpp new file mode 100644 index 0000000000..fb3de77f8e --- /dev/null +++ b/families/siglip2/tests/cpp/preprocess_dump.cpp @@ -0,0 +1,54 @@ +/* + * SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. + * SPDX-License-Identifier: Apache-2.0 + */ + +// Runs the runtime's NaFlex preprocessing on one raw 8-bit RGB image and writes what the +// vision engine would receive, so the family test can compare it with the reference +// processor value for value. +// +// usage: siglip2_preprocess_dump +// +// out.bin: int32 grid_height, int32 grid_width, float32 pixel_values, float32 taps. + +#include "families/siglip2/runtime/naflex_preprocess.h" +#include "families/siglip2/tests/cpp/preprocess_dump_io.h" + +#include +#include +#include +#include +#include +#include +#include + +int main(int argc, char** argv) { + try { + if (argc != 14) + throw std::invalid_argument("expected 13 arguments, see the source header"); + const auto height = std::stoi(argv[2]); + const auto width = std::stoi(argv[3]); + trtmc::Siglip2PreprocessConfig config; + config.patch_size = std::stoi(argv[4]); + config.max_num_patches = std::stoi(argv[5]); + config.position_grid = std::stoi(argv[6]); + config.image_mean = {std::stof(argv[7]), std::stof(argv[8]), std::stof(argv[9])}; + config.image_std = {std::stof(argv[10]), std::stof(argv[11]), std::stof(argv[12])}; + + std::ifstream input(argv[1], std::ios::binary); + const std::vector bytes((std::istreambuf_iterator(input)), + std::istreambuf_iterator()); + if (bytes.size() != static_cast(height) * width * 3) + throw std::invalid_argument("raw image size does not match height x width x 3"); + std::vector rgb(bytes.size()); + for (std::size_t index = 0; index < bytes.size(); ++index) + rgb[index] = static_cast(bytes[index]) / 255.0F; + + const auto patches = trtmc::preprocess_siglip2_image(rgb.data(), height, width, config); + trtmc::write_siglip2_preprocess_dump(argv[13], patches); + } catch (const std::exception& error) { + std::cerr << error.what() << '\n'; + return 1; + } + return 0; +} diff --git a/families/siglip2/tests/cpp/preprocess_dump_io.h b/families/siglip2/tests/cpp/preprocess_dump_io.h new file mode 100644 index 0000000000..2d1fcbd493 --- /dev/null +++ b/families/siglip2/tests/cpp/preprocess_dump_io.h @@ -0,0 +1,32 @@ +/* + * SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. + * SPDX-License-Identifier: Apache-2.0 + */ +// The file siglip2_preprocess_dump writes: int32 grid_height, int32 grid_width, float32 +// pixel_values, float32 taps. +#pragma once + +#include "families/siglip2/runtime/naflex_preprocess.h" + +#include +#include +#include +#include + +namespace trtmc { + +inline void write_siglip2_preprocess_dump(const std::string& path, const Siglip2Patches& patches) { + std::ofstream output(path, std::ios::binary); + output.write(reinterpret_cast(&patches.grid_height), sizeof(std::int32_t)); + output.write(reinterpret_cast(&patches.grid_width), sizeof(std::int32_t)); + output.write(reinterpret_cast(patches.pixel_values.data()), + static_cast(patches.pixel_values.size() * sizeof(float))); + output.write(reinterpret_cast(patches.position_weights.data()), + static_cast(patches.position_weights.size() * sizeof(float))); + // A short write may only fail when the last buffer is flushed: close before checking. + output.close(); + if (!output) + throw std::runtime_error("could not write the output file"); +} + +} // namespace trtmc diff --git a/families/siglip2/tests/cpp/test_naflex_preprocess.cpp b/families/siglip2/tests/cpp/test_naflex_preprocess.cpp new file mode 100644 index 0000000000..ff36affcc9 --- /dev/null +++ b/families/siglip2/tests/cpp/test_naflex_preprocess.cpp @@ -0,0 +1,723 @@ +/* + * SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. + * SPDX-License-Identifier: Apache-2.0 + */ + +// NaFlex host preprocessing against values produced by the reference implementations: +// the processor's patch-budget search, Pillow's 8-bit bilinear resize and torch's +// antialiased bilinear interpolation of the position table. + +#include "families/siglip2/runtime/naflex_preprocess.h" +#include "families/siglip2/tests/cpp/preprocess_dump_io.h" + +#include +#include +#include +#include +#include +#include + +namespace { + +struct TargetCase { + std::int32_t height; + std::int32_t width; + std::int32_t patch; + std::int32_t budget; + std::int32_t target_height; + std::int32_t target_width; +}; + +// Generated by the reference: transformers 5.2.0 get_image_size_for_max_num_patches, +// Pillow 13.0.0 Image.resize(BILINEAR) and torch 2.12.0 F.interpolate(antialias=True). +const TargetCase kTargetCases[] = { + {382, 640, 16, 256, 192, 336}, {640, 382, 16, 256, 336, 192}, {224, 224, 16, 256, 256, 256}, + {37, 53, 16, 256, 208, 304}, {1, 1, 16, 256, 112, 112}, {3000, 20, 16, 256, 2400, 16}, + {20, 3000, 16, 256, 16, 2400}, {1080, 1920, 16, 256, 192, 336}, {100, 1000, 16, 256, 80, 800}, + {480, 640, 16, 1024, 432, 576}, {17, 999, 14, 196, 28, 1372}, {512, 512, 16, 64, 128, 128}, +}; +const std::vector kResize3x4 = { + 22, 93, 164, 40, 111, 182, 61, 132, 203, 78, 149, 220, 81, 152, 196, 101, 172, 186, + 124, 195, 107, 142, 213, 85, 140, 211, 83, 162, 193, 48, 182, 107, 68, 199, 124, 85}; +const std::vector kResize8x11 = { + 0, 71, 142, 5, 76, 147, 12, 83, 154, 19, 90, 161, 26, 97, 168, 33, 104, 175, 40, + 111, 182, 47, 118, 189, 54, 125, 196, 61, 132, 203, 66, 137, 208, 16, 87, 158, 21, 92, + 163, 29, 100, 171, 36, 107, 178, 43, 114, 185, 51, 122, 193, 58, 129, 200, 65, 136, 207, + 72, 143, 214, 80, 151, 222, 85, 156, 227, 39, 110, 181, 44, 115, 186, 52, 123, 194, 60, + 131, 202, 68, 139, 210, 76, 147, 218, 84, 155, 215, 91, 162, 217, 99, 170, 225, 107, 178, + 233, 112, 183, 238, 62, 133, 204, 68, 139, 210, 76, 147, 218, 84, 155, 226, 93, 164, 235, + 101, 172, 243, 109, 180, 138, 117, 188, 83, 125, 196, 91, 133, 204, 99, 139, 210, 105, 86, + 157, 228, 92, 163, 197, 100, 171, 162, 108, 179, 170, 117, 188, 179, 126, 197, 188, 134, 205, + 84, 142, 213, 28, 147, 218, 33, 155, 226, 41, 161, 232, 47, 109, 180, 251, 115, 186, 148, + 124, 195, 26, 133, 204, 35, 142, 213, 44, 151, 222, 53, 159, 230, 51, 165, 236, 51, 166, + 237, 52, 174, 245, 60, 180, 251, 66, 132, 203, 130, 138, 209, 86, 147, 218, 33, 157, 228, + 43, 166, 185, 52, 176, 103, 62, 180, 107, 66, 185, 112, 71, 191, 118, 77, 200, 127, 86, + 206, 133, 92, 148, 219, 34, 155, 226, 41, 164, 235, 50, 174, 245, 60, 183, 161, 69, 193, + 8, 79, 194, 9, 80, 199, 14, 85, 209, 24, 95, 218, 33, 104, 225, 40, 111}; +const std::vector kResize5x2 = {17, 88, 159, 49, 120, 191, 56, 127, 198, 90, + 161, 232, 95, 166, 219, 131, 202, 77, 133, 204, + 73, 166, 237, 52, 171, 182, 57, 204, 37, 90}; +const std::vector kResize2x7 = {37, 108, 179, 49, 120, 179, 61, 132, 191, 73, 144, + 203, 85, 156, 157, 96, 167, 169, 108, 179, 181, 111, + 182, 172, 125, 196, 81, 139, 210, 95, 153, 143, 109, + 163, 152, 60, 172, 161, 69, 186, 175, 83}; +// Pillow 13 resamples vertically first when the height shrinks by more than twice as +// many pixels as the width; these two cases take that order. +const std::vector kResize9x5to3x4 = { + 49, 120, 183, 64, 135, 174, 78, 149, 188, 92, 163, 154, 152, 138, 109, 158, 155, 83, + 156, 120, 98, 168, 97, 90, 95, 70, 141, 85, 87, 158, 61, 100, 171, 74, 113, 184}; +const std::vector kResize12x6to4x5 = { + 49, 120, 184, 63, 134, 173, 77, 148, 187, 91, 162, 160, 104, 175, 150, + 151, 137, 110, 158, 154, 82, 155, 127, 98, 167, 96, 91, 180, 108, 94, + 92, 78, 149, 89, 95, 166, 65, 108, 179, 78, 120, 173, 91, 133, 176, + 109, 180, 91, 129, 200, 111, 138, 177, 120, 150, 157, 91, 163, 170, 81}; +const std::vector kTaps16to14 = { + 0.833333313, 0.166666716, 0, 0, 0, + 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, + 0, 0, 0.72222209, 0.27777794, 0, + 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0.611111045, + 0.388888955, 0, 0, 0, 0, + 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, + 0, 0.5, 0.5, 0, 0, + 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, + 0, 0, 0, 0.388888627, 0.611111403, + 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, + 0.277777553, 0.722222507, 0, 0, 0, + 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, + 0, 0, 0.157894552, 0.789473712, 0.0526318178, + 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0.0526311472, + 0.789473474, 0.157895356, 0, 0, 0, + 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, + 0, 0, 0.72222209, 0.27777794, 0, + 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0.611110687, + 0.388889372, 0, 0, 0, 0, + 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, + 0, 0.499999255, 0.500000715, 0, 0, + 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, + 0, 0, 0, 0.388888627, 0.611111403, + 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, + 0.277777195, 0.722222865, 0, 0, 0, + 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, + 0, 0, 0.166666508, 0.833333552}; +const std::vector kTaps16to21 = {1, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0.357142806, + 0.642857194, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0.59523809, + 0.40476191, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0.833333254, + 0.166666746, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0.0714285374, + 0.928571463, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0.309523582, + 0.690476418, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0.547618866, + 0.452381134, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0.785714149, + 0.214285851, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0.023809433, + 0.976190567, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0.261904716, + 0.738095284, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0.5, + 0.5, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0.738095284, + 0.261904716, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0.976190567, + 0.023809433, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0.214285851, + 0.785714149, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0.452381134, + 0.547618866, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0.690476418, + 0.309523582, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0.928570747, + 0.0714292526, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0.166666031, + 0.833333969, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0.404761314, + 0.595238686, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0.642856598, + 0.357143402, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 1}; +const std::vector kTaps16to5 = {0.230769232, + 0.34065935, + 0.252747267, + 0.142857149, + 0.0329670347, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0.0882352814, + 0.186274499, + 0.284313738, + 0.245098069, + 0.147058859, + 0.049019631, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0.0686274543, + 0.166666672, + 0.264705896, + 0.264705896, + 0.166666672, + 0.0686274543, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0.0490196235, + 0.14705883, + 0.24509804, + 0.284313679, + 0.186274484, + 0.0882352665, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0.0329669714, + 0.142857075, + 0.252747178, + 0.34065941, + 0.230769292}; +const std::vector kTaps16to1 = {0.0442708321, 0.0494791679, 0.0546875, 0.0598958321, + 0.0651041642, 0.0703125, 0.0755208358, 0.0807291642, + 0.0807291642, 0.0755208358, 0.0703125, 0.0651041642, + 0.0598958321, 0.0546875, 0.0494791679, 0.0442708321}; + +void require(bool condition, const std::string& what) { + if (!condition) + throw std::runtime_error(what); +} + +std::vector synthetic(std::int32_t height, std::int32_t width) { + std::vector image(static_cast(height) * width * 3); + for (std::int32_t y = 0; y < height; ++y) + for (std::int32_t x = 0; x < width; ++x) + for (std::int32_t c = 0; c < 3; ++c) + image[(static_cast(y) * width + x) * 3 + c] = + static_cast((y * 37 + x * 11 + c * 71 + (y * x) % 13) % 256); + return image; +} + +void test_target_sizes() { + for (const auto& item : kTargetCases) { + const auto [height, width] = + trtmc::siglip2_target_size(item.height, item.width, item.patch, item.budget); + require(height == item.target_height && width == item.target_width, + "target size of " + std::to_string(item.height) + "x" + std::to_string(item.width) + + " is " + std::to_string(height) + "x" + std::to_string(width)); + } +} + +void test_pillow_bilinear() { + const auto source = synthetic(5, 7); + const struct { + std::int32_t height; + std::int32_t width; + const std::vector* expected; + } cases[] = { + {3, 4, &kResize3x4}, {8, 11, &kResize8x11}, {5, 2, &kResize5x2}, {2, 7, &kResize2x7}}; + for (const auto& item : cases) { + const auto resized = + trtmc::siglip2_resize_bilinear(source.data(), 5, 7, item.height, item.width); + require(resized == *item.expected, "Pillow bilinear differs at " + + std::to_string(item.height) + "x" + + std::to_string(item.width)); + } + const struct { + std::int32_t height; + std::int32_t width; + std::int32_t out_height; + std::int32_t out_width; + const std::vector* expected; + } vertical_first[] = {{9, 5, 3, 4, &kResize9x5to3x4}, {12, 6, 4, 5, &kResize12x6to4x5}}; + for (const auto& item : vertical_first) { + const auto image = synthetic(item.height, item.width); + const auto resized = trtmc::siglip2_resize_bilinear(image.data(), item.height, item.width, + item.out_height, item.out_width); + require(resized == *item.expected, "Pillow vertical-first order differs at " + + std::to_string(item.height) + "x" + + std::to_string(item.width)); + } + // An unchanged size is a copy, as Pillow returns it. + require(trtmc::siglip2_resize_bilinear(source.data(), 5, 7, 5, 7) == source, + "identity resize changed pixels"); +} + +void test_axis_taps() { + const struct { + std::int32_t output; + const std::vector* expected; + } cases[] = {{14, &kTaps16to14}, {21, &kTaps16to21}, {5, &kTaps16to5}, {1, &kTaps16to1}}; + for (const auto& item : cases) { + const auto taps = trtmc::siglip2_axis_taps(16, item.output); + require(taps.size() == item.expected->size(), "tap matrix shape"); + for (std::size_t index = 0; index < taps.size(); ++index) { + // torch builds the taps in float32; these are built in double. + require(std::abs(taps[index] - (*item.expected)[index]) <= 1e-6, + "taps 16->" + std::to_string(item.output) + " differ at " + + std::to_string(index)); + } + } +} + +void test_patch_layout_and_normalisation() { + // 32x48 fits a budget of six 16-pixel patches as it is, so nothing is resampled and + // every value can be traced back to its source pixel. + trtmc::Siglip2PreprocessConfig config; + config.max_num_patches = 6; + config.image_mean = {0.25F, 0.5F, 0.75F}; + config.image_std = {0.5F, 0.25F, 2.0F}; + const auto bytes = synthetic(32, 48); + std::vector rgb(bytes.size()); + for (std::size_t index = 0; index < bytes.size(); ++index) + rgb[index] = static_cast(bytes[index]) / 255.0F; + + const auto patches = trtmc::preprocess_siglip2_image(rgb.data(), 32, 48, config); + require(patches.grid_height == 2 && patches.grid_width == 3, "grid of a 32x48 image"); + require(patches.pixel_values.size() == 6U * 16 * 16 * 3, "pixel value count"); + std::size_t index = 0; + for (std::int32_t py = 0; py < 2; ++py) + for (std::int32_t px = 0; px < 3; ++px) + for (std::int32_t ry = 0; ry < 16; ++ry) + for (std::int32_t rx = 0; rx < 16; ++rx) + for (std::int32_t c = 0; c < 3; ++c) { + const auto byte = bytes[(static_cast(py * 16 + ry) * 48 + + static_cast(px * 16 + rx)) * + 3 + + c]; + // numpy rescales in float64 (x * (1/255)) and normalises in float32. + const auto scaled = + static_cast(static_cast(byte) * (1.0 / 255.0)); + const float expected = + (scaled - config.image_mean[c]) / config.image_std[c]; + require(patches.pixel_values[index++] == expected, + "patch layout or normalisation differs"); + } + + // The taps are the outer product of the two axes, one row per patch. + require(patches.position_weights.size() == 6U * 256, "position tap count"); + const auto rows = trtmc::siglip2_axis_taps(16, 2); + const auto columns = trtmc::siglip2_axis_taps(16, 3); + for (std::int32_t y = 0; y < 2; ++y) + for (std::int32_t x = 0; x < 3; ++x) + for (std::int32_t sy = 0; sy < 16; ++sy) + for (std::int32_t sx = 0; sx < 16; ++sx) { + const auto expected = + static_cast(rows[y * 16 + sy] * columns[x * 16 + sx]); + require(patches.position_weights[((y * 3 + x) * 16 + sy) * 16 + sx] == expected, + "position taps are not the outer product"); + } +} + +void test_rejections() { + trtmc::Siglip2PreprocessConfig config; + const float pixel[3] = {0.0F, 0.0F, 0.0F}; + bool thrown = false; + try { + config.image_std = {0.5F, 0.0F, 0.5F}; + trtmc::preprocess_siglip2_image(pixel, 1, 1, config); + } catch (const std::invalid_argument&) { + thrown = true; + } + require(thrown, "zero deviation was accepted"); + thrown = false; + try { + trtmc::siglip2_target_size(0, 4, 16, 256); + } catch (const std::invalid_argument&) { + thrown = true; + } + require(thrown, "empty image was accepted"); +} + +} // namespace + +// A dump smaller than the stream buffer reaches the file only when the stream is closed; a +// failure there (here: a full device) must still be reported, or the E2E would read a short file. +void test_dump_reports_a_failed_final_write() { + if (!std::ifstream("/dev/full").good()) + return; + // Small enough to stay in the stream's buffer until close(), so the device reports the + // failure only when close() flushes it: the writer must check the stream after closing. + trtmc::Siglip2Patches patches; + patches.grid_height = 1; + patches.grid_width = 1; + patches.pixel_values.assign(4, 0.5F); + patches.position_weights.assign(1, 1.0F); + bool reported = false; + try { + trtmc::write_siglip2_preprocess_dump("/dev/full", patches); + } catch (const std::runtime_error&) { + reported = true; + } + require(reported, "a dump written to a full device was not reported"); +} + +int main() { + try { + test_target_sizes(); + test_pillow_bilinear(); + test_axis_taps(); + test_patch_layout_and_normalisation(); + test_rejections(); + test_dump_reports_a_failed_final_write(); + } catch (const std::exception& error) { + std::cerr << error.what() << '\n'; + return 1; + } + return 0; +} diff --git a/families/siglip2/tests/cpp/test_pipeline.cpp b/families/siglip2/tests/cpp/test_pipeline.cpp new file mode 100644 index 0000000000..5dc224b019 --- /dev/null +++ b/families/siglip2/tests/cpp/test_pipeline.cpp @@ -0,0 +1,273 @@ +/* + * SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. + * SPDX-License-Identifier: Apache-2.0 + */ + +// The pipeline's own rules, with fixture engines: what each engine receives, the padded +// text window, normalisation, the per-pair sigmoid and the refusals. + +#include "families/siglip2/runtime/pipeline.h" + +#include +#include +#include +#include +#include +#include +#include + +namespace { + +void require(bool condition, const std::string& what) { + if (!condition) + throw std::runtime_error(what); +} + +class FixtureModule final : public trtmc::ITrtModule { + public: + explicit FixtureModule(std::string output) : output_(std::move(output)) {} + std::vector values = {3.0F, 0.0F, 4.0F, 0.0F}; + trtmc::TensorMap seen; + std::vector> ids_seen; + std::vector> pixel_shapes; + std::vector> tap_shapes; + + trtmc::TensorMap forward(const trtmc::TensorMap& inputs) override { + if (inputs.count("input_ids")) { + const auto& ids = inputs.at("input_ids"); + const auto* data = static_cast(ids.data); + ids_seen.emplace_back(data, data + ids.numel()); + } else { + pixel_shapes.push_back(inputs.at("pixel_values").shape); + tap_shapes.push_back(inputs.at("position_weights").shape); + } + trtmc::Tensor out; + out.data = values.data(); + out.shape = {1, static_cast(values.size())}; + out.dtype = trtmc::DType::kFloat32; + return {{output_, out}}; + } + 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&) const override { return true; } + bool has_output(const std::string&) const override { return true; } + trtmc::DType tensor_dtype(const std::string&) const override { return trtmc::DType::kFloat32; } + std::vector tensor_shape(const std::string&) const override { return {}; } + std::vector input_profile_shape(const std::string&, int32_t, + trtmc::ProfileShapeSelector) const override { + return {}; + } + int32_t optimization_profile_count() const override { return 1; } + void* device_ptr(const std::string&) const override { return nullptr; } + void bind_external(const std::string&, void*) override {} + void bind_external(const std::string&, void*, const std::vector&) override {} + int32_t input_rank(const std::string&) const override { return 2; } + bool input_is_dynamic(const std::string&) const override { return true; } + 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 {} + + private: + std::string output_; +}; + +class FixtureTokenizer final : public trtmc::siglip2::ITokenizer { + public: + std::vector ids{7, 8, 1}; + std::vector encode(const std::string&) const override { return ids; } + std::int32_t id_for_token(std::string_view) const override { return -1; } + // A vocabulary of ids 0..15. + std::string token_for_id(std::int32_t id) const override { + return id >= 0 && id < 16 ? "t" : std::string{}; + } +}; + +struct Fixture { + FixtureModule* vision; + FixtureModule* text; + std::shared_ptr tokenizer; + std::unique_ptr pipeline; +}; + +Fixture make(trtmc::Siglip2RuntimeConfig config = {}) { + config.max_text_len = 4; + config.embedding_dim = 4; + config.logit_scale = 10.0F; + config.logit_bias = -2.0F; + auto vision = std::make_unique("image_embeds"); + auto text = std::make_unique("text_embeds"); + auto tokenizer = std::make_shared(); + Fixture fixture{vision.get(), text.get(), tokenizer, nullptr}; + fixture.pipeline = std::make_unique( + std::move(vision), std::move(text), tokenizer, config, "text_image_to_relevance"); + return fixture; +} + +trtmc::internal::ImageView image_of(const std::vector& pixels, std::uint32_t height, + std::uint32_t width) { + trtmc::internal::ImageView image; + image.data = pixels.data(); + image.byte_size = pixels.size() * sizeof(float); + image.height = height; + image.width = width; + image.channels = 3; + image.format = trtmc::internal::ImageFormat::Float32; + return image; +} + +void test_text_window() { + auto fixture = make(); + // Short: padded to the window with the pad id after the end token. + require(fixture.pipeline->text_window("x") == std::vector{7, 8, 1, 0}, + "short prompt window"); + // Long: the head is kept and the end token re-appended at the last row. + fixture.tokenizer->ids = {5, 6, 7, 8, 9, 1}; + require(fixture.pipeline->text_window("x") == std::vector{5, 6, 7, 1}, + "long prompt window"); + fixture.tokenizer->ids = {5, 6, 7, 1}; + require(fixture.pipeline->text_window("x") == std::vector{5, 6, 7, 1}, + "exact-length window"); +} + +void test_embeddings_and_relevance() { + auto fixture = make(); + const std::vector pixels(20 * 30 * 3, 0.5F); + const auto image = image_of(pixels, 20, 30); + + trtmc::internal::ImageToEmbeddingRequest image_request{image}; + const auto image_result = fixture.pipeline->run(image_request, {}); + require(image_result.values.size() == 4 && std::abs(image_result.values[0] - 0.6F) < 1e-7F && + std::abs(image_result.values[2] - 0.8F) < 1e-7F, + "image embedding is not L2-normalised"); + require(image_result.pooling == "attention_probe" && image_result.normalization == "l2" && + image_result.embedding_space == "siglip2", + "image embedding metadata"); + // The image is resized to its own grid of 16-pixel patches within the 256 budget. + const auto [height, width] = trtmc::siglip2_target_size(20, 30, 16, 256); + const std::int64_t patches = (height / 16) * (width / 16); + require(fixture.vision->pixel_shapes.back() == std::vector{patches, 768}, + "pixel_values shape"); + require(fixture.vision->tap_shapes.back() == std::vector{patches, 256}, + "position_weights shape"); + + trtmc::internal::TextToEmbeddingRequest text_request{"x", + trtmc::internal::EmbeddingRole::Default}; + const auto text_result = fixture.pipeline->run(text_request, {}); + require(text_result.pooling == "last_token" && text_result.normalization == "l2", + "text embedding metadata"); + require(fixture.text->ids_seen.back() == std::vector{7, 8, 1, 0}, + "text engine did not receive the padded window"); + + trtmc::internal::TextImageToRelevanceRequest pair{"x", image}; + const auto relevance = fixture.pipeline->run(pair, {}); + // Both unit vectors are (0.6, 0, 0.8, 0): cosine 1, logit 10 * 1 - 2 = 8. + require(relevance.kind == trtmc::internal::ScoreKind::Probability, "score kind"); + require(std::abs(relevance.score - 1.0F / (1.0F + std::exp(-8.0F))) < 1e-6F, + "relevance is not sigmoid(scale * cosine + bias)"); +} + +void test_refusals() { + auto fixture = make(); + bool thrown = false; + try { + trtmc::internal::TextToEmbeddingRequest request{"x", trtmc::internal::EmbeddingRole::Query}; + fixture.pipeline->run(request, {}); + } catch (const std::invalid_argument&) { + thrown = true; + } + require(thrown, "a query role was accepted"); + + thrown = false; + try { + const std::vector gray(6, 0.5F); + auto image = image_of(gray, 2, 3); + image.channels = 1; + trtmc::internal::ImageToEmbeddingRequest request{image}; + fixture.pipeline->run(request, {}); + } catch (const std::invalid_argument&) { + thrown = true; + } + require(thrown, "a one-channel image was accepted"); + + thrown = false; + try { + trtmc::Siglip2RuntimeConfig config; + config.resample = 3; + make(config); + } catch (const std::runtime_error&) { + thrown = true; + } + require(thrown, "a bicubic bundle was accepted"); + + thrown = false; + try { + trtmc::Siglip2RuntimeConfig config; + config.pad_token_id = 16; + make(config); + } catch (const std::runtime_error&) { + thrown = true; + } + require(thrown, "a pad id outside the tokenizer's vocabulary was accepted"); +} + +} // namespace + +void test_runtime_config() { + const std::string valid = + R"({"patch_size":16,"max_num_patches":256,"position_grid":16,"image_mean":[0.5,0.5,0.5],)" + R"("image_std":[0.5,0.5,0.5],"resample":2,"rescale_factor":0.00392156862745098,)" + R"("max_text_len":64,"pad_token_id":0,"embedding_dim":768,"logit_scale":117.3,)" + R"("logit_bias":-12.9})"; + const auto parse = [](const std::string& text) { + return trtmc::siglip2::parse_runtime_config(std::vector(text.begin(), text.end())); + }; + require(parse(valid).max_text_len == 64, "a valid runtime.json was refused"); + // A field of another JSON type or beyond its range is refused, not converted: 5.5 would + // pad with token 5, 4294967552 would wrap to 256, true would count as 1 and 1e39 would + // become an infinity. A zero deviation, refused by the builder, is refused here too. + const std::vector> bad = { + {"\"pad_token_id\":0", "\"pad_token_id\":5.5"}, + {"\"max_text_len\":64", "\"max_text_len\":64.0"}, + {"\"max_num_patches\":256", "\"max_num_patches\":4294967552"}, + {"\"patch_size\":16", "\"patch_size\":true"}, + {"\"logit_scale\":117.3", "\"logit_scale\":true"}, + {"\"image_mean\":[0.5,0.5,0.5]", "\"image_mean\":[true,0.5,0.5]"}, + {"\"image_mean\":[0.5,0.5,0.5]", "\"image_mean\":[1e39,0.5,0.5]"}, + {"\"logit_bias\":-12.9", "\"logit_bias\":1e39"}, + {"\"image_std\":[0.5,0.5,0.5]", "\"image_std\":[0.5,0,0.5]"}, + }; + for (const auto& [field, value] : bad) { + std::string text = valid; + text.replace(text.find(field), field.size(), value); + bool thrown = false; + try { + parse(text); + } catch (const std::runtime_error&) { + thrown = true; + } + require(thrown, "runtime.json accepted " + value); + } +} + +int main() { + try { + test_text_window(); + test_embeddings_and_relevance(); + test_refusals(); + test_runtime_config(); + } catch (const std::exception& error) { + std::cerr << error.what() << '\n'; + return 1; + } + return 0; +} diff --git a/families/siglip2/tests/cpp/test_tokenizer.cpp b/families/siglip2/tests/cpp/test_tokenizer.cpp new file mode 100644 index 0000000000..65cc9359d8 --- /dev/null +++ b/families/siglip2/tests/cpp/test_tokenizer.cpp @@ -0,0 +1,317 @@ +/* + * SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. + * SPDX-License-Identifier: Apache-2.0 + */ + +// The SigLIP 2 tokenizer contract on a miniature tokenizer.json of the same shape: a +// byte-fallback BPE whose only normaliser is the space marker, no pre-tokenizer, and a +// template that appends . The real tokenizer.json is exercised by the E2E, whose text +// embeddings are compared with the reference model's. + +#include "families/siglip2/runtime/tokenizer.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace { + +using Json = nlohmann::json; + +constexpr std::int32_t kEos = 1; + +// Like the checkpoint's vocabulary: the pieces, then one byte token per byte in byte +// order, except that the tab's slot holds the tab itself. +std::int32_t byte_id(int byte) { + return 11 + byte; +} + +Json added_token(std::int32_t id, const std::string& content, bool special, + const char* option = nullptr) { + Json token = {{"id", id}, {"content", content}, {"single_word", false}, + {"lstrip", false}, {"rstrip", false}, {"normalized", false}, + {"special", special}}; + if (option != nullptr) + token[option] = true; + return token; +} + +Json miniature() { + Json tokenizer = Json::parse(R"({ + "normalizer":{"type":"Replace","pattern":{"String":" "},"content":"▁"}, + "pre_tokenizer":null, + "post_processor":{"type":"TemplateProcessing", + "single":[{"Sequence":{"id":"A","type_id":0}}, + {"SpecialToken":{"id":"","type_id":0}}], + "special_tokens":{"":{"id":"","ids":[1],"tokens":[""]}}}, + "decoder":{"type":"Sequence","decoders":[ + {"type":"Replace","pattern":{"String":"▁"},"content":" "}, + {"type":"ByteFallback"},{"type":"Fuse"}]}, + "model":{"type":"BPE","byte_fallback":true,"fuse_unk":true,"unk_token":"", + "vocab":{"":0,"":1,"":2,"":3,"▁":4,"a":5,"b":6,"ab":7, + "▁ab":8,"A":9,"aba":10}, + "merges":[["a","b"],["▁","ab"]]} + })"); + tokenizer["added_tokens"] = + Json::array({added_token(0, "", true), added_token(1, "", true), + added_token(2, "", true)}); + auto& vocab = tokenizer["model"]["vocab"]; + for (int byte = 0; byte < 256; ++byte) { + char name[8]; + std::snprintf(name, sizeof(name), "<0x%02X>", byte); + vocab[byte == 0x09 ? std::string("\t") : std::string(name)] = byte_id(byte); + } + return tokenizer; +} + +// Renames a vocabulary entry, keeping its id, so that the ids stay 0..N-1. +void rename_token(Json& tokenizer, const std::string& from, const std::string& to) { + auto& vocab = tokenizer["model"]["vocab"]; + vocab[to] = vocab[from]; + vocab.erase(from); +} + +std::unique_ptr load(const Json& tokenizer) { + const std::string text = tokenizer.dump(); + return trtmc::siglip2::CreateSiglip2Tokenizer(text.data(), text.size(), true); +} + +struct Refusal { + const char* what; + std::function change; + const char* message; +}; + +} // namespace + +int main() { + std::string failures; + try { + const auto tokenizer = load(miniature()); + const auto expect = [&](const std::string& text, const std::vector& ids, + const char* what) { + const auto got = tokenizer->encode(text); + if (got != ids) { + failures += std::string(what) + ": got"; + for (const auto id : got) + failures += " " + std::to_string(id); + failures += "\n"; + } + }; + expect("", {kEos}, "empty text must still carry the end token"); + // No leading marker is prepended: "ab" is one piece, " ab" merges with the marker. + expect("ab", {7, kEos}, "plain piece"); + expect("a ab", {5, 8, kEos}, "space marker merge"); + // Case is preserved: the reference tokenizer for this checkpoint does not lowercase. + expect("A", {9, kEos}, "upper case"); + // A character outside the vocabulary falls back to its UTF-8 bytes; the tab, whose + // byte token the vocabulary leaves out, is an entry of its own. + expect("\xc3\xa9", {byte_id(0xC3), byte_id(0xA9), kEos}, "byte fallback"); + expect("\t", {byte_id(0x09), kEos}, "tab"); + // An added token in the text is matched as itself. + expect("a", {5, kEos, kEos}, "added token"); + // A word that is a vocabulary entry still goes through the merges. + expect("aba", {7, 5, kEos}, "merge path for a vocabulary word"); + // A prompt that ends inside a multi-byte sequence falls back to one token per byte. + expect("a\xc3", {5, byte_id(0xC3), kEos}, "truncated two-byte sequence"); + expect("a\xe2\x82", {5, byte_id(0xE2), byte_id(0x82), kEos}, + "truncated three-byte sequence"); + expect("a\xe2", {5, byte_id(0xE2), kEos}, "three-byte lead at the end"); + expect("a\xf0\x9f", {5, byte_id(0xF0), byte_id(0x9F), kEos}, + "truncated four-byte sequence"); + expect("a\xf0", {5, byte_id(0xF0), kEos}, "four-byte lead at the end"); + // A lead byte without its continuation bytes is one byte: the bytes after it are read + // again, so a tab or a letter keeps its own token. + expect("\xc3\t", {byte_id(0xC3), byte_id(0x09), kEos}, "two-byte lead before a tab"); + expect("\xe2\x82\tb", {byte_id(0xE2), byte_id(0x82), byte_id(0x09), 6, kEos}, + "three-byte lead before a tab"); + expect("\xf0\x9f\x98" + "a", + {byte_id(0xF0), byte_id(0x9F), byte_id(0x98), 5, kEos}, + "four-byte lead before a letter"); + } catch (const std::exception& error) { + failures += std::string("miniature tokenizer: ") + error.what() + "\n"; + } + + // Merges run one at a time, so a pair that a merge forms is merged before the waiting + // pairs it outranks. With (ab, a) ranked before (a, b), the reference tokenises "abab" + // as "aba" + "b", where merging every (a, b) at once would give "ab" + "ab". + try { + Json ranked = miniature(); + ranked["model"]["merges"] = Json::array( + {Json::array({"ab", "a"}), Json::array({"a", "b"}), Json::array({"▁", "ab"})}); + const auto tokenizer = load(ranked); + if (tokenizer->encode("abab") != std::vector{10, 6, kEos}) + failures += "a pair formed by a merge did not take its rank\n"; + if (tokenizer->encode("a ab") != std::vector{5, 8, kEos}) + failures += "merge order: space marker merge\n"; + } catch (const std::exception& error) { + failures += std::string("merge order: ") + error.what() + "\n"; + } + + // The legacy merge format, one "left right" string per rule, reads the same rules. + try { + Json legacy = miniature(); + legacy["model"]["merges"] = Json::array({"a b", "▁ ab"}); + if (load(legacy)->encode("a ab") != std::vector{5, 8, kEos}) + failures += "legacy merge strings\n"; + } catch (const std::exception& error) { + failures += std::string("legacy merge strings: ") + error.what() + "\n"; + } + + // ignore_merges false is the merge path as well ("aba" as "ab" + "a"); the reference skips + // the merges for a vocabulary word only when it is true. + try { + Json merged = miniature(); + merged["model"]["ignore_merges"] = false; + if (load(merged)->encode("aba") != std::vector{7, 5, kEos}) + failures += "ignore_merges false left the merge path\n"; + } catch (const std::exception& error) { + failures += std::string("ignore_merges false: ") + error.what() + "\n"; + } + + // What the runtime would tokenise differently from the reference is refused on load (the + // builder refuses it first), and so is a malformed added-token record. + const std::vector refusals = { + // The reference turns a character with a missing byte token into the unknown token. + {"byte token missing", [](Json& t) { rename_token(t, "<0xAC>", "zz"); }, "<0xAC>"}, + {"ASCII byte token missing", [](Json& t) { rename_token(t, "<0x7A>", "zz"); }, "<0x7A>"}, + {"no byte fallback", [](Json& t) { t["model"]["byte_fallback"] = false; }, + "fall back to bytes"}, + {"single_word", + [](Json& t) { t["added_tokens"].push_back(added_token(7, "ab", false, "single_word")); }, + "sets single_word"}, + {"lstrip", + [](Json& t) { t["added_tokens"].push_back(added_token(7, "ab", false, "lstrip")); }, + "sets lstrip"}, + {"rstrip", + [](Json& t) { t["added_tokens"].push_back(added_token(7, "ab", false, "rstrip")); }, + "sets rstrip"}, + {"normalized", + [](Json& t) { t["added_tokens"].push_back(added_token(7, "ab", false, "normalized")); }, + "sets normalized"}, + // The reference gives an added token in the vocabulary the vocabulary's id. + {"record id is not the vocabulary's", + [](Json& t) { t["added_tokens"].push_back(added_token(5, "ab", false)); }, + "not the vocabulary entry with id 5"}, + {"added token outside the vocabulary", + [](Json& t) { t["added_tokens"].push_back(added_token(300, "", true)); }, + "not the vocabulary entry with id 300"}, + {"template token not special", [](Json& t) { t["added_tokens"][1]["special"] = false; }, + "not a special added token"}, + // The reference appends every id the template token lists. + {"template token expands to two ids", + [](Json& t) { + t["post_processor"]["special_tokens"][""]["ids"] = Json::array({2, 1}); + }, + "exactly its id 1"}, + {"template token expands to another id", + [](Json& t) { t["post_processor"]["special_tokens"][""]["ids"] = Json::array({2}); }, + "exactly its id 1"}, + {"template without special_tokens", + [](Json& t) { t["post_processor"].erase("special_tokens"); }, "exactly its id 1"}, + // The vocabulary is kept as ids 0..N-1 (N = 267 here); the reference takes any id. + {"vocabulary id out of range", [](Json& t) { t["model"]["vocab"]["aba"] = 267; }, + "vocabulary id of aba is not in 0..266"}, + {"vocabulary id beyond int32", [](Json& t) { t["model"]["vocab"]["aba"] = 2147483658ULL; }, + "vocabulary id of aba is not in 0..266"}, + // Without U+2581 in the vocabulary a space would take another encode path. + {"no space marker", + [](Json& t) { + rename_token(t, "▁", "zz"); + rename_token(t, "▁ab", "zab"); + t["model"]["merges"] = Json::array({Json::array({"a", "b"})}); + }, + "no U+2581 space marker"}, + // Settings the runtime does not apply. + {"ignore_merges true", [](Json& t) { t["model"]["ignore_merges"] = true; }, + "model.ignore_merges must be false"}, + {"dropout", [](Json& t) { t["model"]["dropout"] = 0.1; }, "model.dropout must be null"}, + {"subword prefix", [](Json& t) { t["model"]["continuing_subword_prefix"] = "##"; }, + "model.continuing_subword_prefix must be null"}, + {"word suffix", [](Json& t) { t["model"]["end_of_word_suffix"] = ""; }, + "model.end_of_word_suffix must be null"}, + {"model type", [](Json& t) { t["model"]["type"] = "WordPiece"; }, "model.type must be BPE"}, + {"lowercasing normalizer", + [](Json& t) { + t["normalizer"] = + Json{{"type", "Sequence"}, + {"normalizers", Json::array({Json{{"type", "Lowercase"}}, t["normalizer"]})}}; + }, + "the normalizer must only replace spaces"}, + {"no normalizer", [](Json& t) { t["normalizer"] = nullptr; }, + "the normalizer must only replace spaces"}, + {"pre-tokenizer", + [](Json& t) { + t["pre_tokenizer"] = Json{{"type", "Metaspace"}, + {"replacement", "▁"}, + {"prepend_scheme", "always"}, + {"split", true}}; + }, + "pre_tokenizer must be null"}, + {"template without the end token", [](Json& t) { t["post_processor"]["single"].erase(1); }, + "the template must be the sequence followed by one special token"}, + // The reference refuses an item with two operations and every merge rule whose + // operands or result are not vocabulary entries. + {"template item with two operations", + [](Json& t) { + t["post_processor"]["single"][1]["Sequence"] = Json{{"id", "A"}, {"type_id", 0}}; + }, + "the template must be the sequence followed by one special token"}, + {"merge result outside the vocabulary", + [](Json& t) { t["model"]["merges"].push_back(Json::array({"b", "a"})); }, + "merge b a makes ba, which is not in the vocabulary"}, + {"merge operand outside the vocabulary", + [](Json& t) { t["model"]["merges"].push_back(Json::array({"x", "a"})); }, + "merge x a: x is not in the vocabulary"}, + {"merge with three parts", [](Json& t) { t["model"]["merges"].push_back("a b c"); }, + "merge 2 is not one pair"}, + {"merge that is not a pair", + [](Json& t) { t["model"]["merges"].push_back(Json::array({"a"})); }, + "merge 2 is not one pair"}, + {"record without a flag", [](Json& t) { t["added_tokens"][2].erase("normalized"); }, + "no boolean normalized"}, + {"record without content", + [](Json& t) { + auto record = added_token(7, "ab", false); + record.erase("content"); + t["added_tokens"].push_back(record); + }, + "no string content"}, + {"record without id", + [](Json& t) { + auto record = added_token(7, "ab", false); + record.erase("id"); + t["added_tokens"].push_back(record); + }, + "ab has no valid id"}, + {"record with a negative id", + [](Json& t) { t["added_tokens"].push_back(added_token(-1, "ab", false)); }, + "ab has no valid id"}, + }; + for (const auto& refusal : refusals) { + Json tokenizer = miniature(); + refusal.change(tokenizer); + try { + load(tokenizer); + failures += std::string(refusal.what) + ": loaded\n"; + } catch (const std::runtime_error& error) { + if (std::string(error.what()).find(refusal.message) == std::string::npos) + failures += std::string(refusal.what) + ": " + error.what() + "\n"; + } catch (const std::exception& error) { + failures += std::string(refusal.what) + ": " + error.what() + "\n"; + } + } + + if (!failures.empty()) { + std::cerr << failures; + return 1; + } + return 0; +} diff --git a/families/siglip2/tests/data/test_img.png b/families/siglip2/tests/data/test_img.png new file mode 100644 index 0000000000..517bec879b Binary files /dev/null and b/families/siglip2/tests/data/test_img.png differ diff --git a/families/siglip2/tests/manifests/siglip2-base-patch16-naflex.json b/families/siglip2/tests/manifests/siglip2-base-patch16-naflex.json new file mode 100644 index 0000000000..eb5c27fe06 --- /dev/null +++ b/families/siglip2/tests/manifests/siglip2-base-patch16-naflex.json @@ -0,0 +1,26 @@ +{ + "name": "siglip2-base-patch16-naflex", + "hf_id": "google/siglip2-base-patch16-naflex", + "hf_revision": "b53b807d3a2d5e2b3911292f2d69e5341cdc064c", + "bundle": "siglip2-base-patch16-naflex.bundle", + "family": "siglip2", + "task": "text_image_to_relevance", + "precision": "fp32", + "testcases": [ + { + "name": "siglip2-base-patch16-naflex", + "premerge": true, + "test_image": "data/test_img.png", + "image_crops": [[220, 0, 420, 382], [300, 150, 340, 180]], + "query": "a photo of a car", + "negative_query": "a photo of a cat", + "texts": [ + "A White Car Parked On A Coastal Road", + "une voiture blanche au bord de la mer", + "海边的一辆白色汽车", + "a photo of a white electric car parked on a dirt road above the ocean, with hills, dry grass, a blue sky and a few clouds behind it, taken on a sunny afternoon in late summer near the coast of california, where the road winds along the cliffs and the waves break on the rocks far below while a light breeze moves the tall grass on the slope next to the car" + ] + } + ], + "tensor_parallel_size": 1 +} diff --git a/families/siglip2/tests/test_e2e.py b/families/siglip2/tests/test_e2e.py new file mode 100644 index 0000000000..70a1e3db66 --- /dev/null +++ b/families/siglip2/tests/test_e2e.py @@ -0,0 +1,448 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +"""Direct build, native-runtime and official-reference E2E for SigLIP 2 NaFlex. + +One bundle serves all three tasks, so the native side is exercised through ``--task``: +the image tower alone on three aspect ratios (a landscape photo, a portrait crop and a +small crop the processor upscales), the text tower alone on English, mixed-case, +French, Chinese and an over-long prompt, and the scored pair. + +Two oracles, in this order: + +* **host preprocessing, exact.** The runtime's NaFlex resize, patch cut and + normalisation must reproduce the reference processor value for value; its position + taps must reproduce the reference's table resampling to float32 rounding. Checked + through ``siglip2_preprocess_dump`` from the native build, before any engine runs. +* **embeddings and the relevance logit**, against the reference model in float32 on the + CPU. The gate is the embedding, where an error originates; see the constants below + for how the tolerances were set. +""" + +from __future__ import annotations + +import json +import math +import os +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_enabled, evidence_stage, record_evidence + +FAMILY = "siglip2" +TASKS = frozenset({"image_to_embedding", "text_to_embedding", "text_image_to_relevance"}) +TEST_ROOT = Path(__file__).resolve().parent +MANIFEST_ROOT = TEST_ROOT / "manifests" + + +def _case_index() -> dict[str, tuple[Path, dict, dict]]: + result = {} + for path in sorted(MANIFEST_ROOT.glob("*.json")): + manifest = json.loads(path.read_text(encoding="utf-8")) + assert manifest["family"] == FAMILY + assert manifest["task"] in TASKS + for case in manifest["testcases"]: + name = str(case["name"]) + assert name not in result + result[name] = (path, manifest, case) + return result + + +CASES = _case_index() + + +def _selected_cases(config) -> tuple[list[str], bool]: + model_filters = set() + for raw in config.getoption("--e2e-model") or []: + model_filters.update(item.strip() for item in str(raw).split(",") if item.strip()) + models_file = config.getoption("--e2e-models-file") + if models_file: + model_filters.update( + line.strip() + for line in Path(models_file).read_text(encoding="utf-8").splitlines() + if line.strip() and not line.lstrip().startswith("#") + ) + testcase_filters = set() + for raw in config.getoption("--e2e-testcase") or []: + testcase_filters.update(item.strip() for item in str(raw).split(",") if item.strip()) + if not model_filters and not testcase_filters: + return sorted(CASES), False + selected = [] + for name, (_, manifest, _) in CASES.items(): + model_match = (not model_filters or FAMILY in model_filters or name in model_filters + or manifest["name"] in model_filters) + testcase_match = not testcase_filters or name in testcase_filters + if model_match and testcase_match: + selected.append(name) + return sorted(selected), True + + +def pytest_generate_tests(metafunc) -> None: + if "case_name" in metafunc.fixturenames: + names, enabled = _selected_cases(metafunc.config) + parameters = names + if not enabled: + parameters = [ + pytest.param(name, marks=pytest.mark.skip( + reason="direct E2E requires one of the three explicit E2E selectors")) + for name in names + ] + metafunc.parametrize("case_name", parameters, ids=names) + + +def _required_path(value: str | None, label: str) -> Path: + assert value, f"selected {FAMILY} E2E requires {label}" + path = Path(value) + assert path.exists(), f"selected {FAMILY} E2E {label} does not exist: {path}" + return path + + +def _model_dir(manifest: dict) -> Path: + explicit = os.environ.get(f"TRTMC_{FAMILY.upper()}_MODEL_DIR") + if explicit: + return _required_path(explicit, f"TRTMC_{FAMILY.upper()}_MODEL_DIR") + from huggingface_hub import snapshot_download + + try: + snapshot = snapshot_download(repo_id=manifest["hf_id"], revision=manifest.get("hf_revision"), + local_files_only=True) + except Exception as error: + raise AssertionError( + f"selected {FAMILY} E2E requires the exact cached checkpoint {manifest['hf_id']}" + ) from error + return Path(snapshot) + + +def _runtime() -> tuple[Path, Path, Path]: + binary = _required_path(os.environ.get("TRTMC_BINARY"), "TRTMC_BINARY") + runtime_root = _required_path(os.environ.get("TRTMC_RUNTIME_ROOT"), "TRTMC_RUNTIME_ROOT") + native = _required_path(os.environ.get("TRTMC_NATIVE_BUILD_DIR"), "TRTMC_NATIVE_BUILD_DIR") + assert (runtime_root / "libtrtmc_backend_trt.so").is_file() + assert (runtime_root / f"libtrtmc_model_{FAMILY}.so").is_file() + # CI builds a family's CTests and the runtime by name, not this E2E-only tool. + subprocess.run(["cmake", "--build", str(native), "--target", "siglip2_preprocess_dump"], + check=True, timeout=600) + dump = native / "siglip2_preprocess_dump" + assert dump.is_file(), f"selected {FAMILY} E2E requires the native test tool {dump}" + import torch + + assert torch.cuda.is_available(), f"selected {FAMILY} E2E requires CUDA" + return binary, runtime_root, dump + + +def _build(model_dir: Path, bundle: Path, manifest: dict) -> None: + build( + BuildRequest( + model_dir=model_dir, + output_path=bundle, + family=FAMILY, + task=manifest["task"], + precision=manifest["precision"], + max_sequence_length=manifest.get("max_sequence_length"), + image_height=manifest.get("image_height"), + image_width=manifest.get("image_width"), + video_num_frames=manifest.get("video_num_frames"), + max_batch_size=int(manifest.get("max_batch_size", 1)), + tensor_parallel_size=int(manifest["tensor_parallel_size"]), + quantization=manifest.get("quantization"), + fp32_layers=tuple(int(layer) for layer in manifest.get("fp32_layers", ())), + ) + ) + + +def _run_json(binary: Path, runtime_root: Path, bundle: Path, command: str, *arguments: str) -> dict: + invocation = [str(binary), command, str(bundle), "--runtime-root", str(runtime_root), *arguments] + env = os.environ.copy() + env["LD_LIBRARY_PATH"] = ":".join( + value for value in (str(runtime_root), env.get("LD_LIBRARY_PATH", "")) if value) + completed = subprocess.run(invocation, check=True, capture_output=True, text=True, env=env, + timeout=3600) + payloads = [] + for line in completed.stdout.splitlines(): + start = line.find("{") + if start >= 0: + try: + payloads.append(json.loads(line[start:])) + except json.JSONDecodeError: + pass + assert payloads, f"native {command} returned no JSON: {completed.stdout[-1000:]}" + assert all(payload == payloads[0] for payload in payloads) + return payloads[0] + + +def _images(case: dict, tmp_path: Path) -> list[Path]: + """The test photograph and the crops the case names, as lossless PNG files.""" + from PIL import Image + + source = TEST_ROOT / case["test_image"] + assert source.is_file(), f"selected {FAMILY} E2E asset does not exist: {source}" + paths = [source] + photo = Image.open(source).convert("RGB") + for index, box in enumerate(case.get("image_crops", [])): + path = tmp_path / f"crop_{index}.png" + photo.crop(tuple(int(value) for value in box)).save(path) + paths.append(path) + return paths + + +# Host preprocessing: the pixels are exact by construction (Pillow's fixed-point resize +# and numpy's rescale/normalise arithmetic are reproduced), so any difference is a +# defect. The position taps are built in float64 where the reference builds them in +# float32; the resampled table differs by at most 1.7e-05 on the test images. +_POSITION_TOLERANCE = 1e-4 + + +def _check_preprocessing(dump: Path, model_dir: Path, image_path: Path, tmp_path: Path) -> list[int]: + import numpy as np + import torch + from PIL import Image + from safetensors import safe_open + from transformers import AutoImageProcessor + from transformers.models.siglip2.modeling_siglip2 import Siglip2VisionEmbeddings + + processor = AutoImageProcessor.from_pretrained(str(model_dir), use_fast=False) + image = np.asarray(Image.open(image_path).convert("RGB")) + height, width = image.shape[:2] + reference = processor(images=[image], return_tensors="np", input_data_format="channels_last") + grid_height, grid_width = (int(value) for value in reference["spatial_shapes"][0]) + count = grid_height * grid_width + expected = reference["pixel_values"][0, :count].astype(np.float32) + + with safe_open(str(model_dir / "model.safetensors"), "np") as handle: + table = handle.get_tensor("vision_model.embeddings.position_embedding.weight") + grid = int(round(table.shape[0] ** 0.5)) + + raw = tmp_path / f"{image_path.stem}.u8" + image.tofile(raw) + out = tmp_path / f"{image_path.stem}.bin" + subprocess.run([str(dump), str(raw), str(height), str(width), str(processor.patch_size), + str(processor.max_num_patches), str(grid), *map(str, processor.image_mean), + *map(str, processor.image_std), str(out)], check=True, timeout=600) + data = out.read_bytes() + native_grid = [int(value) for value in np.frombuffer(data[:8], dtype=np.int32)] + assert native_grid == [grid_height, grid_width], ( + f"{image_path.name}: native grid {native_grid}, reference {[grid_height, grid_width]}") + values = np.frombuffer(data[8:], dtype=np.float32) + pixels = values[: expected.size].reshape(expected.shape) + mismatched = int((pixels != expected).sum()) + assert mismatched == 0, f"{image_path.name}: {mismatched} pixel values differ from the processor" + + taps = values[expected.size:].reshape(count, grid * grid).astype(np.float64) + resampled = Siglip2VisionEmbeddings.resize_positional_embeddings( + torch.from_numpy(table).reshape(grid, grid, -1), torch.tensor([[grid_height, grid_width]]), + max_length=count)[0].double().numpy() + delta = float(np.abs(taps @ table.astype(np.float64) - resampled).max()) + assert delta <= _POSITION_TOLERANCE, f"{image_path.name}: position taps differ by {delta}" + return [grid_height, grid_width] + + +def _reference(model_dir: Path, images: list[Path], texts: list[str]): + """The reference's own embeddings, in float32 on the CPU, the way it computes them. + + The processor is the Pillow one (``use_fast=False``), which the runtime reproduces + exactly; the text is padded to the 64-token window with truncation, as the + checkpoint's processor does by default. + """ + import torch + from PIL import Image + from transformers import AutoModel, AutoProcessor + + torch.backends.cuda.matmul.allow_tf32 = False + torch.backends.cudnn.allow_tf32 = False + model = AutoModel.from_pretrained(str(model_dir), dtype=torch.float32).eval() + processor = AutoProcessor.from_pretrained(str(model_dir), use_fast=False) + + def pooled(output): + return output if torch.is_tensor(output) else output.pooler_output + + def unit(vector): + return (vector / vector.norm()).tolist() + + image_vectors = [] + with torch.no_grad(): + for path in images: + batch = processor(images=[Image.open(path).convert("RGB")], return_tensors="pt") + vector = pooled(model.get_image_features(**batch))[0] + image_vectors.append(unit(vector)) + batch = processor(text=texts, padding="max_length", max_length=64, truncation=True, + return_tensors="pt") + text_vectors = [unit(row) for row in pooled(model.get_text_features(**batch))] + scale = float(model.logit_scale.detach().exp()) + bias = float(model.logit_bias.detach()) + return image_vectors, text_vectors, scale, bias + + +# Gates, measured on this case on a B300 (family README): a correct float32 build is +# within 6.4e-07 of the reference on every embedding and 1.3e-05 on the logit. The +# weakest deliberate break, the exact GELU in place of the tanh one, moves a text +# embedding by 4.5e-04, an image embedding by 1.1e-03 and the logit by 2.3e-02; feeding +# the padded patch budget without a mask moves the image embedding by 5.5e-03. The +# embedding is the gate: it is where an error originates and its sensitivity does not +# depend on where a pair lands on the sigmoid. The logit confirms that the scale and +# bias are applied the right way round. The cosine floor only fails early and loudly +# on a gross error (the unmasked padding still has cosine 0.9993). +_EMBEDDING_TOLERANCE = 1e-4 +_LOGIT_TOLERANCE = 0.002 +_COSINE_FLOOR = 0.999 + + +def _max_abs(left: list[float], right: list[float]) -> float: + assert len(left) == len(right), f"{FAMILY} embedding width mismatch" + return max(abs(a - b) for a, b in zip(left, right)) + + +def _cosine(left: list[float], right: list[float]) -> float: + dot = sum(a * b for a, b in zip(left, right)) + return dot / (math.sqrt(sum(a * a for a in left)) * math.sqrt(sum(b * b for b in right))) + + +def _native_embedding(binary: Path, runtime_root: Path, bundle: Path, *arguments: str) -> list[float]: + payload = _run_json(binary, runtime_root, bundle, "embed", *arguments) + values = [float(value) for value in payload["values"]] + assert values, f"native {FAMILY} returned an empty embedding" + assert payload["normalization"] == "l2" + assert payload["embedding_space"] == "siglip2" + norm = math.sqrt(sum(value * value for value in values)) + assert abs(norm - 1.0) <= 1e-3, f"native {FAMILY} embedding is not unit length: {norm}" + return values + + +def _logit(probability: float) -> float: + assert 0.0 < probability < 1.0, f"{FAMILY} probability is saturated: {probability}" + return math.log(probability / (1.0 - probability)) + + +def _record_comparison(tmp_path: Path, native: dict, reference: dict, checks: list[dict]) -> None: + """Keep both sides and the family's checks in the E2E evidence, when it is recorded.""" + if not evidence_enabled(): + return + native_path = tmp_path / "siglip2-native.json" + reference_path = tmp_path / "siglip2-reference.json" + native_path.write_text(json.dumps(native) + "\n", encoding="utf-8") + reference_path.write_text(json.dumps(reference) + "\n", encoding="utf-8") + record_evidence( + "reference_comparison", + { + "label": "Embeddings and relevance logits against the official float32 model", + "scope": "independent_reference", + "enforced": True, + "native": native_path, + "reference": reference_path, + "checks": checks, + }, + ) + + +def _check(name: str, label: str, actual: float, limit: float) -> dict: + return {"name": name, "label": label, "scope": "independent_reference", "actual": actual, + "operator": "<=", "expected": limit, "passed": actual <= limit} + + +def test_official_checkpoint_e2e(case_name: str, tmp_path: Path) -> None: + _, manifest, case = CASES[case_name] + # What the model sees: the photograph and the crops the case names, and every text. + images = _images(case, tmp_path) + texts = [str(case["query"]), str(case["negative_query"]), *map(str, case.get("texts", []))] + record_evidence("inputs", {"manifest": manifest, "case": case, "images": images, + "query": texts[0], "negative_query": texts[1], "texts": texts[2:]}) + model_dir = _model_dir(manifest) + record_evidence("checkpoint", {"model_dir": str(model_dir), "hf_id": manifest.get("hf_id"), + "hf_revision": manifest.get("hf_revision")}) + binary, runtime_root, dump = _runtime() + + with evidence_stage("preprocess"): + grids = [_check_preprocessing(dump, model_dir, path, tmp_path) for path in images] + assert len({tuple(grid) for grid in grids}) == len(grids), f"image grids repeat: {grids}" + record_evidence("grids", grids) + + bundle = tmp_path / manifest["bundle"] + with evidence_stage("build"): + _build(model_dir, bundle, manifest) + + with evidence_stage("reference"): + reference_images, reference_texts, scale, bias = _reference(model_dir, images, texts) + expected_logits = [ + scale * sum(a * b for a, b in zip(reference_images[0], vector)) + bias + for vector in reference_texts[:2] + ] + record_evidence("reference", { + "image_embeddings": np.asarray(reference_images, dtype=np.float32), + "text_embeddings": np.asarray(reference_texts, dtype=np.float32), + "relevance_probabilities": np.asarray([1.0 / (1.0 + math.exp(-value)) + for value in expected_logits]), + }) + + with evidence_stage("native"): + native_images = [ + _native_embedding(binary, runtime_root, bundle, "--task", "image_to_embedding", + "--image", str(path)) + for path in images + ] + native_texts = [ + _native_embedding(binary, runtime_root, bundle, "--task", "text_to_embedding", + "--text", text) + for text in texts + ] + # A per-pair sigmoid calibrated by the checkpoint's own scale and bias: compared + # in logit space, where the sensitivity is uniform. + scores = [] + for text in texts[:2]: + payload = _run_json(binary, runtime_root, bundle, "rerank", "--task", + "text_image_to_relevance", "--query", text, "--image", + str(images[0])) + assert payload["score_kind"] == "probability" + scores.append(float(payload["score"])) + record_evidence("native", { + "image_embeddings": np.asarray(native_images, dtype=np.float32), + "text_embeddings": np.asarray(native_texts, dtype=np.float32), + "relevance_probabilities": np.asarray(scores), + }) + record_evidence("thresholds", {"embedding_max_abs": _EMBEDDING_TOLERANCE, + "embedding_cosine_min": _COSINE_FLOOR, + "relevance_logit_abs": _LOGIT_TOLERANCE}) + + with evidence_stage("compare"): + image_deltas = [_max_abs(n, r) for n, r in zip(native_images, reference_images)] + text_deltas = [_max_abs(n, r) for n, r in zip(native_texts, reference_texts)] + logit_deltas = [abs(_logit(score) - expected) + for score, expected in zip(scores, expected_logits)] + checks = [_check(f"image_{index}_maxabs", f"Image {path.name} embedding max |diff|", + delta, _EMBEDDING_TOLERANCE) + for index, (path, delta) in enumerate(zip(images, image_deltas))] + checks += [_check(f"text_{index}_maxabs", f"Text {index} embedding max |diff|", delta, + _EMBEDDING_TOLERANCE) for index, delta in enumerate(text_deltas)] + checks += [_check(f"logit_{index}_absdiff", f"Relevance logit {index} |diff|", delta, + _LOGIT_TOLERANCE) for index, delta in enumerate(logit_deltas)] + _record_comparison( + tmp_path, + {"images": native_images, "texts": native_texts, "probabilities": scores}, + {"images": reference_images, "texts": reference_texts, "logits": expected_logits, + "logit_scale": scale, "logit_bias": bias}, + checks, + ) + for path, native, expected, delta in zip(images, native_images, reference_images, + image_deltas): + cosine = _cosine(native, expected) + assert cosine >= _COSINE_FLOOR, f"image embedding cosine {cosine} for {path.name}" + assert delta <= _EMBEDDING_TOLERANCE, ( + f"image embedding of {path.name} differs from the reference by {delta}") + for text, native, expected, delta in zip(texts, native_texts, reference_texts, + text_deltas): + cosine = _cosine(native, expected) + assert cosine >= _COSINE_FLOOR, f"text embedding cosine {cosine} for {text!r}" + assert delta <= _EMBEDDING_TOLERANCE, ( + f"text embedding for {text!r} differs from the reference by {delta}") + for text, score, delta in zip(texts, scores, logit_deltas): + assert 0.0 <= score <= 1.0, f"{FAMILY} returned a score outside [0, 1]: {score}" + assert delta <= _LOGIT_TOLERANCE, f"relevance logit for {text!r} differs by {delta}" + assert scores[0] > scores[1], f"{FAMILY} scored the negative text higher: {scores}" + print( + f"{FAMILY} parity: grids {grids}, image maxabs " + + ", ".join(f"{value:.3e}" for value in image_deltas) + + ", text maxabs " + ", ".join(f"{value:.3e}" for value in text_deltas) + + f", logit maxabs {max(logit_deltas):.3e}, probabilities {scores[0]:.8f} vs {scores[1]:.8f}" + ) diff --git a/families/siglip2/tests/test_model.py b/families/siglip2/tests/test_model.py new file mode 100644 index 0000000000..0f758c63b0 --- /dev/null +++ b/families/siglip2/tests/test_model.py @@ -0,0 +1,397 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +"""Build-side unit tests for SigLIP 2 NaFlex (CPU only, no engine is built). + +``config.resolve`` reads the geometry from the tensors and the processor file, since the +published ``config.json`` states almost nothing; ``build`` refuses every option it cannot +honour before it touches the checkpoint; the tokenizer contract refuses tokenizers the +runtime would tokenise differently. +""" + +from __future__ import annotations + +import json +from pathlib import Path + +import numpy as np +import pytest + +from families.siglip2 import config as config_module, model as model_module +from tensorrt_model_connect import BuildRequest + +_HIDDEN = 128 +_INTERMEDIATE = 256 +_LAYERS = 2 +_PATCH = 4 +_GRID = 4 +_VOCAB = 100 +_WINDOW = 8 + +_PREPROCESSOR = { + "image_processor_type": "Siglip2ImageProcessorFast", + "do_resize": True, + "resample": 2, + "do_rescale": True, + "rescale_factor": 1 / 255, + "do_normalize": True, + "image_mean": [0.5, 0.5, 0.5], + "image_std": [0.5, 0.5, 0.5], + "patch_size": _PATCH, + "max_num_patches": 16, +} + +def _added(token_id, content, special=True, **options) -> dict: + return {"id": token_id, "content": content, "single_word": False, "lstrip": False, + "rstrip": False, "normalized": False, "special": special, **options} + + +# Like the checkpoint's: ids 0..N-1 with the U+2581 marker, and every byte has its fallback +# token except the tab, whose character is a vocabulary entry itself. +_TOKEN_IDS = {"": 0, "": 1, "a": 2, "\t": 3, "▁": 4, + **{f"<0x{byte:02X}>": 5 + index + for index, byte in enumerate(b for b in range(256) if b != 0x09)}} + +_TOKENIZER = { + "added_tokens": [_added(0, ""), _added(1, "")], + "normalizer": {"type": "Replace", "pattern": {"String": " "}, "content": "▁"}, + "pre_tokenizer": None, + "post_processor": {"type": "TemplateProcessing", + "single": [{"Sequence": {"id": "A", "type_id": 0}}, + {"SpecialToken": {"id": "", "type_id": 0}}], + "special_tokens": {"": {"id": "", "ids": [1], + "tokens": [""]}}}, + "model": {"type": "BPE", "byte_fallback": True, "vocab": _TOKEN_IDS, "merges": []}, +} + + +def _with_model(**changes) -> dict: + return {"model": {**_TOKENIZER["model"], **changes}} + + +def _renamed(token: str, new_name: str) -> dict: + # Keeps the ids 0..N-1: the token's id moves to a name the tokenizer does not use. + return _with_model(vocab={(new_name if k == token else k): v for k, v in _TOKEN_IDS.items()}) + + +def _end_token_expanding_to(ids) -> dict: + processor = dict(_TOKENIZER["post_processor"]) + processor["special_tokens"] = {"": {"id": "", "ids": ids, "tokens": [""]}} + return {"post_processor": processor} + + +def _weights(**overrides) -> dict: + weights = { + "text_model.embeddings.token_embedding.weight": np.zeros((_VOCAB, _HIDDEN), np.float32), + "text_model.embeddings.position_embedding.weight": np.zeros((_WINDOW, _HIDDEN), np.float32), + "text_model.head.weight": np.zeros((_HIDDEN, _HIDDEN), np.float32), + "vision_model.embeddings.patch_embedding.weight": + np.zeros((_HIDDEN, 3 * _PATCH * _PATCH), np.float32), + "vision_model.embeddings.position_embedding.weight": + np.zeros((_GRID * _GRID, _HIDDEN), np.float32), + "vision_model.head.attention.in_proj_weight": np.zeros((3 * _HIDDEN, _HIDDEN), np.float32), + "vision_model.head.probe": np.zeros((1, 1, _HIDDEN), np.float32), + "vision_model.head.attention.in_proj_bias": np.zeros((3 * _HIDDEN,), np.float32), + "vision_model.embeddings.patch_embedding.bias": np.zeros((_HIDDEN,), np.float32), + "vision_model.post_layernorm.weight": np.ones((_HIDDEN,), np.float32), + "text_model.final_layer_norm.weight": np.ones((_HIDDEN,), np.float32), + "logit_scale": np.zeros((1,), np.float32), + "logit_bias": np.zeros((1,), np.float32), + } + for prefix in ("text_model", "vision_model"): + for index in range(_LAYERS): + weights[f"{prefix}.encoder.layers.{index}.mlp.fc1.weight"] = np.zeros( + (_INTERMEDIATE, _HIDDEN), np.float32) + weights.update(overrides) + return weights + + +def _model_dir(tmp_path: Path, config: dict | None = None, preprocessor: dict | None = None, + tokenizer: dict | None = None) -> Path: + (tmp_path / "config.json").write_text(json.dumps( + config if config is not None else {"architectures": ["Siglip2Model"], + "model_type": "siglip2"})) + (tmp_path / "preprocessor_config.json").write_text(json.dumps( + preprocessor if preprocessor is not None else _PREPROCESSOR)) + (tmp_path / "tokenizer.json").write_text(json.dumps( + tokenizer if tokenizer is not None else _TOKENIZER)) + (tmp_path / "tokenizer_config.json").write_text(json.dumps( + {"pad_token": "", "eos_token": ""})) + return tmp_path + + +def test_geometry_comes_from_the_tensors_and_the_processor(tmp_path: Path) -> None: + cfg = _resolve_with_heads(tmp_path) + vision, text = cfg["vision"], cfg["text"] + assert (vision["hidden_size"], vision["intermediate_size"], vision["num_layers"]) == ( + _HIDDEN, _INTERMEDIATE, _LAYERS) + assert vision["patch_size"] == _PATCH + assert vision["patch_features"] == 3 * _PATCH * _PATCH + assert (vision["num_positions"], vision["grid"]) == (_GRID * _GRID, _GRID) + assert vision["max_num_patches"] == 16 + assert (text["vocab_size"], text["max_text_len"], text["projection_size"]) == ( + _VOCAB, _WINDOW, _HIDDEN) + assert cfg["resample"] == 2 + assert cfg["rescale_factor"] == pytest.approx(1 / 255) + + +def test_head_count_defaults_to_the_reference_and_must_divide_the_width(tmp_path: Path) -> None: + stated = {"architectures": ["Siglip2Model"], + "text_config": {"num_attention_heads": 4}, "vision_config": {"num_attention_heads": 8}} + cfg = config_module.resolve(_model_dir(tmp_path, stated), _weights()) + assert (cfg["text"]["num_heads"], cfg["vision"]["num_heads"]) == (4, 8) + assert cfg["vision"]["head_dim"] == _HIDDEN // 8 + with pytest.raises(ValueError, match="not divisible by 12 heads"): + config_module.resolve(_model_dir(tmp_path), _weights()) + + +def _resolve_with_heads(tmp_path: Path, config: dict | None = None, **kwargs): + base = {"architectures": ["Siglip2Model"], + "text_config": {"num_attention_heads": 4}, "vision_config": {"num_attention_heads": 4}} + for key, value in (config or {}).items(): + if isinstance(value, dict): + base.setdefault(key, {}).update(value) + else: + base[key] = value + return config_module.resolve(_model_dir(tmp_path, base, **kwargs), _weights()) + + +def test_a_config_that_contradicts_the_tensors_is_refused(tmp_path: Path) -> None: + with pytest.raises(ValueError, match="tensors say"): + _resolve_with_heads(tmp_path, {"vision_config": {"hidden_size": _HIDDEN * 2}}) + with pytest.raises(ValueError, match="tensors say"): + _resolve_with_heads(tmp_path, {"text_config": {"vocab_size": _VOCAB + 1}}) + + +def test_the_classification_head_is_refused(tmp_path: Path) -> None: + with pytest.raises(NotImplementedError, match="Siglip2Model"): + _resolve_with_heads(tmp_path, {"architectures": ["Siglip2ForImageClassification"]}) + + +def test_a_patch_size_the_embedding_cannot_take_is_refused(tmp_path: Path) -> None: + with pytest.raises(ValueError, match="values per patch"): + _resolve_with_heads(tmp_path, preprocessor={**_PREPROCESSOR, "patch_size": 8}) + + +def test_a_non_square_position_table_is_refused(tmp_path: Path) -> None: + weights = _weights(**{"vision_model.embeddings.position_embedding.weight": + np.zeros((12, _HIDDEN), np.float32)}) + config = {"architectures": ["Siglip2Model"], + "text_config": {"num_attention_heads": 4}, "vision_config": {"num_attention_heads": 4}} + with pytest.raises(NotImplementedError, match="square position table"): + config_module.resolve(_model_dir(tmp_path, config), weights) + + +@pytest.mark.parametrize( + ("override", "message"), + [ + ({"resample": 3}, "bilinear"), + ({"do_resize": False}, "aspect-preserving resize"), + ({"do_rescale": False}, "1/255 rescale"), + ({"rescale_factor": 1 / 127.5}, "1/255 rescale"), + ({"do_normalize": False}, "normalization"), + ({"image_processor_type": "SiglipImageProcessor"}, "Siglip2 image processor"), + ], +) +def test_processor_settings_the_runtime_does_not_reproduce_are_refused( + tmp_path: Path, override: dict, message: str) -> None: + with pytest.raises(NotImplementedError, match=message): + _resolve_with_heads(tmp_path, preprocessor={**_PREPROCESSOR, **override}) + + +@pytest.mark.parametrize( + ("config", "preprocessor", "message"), + [ + # A fraction, a bool or a string is refused where an integer or a number belongs, + # not rounded, counted or parsed into one. + (None, {"max_num_patches": 16.5}, "max_num_patches must be an integer"), + (None, {"patch_size": 4.0}, "patch_size must be an integer"), + (None, {"resample": True}, "resample must be an integer"), + (None, {"rescale_factor": "0.00392156862745098"}, "rescale_factor must be a finite number"), + (None, {"image_mean": ["0.5", 0.5, 0.5]}, "image_mean must be a finite number"), + ({"text_config": {"num_attention_heads": 4.5}}, None, "num_attention_heads must be an integer"), + ({"vision_config": {"hidden_size": 128.5}}, None, "hidden_size must be an integer"), + ({"vision_config": {"num_channels": 3.0}}, None, "num_channels must be an integer"), + ({"text_config": {"layer_norm_eps": "1e-6"}}, None, "layer_norm_eps must be a finite number"), + # The json module reads NaN and Infinity, which would reach the engine or the runtime. + (None, {"rescale_factor": float("nan")}, "rescale_factor must be a finite number"), + (None, {"image_std": [0.5, float("inf"), 0.5]}, "image_std must be a finite number"), + ({"text_config": {"layer_norm_eps": float("nan")}}, None, "layer_norm_eps must be a finite number"), + ], +) +def test_config_numbers_are_checked_before_use(tmp_path: Path, config, preprocessor, message) -> None: + kwargs = {} if preprocessor is None else {"preprocessor": {**_PREPROCESSOR, **preprocessor}} + with pytest.raises(ValueError, match=message): + _resolve_with_heads(tmp_path, config, **kwargs) + + +def test_the_tokenizer_contract_returns_the_pad_id(tmp_path: Path) -> None: + assert model_module._tokenizer_contract(_model_dir(tmp_path)) == 0 + + +@pytest.mark.parametrize( + ("override", "message"), + [ + ({"normalizer": {"type": "Sequence", "normalizers": [ + {"type": "Lowercase"}, + {"type": "Replace", "pattern": {"String": " "}, "content": "▁"}]}}, "normalizer"), + ({"pre_tokenizer": {"type": "Metaspace"}}, "pre-tokenizer"), + ({"post_processor": {"type": "TemplateProcessing", + "single": [{"SpecialToken": {"id": ""}}, + {"Sequence": {"id": "A"}}]}}, "one end token"), + ({"model": {"type": "Unigram", "vocab": []}}, "byte-fallback BPE"), + ({"added_tokens": [_added(0, ""), _added(1, "", special=False)]}, "special token"), + # The reference turns a character whose byte token is missing into the unknown + # token; the runtime has no unknown-token path. + (_renamed("<0xAC>", "zz"), "missing <0xAC>"), + (_renamed("<0x7A>", "zz"), "missing <0x7A>"), + # The runtime keeps ids 0..N-1, where the reference takes any id. + (_with_model(vocab={**_TOKEN_IDS, "<0xFF>": len(_TOKEN_IDS)}), "ids must be integers in"), + (_with_model(vocab={**_TOKEN_IDS, "a": 10_000}), "ids must be integers in"), + # Without the marker the runtime would not encode on the reference's path. + (_renamed("▁", "zz"), "no U.2581 space marker"), + # BPE options the runtime does not apply. + (_with_model(ignore_merges=True), "ignore_merges"), + (_with_model(dropout=0.1), "dropout"), + (_with_model(continuing_subword_prefix="##"), "continuing_subword_prefix"), + (_with_model(end_of_word_suffix=""), "end_of_word_suffix"), + *[({"added_tokens": [_added(0, ""), _added(1, ""), + _added(2, "a", special=False, **{option: True})]}, f"sets {option}") + for option in ("single_word", "lstrip", "rstrip", "normalized")], + # The reference gives an added token in the vocabulary the vocabulary's id. + ({"added_tokens": [_added(0, ""), _added(1, ""), _added(5, "a", special=False)]}, + "vocabulary entry with id 5"), + ({"added_tokens": [_added(0, ""), _added(1, ""), _added(300, "")]}, + "vocabulary entry with id 300"), + (_end_token_expanding_to([0, 1]), "exactly its id 1"), + (_end_token_expanding_to([0]), "exactly its id 1"), + ({"post_processor": {k: v for k, v in _TOKENIZER["post_processor"].items() + if k != "special_tokens"}}, "exactly its id 1"), + # The reference refuses an item with two operations. + ({"post_processor": {**_TOKENIZER["post_processor"], "single": [ + {"Sequence": {"id": "A", "type_id": 0}}, + {"SpecialToken": {"id": "", "type_id": 0}, "Sequence": {"id": "A", "type_id": 0}}]}}, + "one end token"), + ], +) +def test_tokenizers_the_runtime_would_tokenise_differently_are_refused( + tmp_path: Path, override: dict, message: str) -> None: + with pytest.raises(NotImplementedError, match=message): + model_module._tokenizer_contract(_model_dir(tmp_path, tokenizer={**_TOKENIZER, **override})) + + +@pytest.mark.parametrize( + ("merges", "message"), + [ + # The runtime loader requires the table; the reference refuses all of these files. + (None, "model.merges must be a list"), + ({}, "model.merges must be a list"), + ([["a", "a"]], "merge a a makes aa, which is not in the vocabulary"), + ([["x", "a"]], "merge x a: x is not in the vocabulary"), + (["a a a"], "merge 0 is not one pair"), + ([["a"]], "merge 0 is not one pair"), + ], +) +def test_merge_tables_the_reference_cannot_load_are_refused(tmp_path: Path, merges, message) -> None: + model = {k: v for k, v in _TOKENIZER["model"].items() if k != "merges"} + if merges is not None: + model["merges"] = merges + with pytest.raises(ValueError, match=message): + model_module._tokenizer_contract(_model_dir(tmp_path, tokenizer={**_TOKENIZER, "model": model})) + + +def test_a_vocabulary_id_that_is_not_an_integer_is_refused(tmp_path: Path) -> None: + tokenizer = {**_TOKENIZER, **_with_model(vocab={**_TOKEN_IDS, "a": "2"})} + with pytest.raises(ValueError, match="vocabulary id of 'a' is not an integer"): + model_module._tokenizer_contract(_model_dir(tmp_path, tokenizer=tokenizer)) + + +def test_merges_stay_on_with_ignore_merges_false(tmp_path: Path) -> None: + tokenizer = {**_TOKENIZER, **_with_model(ignore_merges=False)} + assert model_module._tokenizer_contract(_model_dir(tmp_path, tokenizer=tokenizer)) == 0 + + +@pytest.mark.parametrize( + ("record", "message"), + [ + ({k: v for k, v in _added(2, "a").items() if k != "content"}, "no string content"), + ({k: v for k, v in _added(2, "a").items() if k != "id"}, "no valid id"), + (_added("2", "a"), "no valid id"), + (_added(-1, "a"), "no valid id"), + ({k: v for k, v in _added(2, "a").items() if k != "normalized"}, "no boolean normalized"), + (_added(2, "a", lstrip=0), "no boolean lstrip"), + ], +) +def test_malformed_added_tokens_are_refused(tmp_path: Path, record: dict, message: str) -> None: + tokenizer = {**_TOKENIZER, "added_tokens": [*_TOKENIZER["added_tokens"], record]} + with pytest.raises(ValueError, match=message): + model_module._tokenizer_contract(_model_dir(tmp_path, tokenizer=tokenizer)) + + +class _Writer: + def __getattr__(self, name): + raise AssertionError(f"build wrote {name} before refusing") + + +@pytest.mark.parametrize( + ("field", "value", "message"), + [ + ("precision", "fp16", "fp32 only"), + ("backend", "trt_rtx", "backend=trt"), + ("max_batch_size", 2, "max_batch_size"), + ("tensor_parallel_size", 2, "tensor parallelism"), + ("context_parallel_size", 2, "context parallelism"), + ("video_num_frames", 4, "video_num_frames"), + ("quantization", "fp8", "quantization"), + ("fp32_layers", (1,), "mixed-precision"), + ("dynamic_kv_cache", True, "dynamic_kv_cache"), + ("mtp_seq_len", 2, "MTP"), + ("image_height", 224, "image_height/width"), + ("image_width", 224, "image_height/width"), + ("task", "image_to_class_scores", "supports only task"), + ], +) +def test_build_refuses_options_it_cannot_honour(tmp_path: Path, field, value, message) -> None: + fields = {"model_dir": tmp_path, "output_path": tmp_path / "x.bundle", "family": "siglip2", + "task": "text_image_to_relevance", "precision": "fp32"} + fields[field] = value + with pytest.raises((ValueError, NotImplementedError), match=message): + model_module.build(BuildRequest(**fields), _Writer()) + + +def _checkpoint(tmp_path: Path, weights: dict) -> Path: + from safetensors.numpy import save_file + + config = {"architectures": ["Siglip2Model"], "model_type": "siglip2", + "text_config": {"num_attention_heads": 4}, "vision_config": {"num_attention_heads": 4}} + model_dir = _model_dir(tmp_path, config) + save_file(weights, str(model_dir / "model.safetensors")) + return model_dir + + +def test_the_prompt_window_is_not_a_capacity(tmp_path: Path) -> None: + model_dir = _checkpoint(tmp_path, _weights()) + request = BuildRequest(model_dir=model_dir, output_path=tmp_path / "x.bundle", family="siglip2", + task="text_to_embedding", precision="fp32", + max_sequence_length=_WINDOW * 2) + with pytest.raises(NotImplementedError, match="window of 8"): + model_module.build(request, _Writer()) + + +def test_a_vocabulary_larger_than_the_embedding_table_is_refused(tmp_path: Path) -> None: + # The text engine gathers token ids from the checkpoint's embedding rows; this test + # vocabulary has 260 tokens and the table 100 rows. + model_dir = _checkpoint(tmp_path, _weights()) + request = BuildRequest(model_dir=model_dir, output_path=tmp_path / "x.bundle", family="siglip2", + task="text_to_embedding", precision="fp32") + with pytest.raises(ValueError, match="260 tokens but the text embedding table has 100 rows"): + model_module.build(request, _Writer()) + + +def test_a_reduced_precision_checkpoint_is_refused(tmp_path: Path) -> None: + weights = _weights(**{"text_model.head.weight": np.zeros((_HIDDEN, _HIDDEN), np.float16)}) + model_dir = _checkpoint(tmp_path, weights) + request = BuildRequest(model_dir=model_dir, output_path=tmp_path / "x.bundle", family="siglip2", + task="text_to_embedding", precision="fp32") + with pytest.raises(NotImplementedError, match="float32 checkpoint"): + model_module.build(request, _Writer()) diff --git a/families/siglip2/tests/test_support.py b/families/siglip2/tests/test_support.py new file mode 100644 index 0000000000..eeb01ab58f --- /dev/null +++ b/families/siglip2/tests/test_support.py @@ -0,0 +1,38 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +"""Dependency-free semantic Task discovery for SigLIP 2 NaFlex.""" + +from families.siglip2.support import describe +from tensorrt_model_connect.model_support import ModelMetadata + + +def test_the_three_tasks_are_offered(): + support = describe(ModelMetadata(config={"model_type": "siglip2"}, model_index={})) + assert support is not None + assert support.tasks == ("image_to_embedding", "text_to_embedding", + "text_image_to_relevance") + assert support.default_task == "text_image_to_relevance" + assert support.default_precision == "fp32" + + +def test_architecture_also_resolves(): + support = describe(ModelMetadata(config={"architectures": ["Siglip2Model"]}, model_index={})) + assert support is not None + assert support.default_task == "text_image_to_relevance" + + +def test_fixed_resolution_siglip2_checkpoints_are_not_claimed(): + # The fixed-resolution SigLIP 2 checkpoints publish model_type "siglip" and the + # SiglipModel graph: they belong to the siglip family, not to this one. + assert describe(ModelMetadata(config={"model_type": "siglip", + "architectures": ["SiglipModel"]}, + model_index={})) is None + + +def test_the_neighbouring_towers_are_not_claimed(): + # Single towers and the CLIP family share the two-tower naming but not this + # checkpoint's identity. + for model_type in ("siglip2_vision_model", "siglip2_text_model", "siglip_vision_model", + "clip", "lfm2_vl"): + assert describe(ModelMetadata(config={"model_type": model_type}, model_index={})) is None diff --git a/families/siglip2/text_builder.py b/families/siglip2/text_builder.py new file mode 100644 index 0000000000..46e8acb862 --- /dev/null +++ b/families/siglip2/text_builder.py @@ -0,0 +1,44 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +"""SigLIP 2 text tower: a full window of token ids to one projected embedding. + +The pooled row is the **last row of the padded window**, which is padding for any +prompt shorter than the window - the reference says so next to the slice. Two rules +follow, and both produce a plausible vector when broken: + +* the window length is a correctness rule, not a capacity: the engine is built at + exactly the checkpoint's window and the runtime always pads to it; +* there is no mask. The reference's tokenizer emits only ``input_ids`` for this + checkpoint, so the padding rows take part in attention. +""" + +from __future__ import annotations + +import numpy as np + +from . import encoder_builder, graph as g + +PREFIX = "text_model" + + +def build_text_tower(network, input_ids, weights, cfg, *, dtype=np.float32): + """``[window]`` int32 token ids to an unnormalised ``[1, projection_size]`` embedding.""" + width = cfg["hidden_size"] + window = int(input_ids.shape[0]) + + table = g.add_constant(network, (cfg["vocab_size"], width), + weights[f"{PREFIX}.embeddings.token_embedding.weight"], dtype=dtype) + hidden = network.add_gather(table, input_ids, axis=0).get_output(0) + positions = g.add_constant(network, (window, width), + weights[f"{PREFIX}.embeddings.position_embedding.weight"][:window], + dtype=dtype) + hidden = g.add_sum(network, hidden, positions) + + hidden = encoder_builder.build_layers(network, hidden, weights, PREFIX, cfg, dtype=dtype) + hidden = g.add_layer_norm(network, hidden, weights[f"{PREFIX}.final_layer_norm.weight"], + weights[f"{PREFIX}.final_layer_norm.bias"], cfg["eps"]) + + last = network.add_slice(hidden, start=(window - 1, 0), shape=(1, width), stride=(1, 1)) + return g.add_linear(network, last.get_output(0), weights[f"{PREFIX}.head.weight"], + weights[f"{PREFIX}.head.bias"], dtype=dtype) diff --git a/families/siglip2/vision_builder.py b/families/siglip2/vision_builder.py new file mode 100644 index 0000000000..630bf513e1 --- /dev/null +++ b/families/siglip2/vision_builder.py @@ -0,0 +1,84 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +"""SigLIP 2 NaFlex vision tower: one image's patches to one pooled embedding. + +The engine sees exactly the request's patches, ``[patches, channels x patch x patch]`` +in (row, column, channel) order, with the patch count dynamic up to the processor's +budget. Three details separate it from the fixed-grid SigLIP tower: + +* patches are embedded by a **Linear** layer over already-flattened pixels, not by a + convolution over the image; +* the position table is a square grid **resampled to the image's own grid** with an + antialiased bilinear filter. The filter taps depend only on the two grid shapes, so + the runtime computes them on the host as one ``[patches, table rows]`` matrix and + the engine applies it to the table it carries as a constant. The table never leaves + the engine; only geometry crosses the boundary; +* pooling is a learned attention head: one ``probe`` row attends over every patch and + the result goes through ``residual + mlp(layernorm(residual))``, where the residual + is the attention **output**. + +The reference pads every image to the patch budget and masks the padding out of both +the encoder and the pooling head. A masked key contributes exactly zero after the +softmax, so running only the real patches computes the same function without a mask. +""" + +from __future__ import annotations + +import numpy as np +import tensorrt as trt + +from . import encoder_builder, graph as g + +PREFIX = "vision_model" + + +def _pooling_head(network, hidden, weights, cfg, *, dtype=np.float32): + """torch ``MultiheadAttention`` with one learned query row, then an MLP.""" + width = cfg["hidden_size"] + head = f"{PREFIX}.head" + + # torch packs this head's projections into one [3 * width, width] tensor, in + # q, k, v order; the encoder layers ship them separately. + q_w, k_w, v_w = np.split(np.asarray(weights[f"{head}.attention.in_proj_weight"]), 3, axis=0) + q_b, k_b, v_b = np.split(np.asarray(weights[f"{head}.attention.in_proj_bias"]), 3, axis=0) + + probe = g.add_constant(network, (1, width), + np.asarray(weights[f"{head}.probe"]).reshape(1, width), dtype=dtype) + query = g.add_linear(network, probe, q_w, q_b, dtype=dtype) + key = g.add_linear(network, hidden, k_w, k_b, dtype=dtype) + value = g.add_linear(network, hidden, v_w, v_b, dtype=dtype) + attended = g.add_attention(network, query, key, value, num_heads=cfg["num_heads"], + head_dim=cfg["head_dim"]) + attended = g.add_linear(network, attended, weights[f"{head}.attention.out_proj.weight"], + weights[f"{head}.attention.out_proj.bias"], dtype=dtype) + + # residual = attention output; the norm feeds the MLP only. + normed = g.add_layer_norm(network, attended, weights[f"{head}.layernorm.weight"], + weights[f"{head}.layernorm.bias"], cfg["eps"]) + inner = g.add_linear(network, normed, weights[f"{head}.mlp.fc1.weight"], + weights[f"{head}.mlp.fc1.bias"], dtype=dtype) + inner = g.add_gelu_tanh(network, inner, dtype=dtype) + inner = g.add_linear(network, inner, weights[f"{head}.mlp.fc2.weight"], + weights[f"{head}.mlp.fc2.bias"], dtype=dtype) + return g.add_sum(network, attended, inner) + + +def build_vision_tower(network, patches, position_weights, weights, cfg, *, dtype=np.float32): + """``[patches, features]`` pixels and ``[patches, table rows]`` taps to ``[1, width]``.""" + width = cfg["hidden_size"] + + hidden = g.add_linear(network, patches, + weights[f"{PREFIX}.embeddings.patch_embedding.weight"], + weights[f"{PREFIX}.embeddings.patch_embedding.bias"], dtype=dtype) + + table = g.add_constant(network, (cfg["num_positions"], width), + weights[f"{PREFIX}.embeddings.position_embedding.weight"], dtype=dtype) + positions = network.add_matrix_multiply(position_weights, trt.MatrixOperation.NONE, + table, trt.MatrixOperation.NONE).get_output(0) + hidden = g.add_sum(network, hidden, positions) + + hidden = encoder_builder.build_layers(network, hidden, weights, PREFIX, cfg, dtype=dtype) + hidden = g.add_layer_norm(network, hidden, weights[f"{PREFIX}.post_layernorm.weight"], + weights[f"{PREFIX}.post_layernorm.bias"], cfg["eps"]) + return _pooling_head(network, hidden, weights, cfg, dtype=dtype)