Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions ASSET_LICENSES.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
150 changes: 150 additions & 0 deletions families/siglip2/NOTICE
Original file line number Diff line number Diff line change
@@ -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.
152 changes: 152 additions & 0 deletions families/siglip2/README.md
Original file line number Diff line number Diff line change
@@ -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 `<eos>` 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 `<pad>` to the 64-token window, and a longer prompt keeps its
first 63 tokens and `<eos>`, 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.
4 changes: 4 additions & 0 deletions families/siglip2/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: Apache-2.0

"""siglip2 family."""
Loading
Loading