Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

fix(models)!: SigLip2 loss and pooling mask, NaFlex table resize, Kimi-VL mask, PaliGemma Gemma numerics (#6044)

Dmytro Mishkinb2d3b6f94d49
diff --git a/changelog.d/6044.breaking.md b/changelog.d/6044.breaking.md
new file mode 100644
index 000000000..0251b83e1
--- /dev/null
+++ b/changelog.d/6044.breaking.md
@@ -0,0 +1,5 @@
+Some vision-language calls of `kornia.models` that ran now raise:
+
+- `SigLip2Config.from_name` and `SigLip2Builder.from_name` give the supported checkpoints (`google/siglip-base-patch16-224`, `google/siglip2-base-patch16-{224,256,384,512}` and `google/siglip2-large-patch16-{256,384,512}`) their 64 text positions, where they gave 512: a random-init model built from one of these names takes at most 64 tokens, and longer `input_ids` raise. Other names keep 512 positions.
+- SigLip2 honours `hidden_act`: `"gelu_pytorch_tanh"` and `"gelu_new"` give tanh GELU, `"gelu"` exact GELU, and any other value raises `ValueError` when the model is built. `hidden_act` was ignored (every MLP used exact GELU), so a config with `hidden_act="quick_gelu"` or `"relu"` built and ran.
+- With the legacy TorchScript ONNX exporter (`torch.onnx.export(..., dynamo=False)`), exporting a `NaFlex` from an example input whose patch grid is smaller than its position table along an axis raises `UnsupportedOperatorError`, because such a grid is now resized with antialiasing (`aten::_upsample_bilinear2d_aa`). It exported a plain bilinear resize, whose values were wrong at that size. An example grid at least as large as the table along both axes still exports, and its graph is exact for such grids only. The dynamo exporter (`dynamo=True`) exports the antialiased resize; with dynamic H and W, export from an example whose grid is smaller than the table along both axes, as the `NaFlex` note says.
diff --git a/changelog.d/6044.fixed.md b/changelog.d/6044.fixed.md
new file mode 100644
index 000000000..16a6b93dd
--- /dev/null
+++ b/changelog.d/6044.fixed.md
@@ -0,0 +1,10 @@
+The vision-language models of `kornia.models` follow their reference implementations in more places:
+
+- `SigLip2Model(..., return_loss=True)` returns SigLIP's pairwise sigmoid loss over every image-text pair of the batch, with the matching pairs labelled +1 and every other pair -1. It used only the matching pairs, so the negatives never entered and the loss fell to zero as `logit_bias` grew: `0.0` on a batch of 4 with `logit_bias = 10`, where SigLIP's loss is `38.54`. The loss pairs the i-th image with the i-th text, so unequal image and text batches raise `BaseError` with `return_loss=True`: 3 images with 1 text raised `IndexError`, and 1 image with 3 texts returned the loss of its first pair only. Without the loss, unequal batches still give rectangular logits.
+- The `attention_mask` of `SigLip2VisionModel` and `SigLip2Model.get_image_features` reaches the attention-pooling head as well as the encoder, so the pixels of masked patches no longer change the pooled embedding. For a `(B, N, N)` or `(B, 1, N, N)` mask, the head leaves out the patches no query may attend to.
+- An image whose patches are all masked is pooled by `SigLip2VisionModel` with uniform weights over its patches, as transformers' pooling mask gives: it adds `torch.finfo(dtype).min` to the masked scores, not `-inf`. The weights are exactly uniform in float32, float64 and bfloat16. In float16, as in transformers, `finfo(float16).min` plus a score rounds to a multiple of 32, so they are only roughly uniform, and a head whose scores are all below about -16 gives a non-finite output.
+- SigLip2's MLPs use the tanh approximation of GELU (`hidden_act="gelu_pytorch_tanh"`, the new config default) and `SigLip2ImagePreprocessor` resizes bilinearly by default, as the SigLIP 2 checkpoints do (`"resample": 2` in their `preprocessor_config.json`). Both used exact GELU and bicubic resizing. `SigLip2ImagePreprocessor` and its `from_config` take `interpolation="bicubic"` for the SigLIP 1 checkpoint `google/siglip-base-patch16-224`.
+- `NaFlex` resizes its position table to the image's patch grid whenever that grid is not the table's own square grid, with bilinear interpolation as transformers' SigLIP 2 does, antialiased when the grid is smaller than the table along an axis (transformers always antialiases, which changes nothing when no axis shrinks). It added a table unresized in raster order whenever the patch count matched (4.27 off for an 8 x 32 grid and a 16 x 16 table), and did not antialias a downsampled axis (0.81 off). A `(B, N, C)` patch output carries no grid and is read as a square grid, which is silently wrong for a non-square grid (128 x 512 at patch 16) and an error for a token count that is not a square number (192 x 336): pass the new `patch_size` argument, which gives such an output the grid `(H // p_h, W // p_w)`, or return patch embeddings of shape `(B, C, h, w)`. Without `patch_size`, the square reading is unchanged, and a token count that is not a square number raises `BaseError` saying so, where it raised a shape error or gave wrong values. A float16 or bfloat16 table on the CPU is resized in float32. A position table passed as an `nn.Parameter` stays a parameter of the module and is trained with it; it was registered as a buffer.
+- `KimiVLModel` and `MoonViT` apply a `(B, N, N)` attention mask per sample, shared by the heads. The mask's leading dimension lined up with the attention heads: outputs were wrong when the batch size equalled the number of heads, and batch sizes other than 1 and the number of heads raised.
+- `PaliGemma` follows Gemma: the text embeddings are scaled by `sqrt(hidden_size)`, the embedding's padding row is the new `PaliGemmaConfig.pad_token_id` (default 0) instead of `ignore_index`, the MLP uses tanh GELU, and `GemmaRMSNorm` multiplies by `1 + weight` in float32 before casting. `ignore_index = -100` wrapped to row `vocab_size - 100`, a real token whose embedding was zeroed and received no gradient.
+- When the checkpoint of a repository outside its supported list does not fit the configuration `SigLip2Config.from_name` reads from the name, `SigLip2Builder.from_pretrained_hf` raises a `RuntimeError` that lists the supported names and says which architecture such a name must have. It raised `load_state_dict`'s bare size-mismatch error. A fine-tune or mirror whose checkpoint fits the configuration read from its name loads as before. An image size in such a name counts only as a whole number, of the repository part after the last `/` and else of the owner part: `org2560/siglip2-base-patch16-384` and `org-256/siglip2-base-patch16-384` read 384 where they read 256, and `x/siglip2-base-patch16-ckpt2560` reads 224 where it read 256, while `siglip384/finetune` still reads 384.
diff --git a/docs/export_support/cases_models.py b/docs/export_support/cases_models.py
index fd9da1586..139826c7a 100644
--- a/docs/export_support/cases_models.py
+++ b/docs/export_support/cases_models.py
@@ -723,7 +723,7 @@ A(
"models.processors",
NaFlex(_pe_conv, torch.randn(16, 8)),
[torch.rand(1, 3, 32, 32)],
- note="num_patches == pos rows -> plain add",
+ note="4x4 patch grid == the 4x4 pos-embed grid -> plain add, no resize",
)
)
@@ -783,7 +783,7 @@ A(
"models.vlm",
SigLip2ImagePreprocessor((32, 40)),
[torch.rand(1, 3, 48, 64) * 255],
- note="Rescale(1/255) + Resize bicubic antialias + Normalize; size baked",
+ note="Rescale(1/255) + Resize bilinear antialias (default; bicubic via interpolation=) + Normalize; size baked",
)
)
A(
diff --git a/docs/source/_data/export_support.json b/docs/source/_data/export_support.json
index c17d62ced..ec764763a 100644
--- a/docs/source/_data/export_support.json
+++ b/docs/source/_data/export_support.json
@@ -21189,7 +21189,7 @@
"export_detail": "",
"graph_breaks": 0,
"name": "models.processors.NaFlex[matching pos]",
- "note": "num_patches == pos rows -> plain add",
+ "note": "4x4 patch grid == the 4x4 pos-embed grid -> plain add, no resize",
"onnx": "ok",
"onnx_detail": "",
"operator": "NaFlex",
@@ -21257,7 +21257,7 @@
"export_detail": "",
"graph_breaks": 0,
"name": "models.siglip2.SigLip2ImagePreprocessor",
- "note": "Rescale(1/255) + Resize bicubic antialias + Normalize; size baked",
+ "note": "Rescale(1/255) + Resize bilinear antialias (default; bicubic via interpolation=) + Normalize; size baked",
"onnx": "ok",
"onnx_detail": "",
"operator": "siglip2.SigLip2ImagePreprocessor",
diff --git a/docs/source/models.rst b/docs/source/models.rst
index cb3bc3661..9272d2625 100644
--- a/docs/source/models.rst
+++ b/docs/source/models.rst
@@ -7,8 +7,11 @@ kornia.models
Builders for Kornia's ready-to-use models (object detection, edge detection, semantic segmentation and Kimi-VL).
Each builder returns a configured model with pretrained weights. For the papers behind the models, see the :doc:`Models </models/index>` section.
-Pretrained weights are downloaded on first use, and the model builders return a regular ``nn.Module`` that accepts a
-batched ``(B, 3, H, W)`` float image in ``[0, 1]``. :func:`kornia.io.get_sample_images` provides a couple of sample images for quick experiments.
+Pretrained weights are downloaded on first use, and the model builders return a regular ``nn.Module``. Every model
+here except Kimi-VL accepts a batched ``(B, 3, H, W)`` float image in ``[0, 1]``. Kimi-VL takes that image normalized
+with mean = std = 0.5 per channel (``2 * x - 1``), as its checkpoint's ``preprocessor_config.json`` specifies, with
+``H`` and ``W`` multiples of 28 (see ``kornia.models.kimi_vl.KimiVLModel.forward``). :func:`kornia.io.get_sample_images`
+provides a couple of sample images for quick experiments.
.. _RTDETRDetectorBuilder:
diff --git a/kornia/models/kimi_vl/model.py b/kornia/models/kimi_vl/model.py
index 1d61ac4cf..3414da7ec 100644
--- a/kornia/models/kimi_vl/model.py
+++ b/kornia/models/kimi_vl/model.py
@@ -105,8 +105,13 @@ class KimiVLModel(nn.Module):
"""Forward pass.
Args:
- images: (B, C, H, W)
- attention_mask: (B, 1, N, N) or (B, N, N) optional mask for vision encoder.
+ images: (B, C, H, W) image normalized with mean = std = 0.5 per channel, i.e. ``2 * x - 1`` for an image
+ ``x`` in ``[0, 1]``, as the Kimi-VL checkpoint's ``preprocessor_config.json`` specifies. H and W must
+ be multiples of ``2 * patch_size`` (28 for the released checkpoint): sizes that are not multiples of
+ ``patch_size`` are cropped silently, and an odd number of patch rows or columns raises.
+ attention_mask: (B, 1, N, N) or (B, N, N) optional boolean mask for the vision encoder over its N
+ patches, ``True`` where a patch may attend to another. A (B, N, N) mask holds one mask per sample,
+ shared by the heads.
Returns:
Projected visual features (B, seq_len, output_dim)
diff --git a/kornia/models/kimi_vl/moonvit.py b/kornia/models/kimi_vl/moonvit.py
index daf1bd02c..6c09b6f1f 100644
--- a/kornia/models/kimi_vl/moonvit.py
+++ b/kornia/models/kimi_vl/moonvit.py
@@ -127,9 +127,10 @@ class MoonViTAttention(nn.Module):
:math:`(N, d / 2)`, where ``d = D / H`` is the per-head dimension.
sin: Sine component of the rotary positional embedding with shape
:math:`(N, d / 2)`.
- attention_mask: Optional mask broadcastable to the scaled dot-product
- attention scores. It can be used to prevent selected tokens from
- attending to one another.
+ attention_mask: Optional boolean mask, ``True`` where a query may attend to a key: :math:`(B, N, N)`,
+ one mask per sample shared by the heads, or :math:`(B, 1, N, N)` or any other form that broadcasts
+ against the :math:`(B, H, N, N)` attention scores of
+ :func:`~torch.nn.functional.scaled_dot_product_attention`.
Returns:
Tensor with shape :math:`(B, N, D)` containing the attended visual token
@@ -153,6 +154,10 @@ class MoonViTAttention(nn.Module):
query = apply_rotary_pos_emb(query, cos, sin)
key = apply_rotary_pos_emb(key, cos, sin)
+ if attention_mask is not None and attention_mask.dim() == 3:
+ # (B, N, N) -> (B, 1, N, N): one mask per sample, broadcast over the heads. Passed as is, its leading
+ # dimension would line up with the heads of the (B, H, N, N) scores.
+ attention_mask = attention_mask.unsqueeze(1)
attn_output = F.scaled_dot_product_attention(
query, key, value, attn_mask=attention_mask, dropout_p=self.dropout.p if self.training else 0.0
)
@@ -307,8 +312,13 @@ class MoonViT(nn.Module):
"""Forward pass.
Args:
- pixel_values: (B, C, H, W)
- attention_mask: (B, 1, N, N) or (B, N, N) optional mask.
+ pixel_values: (B, C, H, W) image normalized with mean = std = 0.5 per channel, i.e. ``2 * x - 1`` for an
+ image ``x`` in ``[0, 1]``, as the Kimi-VL checkpoint's ``preprocessor_config.json`` specifies. H and W
+ should be multiples of ``2 * patch_size`` (28 for the released checkpoint), which
+ :class:`~kornia.models.kimi_vl.KimiVLModel` needs to merge the patches 2 x 2: the patch embedding crops
+ a size that is not a multiple of ``patch_size`` silently.
+ attention_mask: (B, 1, N, N) or (B, N, N) optional boolean mask over the N patches, ``True`` where a patch
+ may attend to another. A (B, N, N) mask holds one mask per sample, shared by the heads.
Returns:
(B, seq_len, hidden_size)
diff --git a/kornia/models/paligemma/configuration_paligemma.py b/kornia/models/paligemma/configuration_paligemma.py
index ab5b7ca13..3db44976c 100644
--- a/kornia/models/paligemma/configuration_paligemma.py
+++ b/kornia/models/paligemma/configuration_paligemma.py
@@ -40,6 +40,7 @@ class PaliGemmaConfig:
rope_theta: The base period of the RoPE embeddings.
ignore_index: Index to ignore in the loss function.
image_token_index: Token index used for image placeholders.
+ pad_token_id: Index of the padding token, whose embedding row is zero and receives no gradient. Gemma's is 0.
"""
vision_config: Optional[SigLip2VisionConfig] = field(default_factory=SigLip2VisionConfig)
@@ -54,3 +55,4 @@ class PaliGemmaConfig:
rope_theta: float = 10000.0
ignore_index: int = -100
image_token_index: int = 256000
+ pad_token_id: int = 0
diff --git a/kornia/models/paligemma/modeling_paligemma.py b/kornia/models/paligemma/modeling_paligemma.py
index ee10393b7..705d53b86 100644
--- a/kornia/models/paligemma/modeling_paligemma.py
+++ b/kornia/models/paligemma/modeling_paligemma.py
@@ -51,8 +51,10 @@ class GemmaRMSNorm(nn.Module):
Tensor with the same shape as ``x`` after root-mean-square
normalization and learned scaling.
"""
- output = self._norm(x.float()).type_as(x)
- return output * (1.0 + self.weight)
+ # Gemma normalizes and multiplies by (1 + weight) in float32, then casts: (x * w).to(dtype), not
+ # x.to(dtype) * w as Llama does
+ output = self._norm(x.float()) * (1.0 + self.weight.float())
+ return output.type_as(x)
class GemmaRotaryEmbedding(nn.Module):
@@ -123,7 +125,8 @@ class GemmaMLP(nn.Module):
self.gate_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
self.up_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
self.down_proj = nn.Linear(self.intermediate_size, self.hidden_size, bias=False)
- self.act_fn = nn.GELU()
+ # Gemma's hidden_act, gelu_pytorch_tanh
+ self.act_fn = nn.GELU(approximate="tanh")
def forward(self, x: torch.Tensor) -> torch.Tensor:
"""Apply the gated Gemma feed-forward projection.
@@ -275,7 +278,7 @@ class PaliGemma(nn.Module):
def __init__(self, config: PaliGemmaConfig) -> None:
super().__init__()
self.config = config
- self.padding_idx = config.ignore_index
+ self.padding_idx = config.pad_token_id
self.vocab_size = config.vocab_size
if config.vision_config is None:
@@ -312,14 +315,22 @@ class PaliGemma(nn.Module):
) -> torch.Tensor:
"""Forward pass of the model.
+ The image tokens are prepended to the text tokens: the decoder input is the projected image features followed
+ by the text embeddings, scaled by ``sqrt(hidden_size)`` as in Gemma; the image features are not scaled.
+
Args:
- input_ids: Text tokens (batch, input_seq_len)
+ input_ids: Text tokens only (batch, input_seq_len), without ``<image>`` placeholder tokens: the image
+ tokens are prepended to them, not substituted for placeholders.
pixel_values: Images (batch, channels, height, width)
- attention_mask: Optional attention mask.
+ attention_mask: Optional attention mask over the image and text positions together, in a form
+ :func:`~torch.nn.functional.scaled_dot_product_attention` broadcasts against the
+ (batch, heads, total_seq_len, total_seq_len) scores, e.g. (batch, 1, total_seq_len, total_seq_len).
+ A (batch, input_seq_len) text padding mask raises.
position_ids: Optional position IDs.
Returns:
- logits: Prediction scores (batch, total_seq_len, vocab_size).
+ logits: Prediction scores (batch, total_seq_len, vocab_size), where total_seq_len is the number of image
+ tokens plus input_seq_len: the logits include the image positions.
"""
vision_outputs = self.vision_tower(pixel_values)
@@ -331,6 +342,9 @@ class PaliGemma(nn.Module):
image_features = self.multi_modal_projector(image_features)
inputs_embeds = self.embed_tokens(input_ids)
+ # Gemma scales the text embeddings by sqrt(hidden_size), a tensor in the embedding dtype; PaliGemma's image
+ # features enter unscaled (transformers divides them by the same factor before Gemma multiplies the sequence)
+ inputs_embeds = inputs_embeds * torch.tensor(self.config.hidden_size**0.5, dtype=inputs_embeds.dtype)
inputs_embeds = torch.cat([image_features, inputs_embeds], dim=1)
diff --git a/kornia/models/processors/naflex.py b/kornia/models/processors/naflex.py
index 1bb350d90..1aea6d70d 100644
--- a/kornia/models/processors/naflex.py
+++ b/kornia/models/processors/naflex.py
@@ -17,26 +17,61 @@
from __future__ import annotations
import math
-from typing import Callable
+from typing import Callable, Optional, Union
+import torch
from torch import Tensor, nn
from torch.nn import functional as F
+from kornia.core._compat import torch_version_lt
+from kornia.core.check import KORNIA_CHECK
+
__all__ = ["NaFlex"]
class NaFlex(nn.Module):
r"""NaFlex wrapper for vision embeddings that supports flexible image sizes.
- This module wraps a patch embedding function and a position embedding tensor.
- It computes patch embeddings and dynamically interpolates the position embeddings
- to match the input resolution using bilinear interpolation.
+ This module wraps a patch embedding function and a square position embedding table. It computes the patch
+ embeddings of an image and adds the table resized to the image's patch grid, as transformers'
+ ``Siglip2VisionEmbeddings.resize_positional_embeddings`` does for SigLIP 2's NaFlex variant: the resize is
+ bilinear interpolation (``align_corners=False``), antialiased when the grid is smaller than the table along an
+ axis, so a downsampled axis averages the table instead of sampling it. transformers always antialiases; when no
+ axis is downsampled antialiasing changes nothing (up to float rounding), and the plain resize keeps working where
+ the antialiased one does not (see the note). A square table is added unresized only when the patch grid is the
+ table's own grid.
Args:
patch_embedding_fcn: A callable (e.g., Conv2d) that takes images and returns
- patch embeddings of shape :math:`(B, C, H, W)` or :math:`(B, N, C)`.
- position_embedding: Position embedding tensor of shape :math:`(N, C)` to be
- interpolated to match input resolution.
+ patch embeddings of shape :math:`(B, C, h, w)` or :math:`(B, N, C)`. A :math:`(B, C, h, w)` output gives
+ the patch grid. A :math:`(B, N, C)` output carries no grid: without ``patch_size`` its :math:`N` tokens
+ are read as a square :math:`\sqrt{N} \times \sqrt{N}` grid in raster order, and a :math:`N` that is not
+ a square number raises. A non-square grid therefore needs ``patch_size`` or a :math:`(B, C, h, w)` output:
+ the :math:`8 \times 32` grid of a :math:`128 \times 512` image at patch 16 is read right with
+ ``patch_size=16``, and as :math:`16 \times 16` without it.
+ position_embedding: Position embedding table of shape :math:`(S^2, C)`, the raster-order rows of an
+ :math:`S \times S` grid, to be interpolated to match input resolution. An ``nn.Parameter`` stays a
+ parameter of the module, so it is trained with it; any other tensor is registered as a buffer. A table
+ that is not a square grid is added as is when it has one row per patch.
+ patch_size: The patch size :math:`p` or :math:`(p_h, p_w)` of a patch embedding that returns
+ :math:`(B, N, C)`, which then has the grid :math:`(H // p_h, W // p_w)` of whole patches with the remainder
+ dropped (a ``Conv2d`` with that kernel and stride); the grid must have :math:`N` cells. Ignored for a
+ :math:`(B, C, h, w)` output. Default: ``None``, the square reading above.
+
+ Note:
+ A float16 or bfloat16 table on the CPU is resized in float32 and cast back, as transformers does: the CPU has
+ no half-precision antialiased bilinear kernel. A table on MPS that is downsampled is resized on the CPU in
+ float32 with torch older than 2.7, which has no MPS antialiased kernel.
+
+ Eager mode picks the resize per call, from the grid and the table size. An exported graph with dynamic H and W
+ keeps the choice made for its example input. With the dynamo ONNX exporter
+ (``torch.onnx.export(..., dynamo=True)``), export from an input whose grid is smaller than the table along both
+ axes: the graph then resizes with antialiasing at every size, which is right for every grid because
+ antialiasing changes nothing when upsampling. ``torch.export.export`` reports that size comparison as a
+ constraint violation; ``torch.onnx.export`` exports anyway on torch 2.14 and refuses on torch 2.5.1. The
+ legacy TorchScript exporter cannot export the antialiased resize (``UnsupportedOperatorError`` for
+ ``aten::_upsample_bilinear2d_aa``), so it exports only from an example grid at least as large as the table
+ along both axes, and its graph resizes without antialiasing at every size, which is exact only for such grids.
Example:
>>> import torch
@@ -54,10 +89,19 @@ class NaFlex(nn.Module):
self,
patch_embedding_fcn: Callable[[Tensor], Tensor],
position_embedding: Tensor,
+ patch_size: Optional[Union[int, tuple[int, int]]] = None,
) -> None:
super().__init__()
self.patch_embedding_fcn = patch_embedding_fcn
- self.register_buffer("position_embedding", position_embedding)
+ self.patch_size: Optional[tuple[int, int]] = None
+ if patch_size is not None:
+ self.patch_size = (
+ (patch_size, patch_size) if isinstance(patch_size, int) else (patch_size[0], patch_size[1])
+ )
+ if isinstance(position_embedding, nn.Parameter):
+ self.position_embedding = position_embedding
+ else:
+ self.register_buffer("position_embedding", position_embedding)
def forward(self, pixel_values: Tensor) -> Tensor:
r"""Forward pass through NaFlex wrapper.
@@ -69,25 +113,73 @@ class NaFlex(nn.Module):
Embeddings with interpolated positional embeddings of shape :math:`(B, N, C)`.
Raises:
- ValueError: If original positional embedding does not form a square grid.
+ ValueError: If original positional embedding does not form a square grid and does not have one row per
+ patch.
+ BaseError: If a :math:`(B, N, C)` patch output's grid cannot be read: with ``patch_size``, when
+ :math:`(H // p_h) (W // p_w) \neq N`; without it, when :math:`N` is not a square number.
"""
embeddings = self.patch_embedding_fcn(pixel_values)
+ grid = embeddings.shape[2:] if embeddings.ndim == 4 else None
if embeddings.ndim == 4:
- _, _, h_grid, w_grid = embeddings.shape
embeddings = embeddings.flatten(2).transpose(1, 2)
- num_patches = h_grid * w_grid
- else:
- _, num_patches, _ = embeddings.shape
- h_grid = int(math.sqrt(num_patches))
- w_grid = h_grid
- if self.position_embedding.shape[0] == num_patches:
- return embeddings + self.position_embedding.unsqueeze(0)
- orig_num = int(self.position_embedding.shape[0])
- orig_grid = int(math.sqrt(orig_num))
+ num_patches = embeddings.shape[1]
+ position_embedding = self.position_embedding
+ orig_num = int(position_embedding.shape[0])
+ orig_grid = math.isqrt(orig_num)
if orig_grid * orig_grid != orig_num:
+ # a table that is not a square grid cannot be resized; one row per patch is added in raster order
+ if orig_num == num_patches:
+ return embeddings + position_embedding.unsqueeze(0)
raise ValueError(f"Original positional embedding is not a square grid (got {orig_num} embeddings)")
- pos = self.position_embedding.view(orig_grid, orig_grid, -1).permute(2, 0, 1).unsqueeze(0)
- pos_resized = F.interpolate(pos, size=(h_grid, w_grid), mode="bilinear", align_corners=False)
- pos_resized = pos_resized.squeeze(0).permute(1, 2, 0).view(h_grid * w_grid, -1)
+ h_grid, w_grid = grid if grid is not None else self._token_grid(num_patches, *pixel_values.shape[-2:])
+ if (h_grid, w_grid) == (orig_grid, orig_grid):
+ return embeddings + position_embedding.unsqueeze(0)
+ # transformers always passes antialias=True. Antialiasing only changes a downsampled axis: an upsampled one
+ # gets plain bilinear weights either way (equal up to float rounding), so the plain resize, which the legacy
+ # TorchScript ONNX exporter and MPS before torch 2.7 support, is used when no axis shrinks. Python ints from
+ # the shapes: dynamo guards on the comparison instead of breaking the graph.
+ antialias = h_grid < orig_grid or w_grid < orig_grid
+ pos = position_embedding.reshape(orig_grid, orig_grid, -1).permute(2, 0, 1).unsqueeze(0)
+ # Required, not an optimization: the CPU has no float16/bfloat16 antialiased bilinear kernel
+ # (NotImplementedError on torch 2.14, RuntimeError on 2.5.1), as transformers notes where it upcasts on the CPU
+ # (for every resize, which keeps its float32 values), and MPS has none before torch 2.7. A float64 table keeps
+ # its precision.
+ if (pos.device.type == "cpu" and pos.dtype in (torch.float16, torch.bfloat16)) or (
+ antialias and pos.device.type == "mps" and torch_version_lt(2, 7, 0)
+ ):
+ pos = pos.to("cpu", torch.float32)
+ pos_resized = F.interpolate(
+ pos, size=(h_grid, w_grid), mode="bilinear", align_corners=False, antialias=antialias
+ )
+ pos_resized = pos_resized.squeeze(0).permute(1, 2, 0).reshape(h_grid * w_grid, -1)
+ pos_resized = pos_resized.to(position_embedding.device, position_embedding.dtype)
return embeddings + pos_resized.unsqueeze(0)
+
+ def _token_grid(self, num_patches: int, height: int, width: int) -> tuple[int, int]:
+ """Return the patch grid of the ``num_patches`` tokens of a ``height x width`` image.
+
+ ``(height // p_h, width // p_w)`` with ``patch_size``, else the square grid of a square ``num_patches``.
+
+ Raises:
+ BaseError: if that grid does not have ``num_patches`` cells, or without ``patch_size`` if
+ ``num_patches`` is not a square number.
+ """
+ if self.patch_size is not None:
+ patch_h, patch_w = self.patch_size
+ h_grid, w_grid = height // patch_h, width // patch_w
+ KORNIA_CHECK(
+ h_grid * w_grid == num_patches,
+ f"NaFlex reads the grid of a (B, N, C) patch output from patch_size={self.patch_size}: a {height} x "
+ f"{width} image has a {h_grid} x {w_grid} grid of {h_grid * w_grid} patches, but the patch embedding "
+ f"returned {num_patches}.",
+ )
+ return h_grid, w_grid
+ side = math.isqrt(num_patches)
+ KORNIA_CHECK(
+ side * side == num_patches,
+ f"NaFlex reads a (B, N, C) patch output without patch_size as a square grid, but {num_patches} patch "
+ "embeddings are not a square number. Pass patch_size to NaFlex, or make the patch embedding return "
+ "(B, C, h, w).",
+ )
+ return side, side
diff --git a/kornia/models/siglip2/builder.py b/kornia/models/siglip2/builder.py
index bf9ea5152..ca1be13bc 100644
--- a/kornia/models/siglip2/builder.py
+++ b/kornia/models/siglip2/builder.py
@@ -27,7 +27,7 @@ import torch
from kornia.core.download import download_hf_file
from kornia.core.safetensors import check_safetensors, load_safetensors
-from .config import SigLip2Config
+from .config import _SUPPORTED_MODELS, SigLip2Config
from .model import SigLip2Model
_logger = logging.getLogger(__name__)
@@ -94,7 +94,8 @@ class SigLip2Builder:
model_name: HuggingFace model identifier.
Returns:
- SigLip2Model instance with random initialization.
+ SigLip2Model instance with random initialization, configured by ``SigLip2Config.from_name``: a name outside
+ its supported list gets the configuration read from the name's parts.
"""
config = SigLip2Config.from_name(model_name)
return SigLip2Model(config)
@@ -131,6 +132,10 @@ class SigLip2Builder:
- google/siglip2-large-patch16-384
- google/siglip2-large-patch16-512
+ Another repository, such as a fine-tune or a mirror of one of these, loads when its checkpoint has the
+ architecture ``SigLip2Config.from_name`` reads from its name's parts (base unless the name contains
+ ``"large"``, patch size 16, the image size in its name).
+
Args:
model_name: HuggingFace model identifier. Default: "google/siglip2-base-patch16-224".
cache_dir: Optional cache directory for model files. Defaults to
@@ -141,6 +146,10 @@ class SigLip2Builder:
SigLip2Model instance with pretrained weights, in evaluation mode, since it always loads weights (see
:ref:`pretrained-models-conventions`).
+ Raises:
+ RuntimeError: if the checkpoint of a repository outside the supported list does not fit the configuration
+ read from its name; the message lists the supported names.
+
.. note::
The repository must publish its weights as a single
``model.safetensors`` file at its root.
@@ -162,6 +171,17 @@ class SigLip2Builder:
# create model and load weights directly (no transformation needed)
model = SigLip2Model(config)
- model.load_state_dict(state_dict, strict=True)
+ try:
+ model.load_state_dict(state_dict, strict=True)
+ except RuntimeError as e:
+ if model_name in _SUPPORTED_MODELS:
+ raise
+ raise RuntimeError(
+ f"The checkpoint of {model_name!r} does not fit the configuration SigLip2Config.from_name reads from "
+ f"this name. Supported names: {', '.join(_SUPPORTED_MODELS)}. A repository outside that list must "
+ "have the architecture its name gives: base (hidden size 768, 12 layers, 12 heads) unless the name "
+ "contains 'large' (1024, 24, 16), patch size 16, and the first of the image sizes 224, 256, 384 and "
+ "512 that is a whole number in the repository part of the name, else in its owner part, else 224."
+ ) from e
return model.eval()
diff --git a/kornia/models/siglip2/config.py b/kornia/models/siglip2/config.py
index 00c58d824..6394a3ffc 100644
--- a/kornia/models/siglip2/config.py
+++ b/kornia/models/siglip2/config.py
@@ -19,9 +19,30 @@
from __future__ import annotations
+import re
from dataclasses import dataclass
from typing import Optional
+from torch import nn
+
+
+def _activation(hidden_act: str) -> nn.Module:
+ """Return the MLP activation that a ``hidden_act`` config value names.
+
+ The names are transformers' ``ACT2FN`` keys: ``"gelu_pytorch_tanh"`` and ``"gelu_new"`` are the tanh approximation
+ of GELU, which the released SigLIP and SigLIP 2 checkpoints use, and ``"gelu"`` is the exact GELU.
+
+ Raises:
+ ValueError: for any other value.
+ """
+ if hidden_act in ("gelu_pytorch_tanh", "gelu_new"):
+ return nn.GELU(approximate="tanh")
+ if hidden_act == "gelu":
+ return nn.GELU()
+ raise ValueError(
+ f"Unsupported hidden_act {hidden_act!r}: expected 'gelu_pytorch_tanh' or 'gelu_new' (tanh GELU) or 'gelu'."
+ )
+
@dataclass
class SigLip2VisionConfig:
@@ -35,7 +56,9 @@ class SigLip2VisionConfig:
num_hidden_layers: Number of transformer layers.
num_attention_heads: Number of attention heads.
intermediate_size: Intermediate size in feed-forward network.
- hidden_act: Activation function (typically 'gelu').
+ hidden_act: Activation of the MLPs: ``"gelu_pytorch_tanh"`` (default, the checkpoints' value) or
+ ``"gelu_new"`` for tanh GELU, ``"gelu"`` for exact GELU. Other values raise ``ValueError`` when the model
+ is built.
layer_norm_eps: Epsilon for layer normalization.
dropout_p: Dropout probability.
attention_dropout_p: Attention dropout probability.
@@ -48,7 +71,7 @@ class SigLip2VisionConfig:
num_hidden_layers: int = 12
num_attention_heads: int = 12
intermediate_size: int = 3072
- hidden_act: str = "gelu"
+ hidden_act: str = "gelu_pytorch_tanh"
layer_norm_eps: float = 1e-6
dropout_p: float = 0.0
attention_dropout_p: float = 0.0
@@ -65,7 +88,9 @@ class SigLip2TextConfig:
num_attention_heads: Number of attention heads.
intermediate_size: Intermediate size in feed-forward network.
max_position_embeddings: Maximum sequence length.
- hidden_act: Activation function (typically 'gelu').
+ hidden_act: Activation of the MLPs: ``"gelu_pytorch_tanh"`` (default, the checkpoints' value) or
+ ``"gelu_new"`` for tanh GELU, ``"gelu"`` for exact GELU. Other values raise ``ValueError`` when the model
+ is built.
layer_norm_eps: Epsilon for layer normalization.
dropout_p: Dropout probability.
attention_dropout_p: Attention dropout probability.
@@ -77,12 +102,51 @@ class SigLip2TextConfig:
num_attention_heads: int = 12
intermediate_size: int = 3072
max_position_embeddings: int = 512
- hidden_act: str = "gelu"
+ hidden_act: str = "gelu_pytorch_tanh"
layer_norm_eps: float = 1e-6
dropout_p: float = 0.0
attention_dropout_p: float = 0.0
+# The checkpoints SigLip2Config.from_name supports: name -> (vocab_size, hidden_size, num_hidden_layers,
+# num_attention_heads, image_size), from each checkpoint's config.json on the Hugging Face Hub and transformers'
+# SiglipTextConfig / SiglipVisionConfig defaults for the fields it omits (vocabulary 32000, hidden size 768, 12 layers,
+# 12 heads, image size 224, patch size 16, 64 text positions).
+_SUPPORTED_MODELS: dict[str, tuple[int, int, int, int, int]] = {
+ "google/siglip-base-patch16-224": (32000, 768, 12, 12, 224),
+ "google/siglip2-base-patch16-224": (256000, 768, 12, 12, 224),
+ "google/siglip2-base-patch16-256": (256000, 768, 12, 12, 256),
+ "google/siglip2-base-patch16-384": (256000, 768, 12, 12, 384),
+ "google/siglip2-base-patch16-512": (256000, 768, 12, 12, 512),
+ "google/siglip2-large-patch16-256": (256000, 1024, 24, 16, 256),
+ "google/siglip2-large-patch16-384": (256000, 1024, 24, 16, 384),
+ "google/siglip2-large-patch16-512": (256000, 1024, 24, 16, 512),
+}
+
+
+def _read_name_parts(model_name: str) -> tuple[int, int, int, int, int]:
+ """Read (vocab_size, hidden_size, num_hidden_layers, num_attention_heads, image_size) from a name's parts.
+
+ Used by ``SigLip2Config.from_name`` for a name outside ``_SUPPORTED_MODELS``: large if the name contains
+ ``"large"``, base otherwise; the first of 224, 256, 384 and 512 that is a whole number of the repository part of
+ the name, after its last ``/``, else of the owner part before it, else 224; the SigLIP 1 vocabulary only for a name
+ containing ``google/siglip-base-patch16-224``.
+ """
+ # Whole numbers only ("x/siglip2-ckpt2560" is 224), and the repository's before the owner's:
+ # "org-256/siglip2-base-patch16-384" is 384, "siglip384/finetune" is 384.
+ image_size = 224
+ for part in reversed(model_name.rsplit("/", 1)):
+ numbers = set(re.split(r"[^0-9]+", part))
+ size = next((size for size in (224, 256, 384, 512) if str(size) in numbers), None)
+ if size is not None:
+ image_size = size
+ break
+ vocab_size = 32000 if "google/siglip-base-patch16-224" in model_name else 256000
+ if "large" in model_name:
+ return vocab_size, 1024, 24, 16, image_size
+ return vocab_size, 768, 12, 12, image_size
+
+
@dataclass
class SigLip2Config:
"""Configuration for SigLip2 model.
@@ -110,7 +174,7 @@ class SigLip2Config:
@staticmethod
def from_name(model_name: str) -> SigLip2Config:
- """Create config from model name.
+ """Create the configuration of a checkpoint from its name.
Supports the following models:
- google/siglip-base-patch16-224 (V1)
@@ -122,45 +186,33 @@ class SigLip2Config:
- google/siglip2-large-patch16-384
- google/siglip2-large-patch16-512
+ Each of these names gives its checkpoint's ``config.json`` values: patch size 16, 64 text positions, the
+ vocabulary (32000 for the SigLIP 1 model, 256000 for SigLIP 2), and the base (hidden size 768, 12 layers, 12
+ heads) or large (1024, 24, 16) architecture.
+
+ Any other name, such as a fine-tune or a mirror of one of these checkpoints, is read from its parts: the large
+ architecture if it contains ``"large"`` and the base one otherwise, patch size 16, the first of the image sizes
+ 224, 256, 384 and 512 that is a whole number in the repository part after the last ``/``, else in the owner
+ part before it, else 224, the SigLIP 2 vocabulary (SigLIP 1's if the name contains
+ ``google/siglip-base-patch16-224``) and 512 text positions. That configuration fits only a checkpoint with that
+ architecture: ``SigLip2Builder.from_pretrained_hf`` adapts the text positions to the checkpoint and raises
+ ``RuntimeError`` when its other shapes differ.
+
Args:
model_name: HuggingFace model identifier.
Returns:
SigLip2Config instance configured for the specified model.
"""
- # Parse model name
- is_v1 = "google/siglip-base-patch16-224" in model_name
- is_large = "large" in model_name
-
- # Extract image size from model name
- image_size = 224 # default
- if "224" in model_name:
- image_size = 224
- elif "256" in model_name:
- image_size = 256
- elif "384" in model_name:
- image_size = 384
- elif "512" in model_name:
- image_size = 512
-
- # Base vs Large configurations
- if is_large:
- hidden_size = 1024
- num_layers = 24
- num_heads = 16
- projection_dim = 1024
- else: # base
- hidden_size = 768
- num_layers = 12
- num_heads = 12
- projection_dim = 768
-
- # Intermediate size is typically 4x hidden_size
+ text_kwargs: dict[str, int] = {}
+ if model_name in _SUPPORTED_MODELS:
+ vocab_size, hidden_size, num_layers, num_heads, image_size = _SUPPORTED_MODELS[model_name]
+ text_kwargs["max_position_embeddings"] = 64
+ else:
+ vocab_size, hidden_size, num_layers, num_heads, image_size = _read_name_parts(model_name)
+ # every supported checkpoint has an MLP of 4 x hidden_size (3072 for base, 4096 for large)
intermediate_size = 4 * hidden_size
- # V1 vs V2 vocab size
- vocab_size = 32000 if is_v1 else 256000
-
vision_config = SigLip2VisionConfig(
image_size=image_size,
patch_size=16,
@@ -176,10 +228,11 @@ class SigLip2Config:
num_hidden_layers=num_layers,
num_attention_heads=num_heads,
intermediate_size=intermediate_size,
+ **text_kwargs,
)
return SigLip2Config(
vision_config=vision_config,
text_config=text_config,
- projection_dim=projection_dim,
+ projection_dim=hidden_size,
)
diff --git a/kornia/models/siglip2/model.py b/kornia/models/siglip2/model.py
index 09cab516b..1a9ebb977 100644
--- a/kornia/models/siglip2/model.py
+++ b/kornia/models/siglip2/model.py
@@ -27,6 +27,8 @@ import torch
import torch.nn.functional as F
from torch import nn
+from kornia.core.check import KORNIA_CHECK
+
from .config import SigLip2Config
from .text_encoder import SigLip2TextModel
from .vision_encoder import SigLip2VisionModel
@@ -201,7 +203,8 @@ class SigLip2Model(nn.Module):
input_ids: Token IDs of shape (batch_size, seq_len).
attention_mask: Optional attention mask for text encoder of shape (batch_size, seq_len).
position_ids: Optional position IDs for text encoder.
- return_loss: Whether to compute and return contrastive loss.
+ return_loss: Whether to compute and return the pairwise sigmoid loss. It pairs the ``i``-th image with the
+ ``i``-th text, so it needs as many images as texts.
Returns:
SigLip2Result containing:
@@ -210,7 +213,13 @@ class SigLip2Model(nn.Module):
- logit_scale: Logit scale parameter
- logits_per_image: Logits for image-to-text matching (if both provided)
- logits_per_text: Logits for text-to-image matching (if both provided)
- - loss: Contrastive loss (if return_loss=True and both provided)
+ - loss: The SigLIP pairwise sigmoid loss over all ``B x B`` pairs, with the ``i``-th image and the ``i``-th
+ text as the only matching pairs, ``-logsigmoid((2 I - 1) * logits_per_text).sum(-1).mean()`` (if
+ return_loss=True and both provided)
+
+ Raises:
+ BaseError: if ``return_loss`` is True and the numbers of images and texts differ. Without the loss,
+ unequal batches are fine: ``logits_per_image`` is then ``(num_images, num_texts)``.
"""
# get embeddings
image_embeds = self.get_image_features(pixel_values, normalize=True) if pixel_values is not None else None
@@ -230,13 +239,16 @@ class SigLip2Model(nn.Module):
logits_per_text = torch.matmul(text_embeds, image_embeds.t()) * logit_scale + self.logit_bias
logits_per_image = logits_per_text.t()
- # compute loss if requested for training or evaluation
+ # pairwise sigmoid loss (SigLIP paper, eq. 1; transformers' SiglipModel): every image-text pair enters,
+ # the matching pairs on the diagonal labelled +1 and every other pair -1
if return_loss:
- batch_size = image_embeds.shape[0]
- labels = torch.arange(batch_size, device=image_embeds.device)
- loss_img = -F.logsigmoid(logits_per_image[labels, labels]).mean()
- loss_txt = -F.logsigmoid(logits_per_text[labels, labels]).mean()
- loss = (loss_img + loss_txt) / 2.0
+ KORNIA_CHECK(
+ image_embeds.shape[0] == text_embeds.shape[0],
+ "return_loss pairs the i-th image with the i-th text, so it needs as many images as texts; got "
+ f"{image_embeds.shape[0]} images and {text_embeds.shape[0]} texts.",
+ )
+ eye = torch.eye(logits_per_text.shape[0], device=logits_per_text.device, dtype=logits_per_text.dtype)
+ loss = -F.logsigmoid((2 * eye - 1) * logits_per_text).sum(-1).mean()
return SigLip2Result(
image_embeds=image_embeds,
diff --git a/kornia/models/siglip2/preprocessor.py b/kornia/models/siglip2/preprocessor.py
index 11df73572..78b89cfd5 100644
--- a/kornia/models/siglip2/preprocessor.py
+++ b/kornia/models/siglip2/preprocessor.py
@@ -32,7 +32,7 @@ class SigLip2ImagePreprocessor(nn.Module):
This preprocessor applies the following steps:
- Rescales pixel values from [0, 255] to [0, 1]
- - Resizes images to the specified size (with bicubic interpolation and antialiasing)
+ - Resizes images to the specified size (with ``interpolation`` and antialiasing)
- Normalizes with mean=[0.5, 0.5, 0.5] and std=[0.5, 0.5, 0.5] (converts [0, 1] to [-1, 1])
Args:
@@ -40,6 +40,9 @@ class SigLip2ImagePreprocessor(nn.Module):
mean: Normalization mean. Default: [0.5, 0.5, 0.5]
std: Normalization std. Default: [0.5, 0.5, 0.5]
rescale_factor: Rescaling factor. Default: 1/255
+ interpolation: Resize interpolation. The default ``"bilinear"`` is the resampling of the SigLIP 2 checkpoints
+ (``"resample": 2`` in their ``preprocessor_config.json``); pass ``"bicubic"`` for the SigLIP 1 checkpoint
+ ``google/siglip-base-patch16-224`` (``"resample": 3``).
Example:
>>> import torch
@@ -50,7 +53,9 @@ class SigLip2ImagePreprocessor(nn.Module):
>>>
>>> # Process image (assumes input in [0, 255] range)
>>> image = torch.randint(0, 255, (3, 300, 400), dtype=torch.float32)
- >>> processed = preprocessor(image) # Shape: (3, 224, 224), range: [-1, 1]
+ >>> processed = preprocessor(image) # range: [-1, 1]
+ >>> processed.shape
+ torch.Size([1, 3, 224, 224])
"""
def __init__(
@@ -59,6 +64,7 @@ class SigLip2ImagePreprocessor(nn.Module):
mean: list[float] | tuple[float, float, float] = (0.5, 0.5, 0.5),
std: list[float] | tuple[float, float, float] = (0.5, 0.5, 0.5),
rescale_factor: float = 1.0 / 255.0,
+ interpolation: str = "bilinear",
) -> None:
super().__init__()
self.image_size = image_size
@@ -74,7 +80,7 @@ class SigLip2ImagePreprocessor(nn.Module):
preproc_list.append(Rescale(factor=rescale_factor))
# resize (on [0, 1] range)
- preproc_list.append(Resize(size=image_size, interpolation="bicubic", align_corners=False, antialias=True))
+ preproc_list.append(Resize(size=image_size, interpolation=interpolation, align_corners=False, antialias=True))
# normalize (convert [0, 1] to [-1, 1])
preproc_list.append(Normalize(mean=self.mean, std=self.std))
@@ -101,15 +107,19 @@ class SigLip2ImagePreprocessor(nn.Module):
return self.preprocessor(images)
@classmethod
- def from_config(cls, image_size: int | tuple[int, int]) -> SigLip2ImagePreprocessor:
+ def from_config(
+ cls, image_size: int | tuple[int, int], interpolation: str = "bilinear"
+ ) -> SigLip2ImagePreprocessor:
"""Create preprocessor from image size configuration.
Args:
image_size: Image size (single int for square, or tuple for (height, width))
+ interpolation: Resize interpolation, ``"bilinear"`` for the SigLIP 2 checkpoints and ``"bicubic"`` for the
+ SigLIP 1 ``google/siglip-base-patch16-224`` (see the class docstring).
Returns:
Preprocessor instance
"""
if isinstance(image_size, int):
image_size = (image_size, image_size)
- return cls(image_size=image_size)
+ return cls(image_size=image_size, interpolation=interpolation)
diff --git a/kornia/models/siglip2/text_encoder.py b/kornia/models/siglip2/text_encoder.py
index e5aec3fbc..9e677dad9 100644
--- a/kornia/models/siglip2/text_encoder.py
+++ b/kornia/models/siglip2/text_encoder.py
@@ -25,7 +25,7 @@ import torch
from torch import nn
from .attention import SigLip2Attention
-from .config import SigLip2TextConfig
+from .config import SigLip2TextConfig, _activation
__all__ = ["SigLip2TextEmbeddings", "SigLip2TextEncoder", "SigLip2TextLayer", "SigLip2TextModel"]
@@ -81,13 +81,16 @@ class SigLip2TextMLP(nn.Module):
"""MLP (feed-forward network) for text encoder.
Args:
- config: Text encoder configuration.
+ config: Text encoder configuration. Its ``hidden_act`` selects the activation.
+
+ Raises:
+ ValueError: if ``config.hidden_act`` is not ``"gelu_pytorch_tanh"``, ``"gelu_new"`` or ``"gelu"``.
"""
def __init__(self, config: SigLip2TextConfig) -> None:
super().__init__()
self.fc1 = nn.Linear(config.hidden_size, config.intermediate_size)
- self.activation = nn.GELU()
+ self.activation = _activation(config.hidden_act)
self.fc2 = nn.Linear(config.intermediate_size, config.hidden_size)
self.dropout = nn.Dropout(config.dropout_p)
diff --git a/kornia/models/siglip2/vision_encoder.py b/kornia/models/siglip2/vision_encoder.py
index 6882a3797..ebfe75e84 100644
--- a/kornia/models/siglip2/vision_encoder.py
+++ b/kornia/models/siglip2/vision_encoder.py
@@ -25,7 +25,7 @@ import torch
from torch import nn
from .attention import SigLip2Attention
-from .config import SigLip2VisionConfig
+from .config import SigLip2VisionConfig, _activation
__all__ = [
"SigLip2MultiheadAttentionPoolingHead",
@@ -92,13 +92,16 @@ class SigLip2VisionMLP(nn.Module):
"""MLP (feed-forward network) for vision encoder.
Args:
- config: Vision encoder configuration.
+ config: Vision encoder configuration. Its ``hidden_act`` selects the activation.
+
+ Raises:
+ ValueError: if ``config.hidden_act`` is not ``"gelu_pytorch_tanh"``, ``"gelu_new"`` or ``"gelu"``.
"""
def __init__(self, config: SigLip2VisionConfig) -> None:
super().__init__()
self.fc1 = nn.Linear(config.hidden_size, config.intermediate_size)
- self.activation = nn.GELU()
+ self.activation = _activation(config.hidden_act)
self.fc2 = nn.Linear(config.intermediate_size, config.hidden_size)
self.dropout = nn.Dropout(config.dropout_p)
@@ -176,16 +179,25 @@ class SigLip2MultiheadAttentionPoolingHead(nn.Module):
self.layernorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
self.mlp = SigLip2VisionMLP(config)
- def forward(self, hidden_state: torch.Tensor) -> torch.Tensor:
+ def forward(self, hidden_state: torch.Tensor, attention_mask: Optional[torch.Tensor] = None) -> torch.Tensor:
"""Pool vision tokens with a learned probe query.
Args:
hidden_state: Vision token tensor with shape :math:`(B, N, D)`,
where :math:`B` is batch size, :math:`N` is token count, and
:math:`D` is hidden size.
+ attention_mask: Optional mask of the tokens, ``1``/``True`` for a token to pool and ``0``/``False`` for
+ padding, in any form :class:`SigLip2Attention` accepts: :math:`(B, N)`, :math:`(B, N, N)` or
+ :math:`(B, 1, N, N)`. The probe does not attend to the padding tokens. For a 3-D or 4-D mask, a token
+ that no query may attend to is padding, so a :math:`(B, N)` mask broadcast over the queries pools
+ exactly as the :math:`(B, N)` mask itself. As in transformers, a padding token's attention score gets
+ ``torch.finfo(dtype).min`` added rather than ``-inf``: a sample whose tokens are all padding pools
+ them with exactly uniform weights in float32, float64 and bfloat16. In float16, as in transformers,
+ ``finfo(float16).min`` plus a score rounds to a multiple of 32, so those weights are only roughly
+ uniform, and a head whose scores are all below about -16 gives a non-finite output.
Returns:
- Tensor with shape :math:`(B, 1, D)` containing the pooled visual
+ Tensor with shape :math:`(B, D)` containing the pooled visual
representation after attention, layer normalization, and MLP
refinement.
"""
@@ -193,8 +205,22 @@ class SigLip2MultiheadAttentionPoolingHead(nn.Module):
batch_size = hidden_state.shape[0]
probe = self.probe.repeat(batch_size, 1, 1) # (batch_size, 1, hidden_size)
+ key_padding_mask = None
+ if attention_mask is not None:
+ keep = attention_mask.bool()
+ if keep.dim() > 2:
+ # (B, N, N) or (B, 1, N, N) -> (B, N): a key no query may attend to is padding
+ keep = keep.flatten(1, -2).any(1)
+ # An additive mask with the dtype's finite minimum on the padding keys, as transformers'
+ # _prepare_4d_attention_mask builds it: a partly padded sample pools as with -inf (exp underflows to 0),
+ # and an all-padding sample gets uniform weights (exactly so in float32, float64 and bfloat16; float16
+ # rounds min + score, see the docstring) instead of the nan of a softmax over -inf only.
+ key_padding_mask = torch.zeros(keep.shape, dtype=hidden_state.dtype, device=hidden_state.device)
+ key_padding_mask = key_padding_mask.masked_fill(~keep, torch.finfo(hidden_state.dtype).min)
+ key_padding_mask = key_padding_mask.expand(batch_size, -1)
+
# multi-head attention: probe as query, hidden_state as key/value
- hidden_state, _ = self.attention(probe, hidden_state, hidden_state)
+ hidden_state, _ = self.attention(probe, hidden_state, hidden_state, key_padding_mask=key_padding_mask)
# residual connection with layer norm and MLP
residual = hidden_state
@@ -275,12 +301,15 @@ class SigLip2VisionModel(nn.Module):
Args:
pixel_values: Input images of shape (batch_size, num_channels, height, width).
- attention_mask: Optional attention mask.
+ attention_mask: Optional mask of the patches, ``1``/``True`` for a patch to keep and ``0``/``False`` for
+ a padded one: :math:`(B, N)`, :math:`(B, N, N)` or :math:`(B, 1, N, N)` for :math:`N` patches (see
+ :class:`SigLip2Attention`). It excludes the padded patches from the encoder, where no patch attends
+ to them, and from the pooling.
output_hidden_states: Whether to return hidden states from all layers.
Returns:
Tuple containing:
- - Pooled output (mean pooled)
+ - Pooled output, attention-pooled by the probe head (:class:`SigLip2MultiheadAttentionPoolingHead`)
- Last hidden state
- All hidden states (if output_hidden_states=True)
"""
@@ -300,7 +329,7 @@ class SigLip2VisionModel(nn.Module):
last_hidden_state = self.post_layernorm(last_hidden_state)
# pool: multi-head attention pooling - [batch_size, hidden_size]
- pooled_output = self.head(last_hidden_state)
+ pooled_output = self.head(last_hidden_state, attention_mask=attention_mask)
if output_hidden_states:
return (pooled_output, last_hidden_state, encoder_outputs[1])
diff --git a/tests/models/test_kimi_vl.py b/tests/models/test_kimi_vl.py
index 711a46bf1..e5c23fa39 100644
--- a/tests/models/test_kimi_vl.py
+++ b/tests/models/test_kimi_vl.py
@@ -170,6 +170,32 @@ class TestKimiVLModel(BaseTester):
output = model(images, attention_mask=mask)
assert output.shape == (batch_size, 16, config.projector_config.output_dim)
+ @pytest.mark.parametrize("batch_size", [2, 4])
+ def test_three_dim_mask_is_per_sample(self, device, dtype, model, config, batch_size):
+ # A (B, N, N) mask holds one N x N mask per sample, shared by the heads: sample b of a batch equals its own
+ # batch-of-one run. The fixture has 4 heads: a mask read per head does not broadcast against B = 2, and with
+ # B = 4, the head count, it broadcasts silently to wrong outputs.
+ model = model.eval()
+ n = 64 # 32 px at patch 4: an 8 x 8 grid
+ images = torch.randn(batch_size, 3, 32, 32, device=device, dtype=dtype)
+ mask = torch.ones(batch_size, n, n, dtype=torch.bool, device=device)
+ mask[1, :, n // 2 :] = False # sample 1 attends to the first half of the keys only
+ if batch_size == 4:
+ mask[2, :, 1::2] = False # sample 2: the even keys
+ mask[3, :, : n // 4] = False # sample 3: all but the first quarter
+
+ with torch.no_grad():
+ output = model(images, attention_mask=mask)
+ for b in range(batch_size):
+ self.assert_close(output[b], model(images[b : b + 1], attention_mask=mask[b : b + 1])[0])
+ self.assert_close(model(images, attention_mask=mask[:, None]), output)
+ batch_of_three = model(
+ torch.randn(3, 3, 32, 32, device=device, dtype=dtype),
+ attention_mask=torch.ones(3, n, n, dtype=torch.bool, device=device),
+ )
+
+ assert batch_of_three.shape == (3, 16, config.projector_config.output_dim)
+
def test_exception(self, device, dtype, model):
# Test invalid input shape (missing batch dim)
images = torch.randn(3, 32, 32, device=device, dtype=dtype)
@@ -197,6 +223,24 @@ class TestKimiVLModel(BaseTester):
self.assert_close(actual, expected)
+ def test_dynamo_fullgraph_three_dim_mask(self, device, dtype, torch_optimizer, config):
+ model = MoonViT(config.vision_config).to(device, dtype).eval()
+ n = 64
+ images = torch.randn(2, 3, 32, 32, device=device, dtype=dtype)
+ mask = torch.ones(2, n, n, dtype=torch.bool, device=device)
+ mask[1, :, n // 2 :] = False
+
+ model_optimized = torch_optimizer(model, fullgraph=True)
+
+ with torch.no_grad():
+ expected = model(images, attention_mask=mask)
+ actual = model_optimized(images, attention_mask=mask)
+
+ # Inductor keeps fused half-precision intermediates in float32, so a few outputs differ from eager by one
+ # unit in the last place. On the base revision a60a6c932, where a (B, N, N) mask raised, the (B, 1, N, N) form
+ # fails the default half tolerance the same way (7 / 4096 outputs in float16, 12 / 4096 in bfloat16).
+ self.assert_close(actual, expected, low_tolerance=dtype in (torch.float16, torch.bfloat16))
+
class TestKimiVLComponents(BaseTester):
def test_apply_rotary_pos_emb_preserves_float64_precision(self, device):
diff --git a/tests/models/test_naflex.py b/tests/models/test_naflex.py
index 8ccd78d30..307995cbd 100644
--- a/tests/models/test_naflex.py
+++ b/tests/models/test_naflex.py
@@ -14,14 +14,47 @@
# See the License for the specific language governing permissions and
# limitations under the License.
#
+import io
+import math
+import warnings
+
import pytest
import torch
+import torch.nn.functional as F
from torch import Tensor
+from kornia.core._compat import torch_version_lt
+from kornia.core.exceptions import BaseError
from kornia.models.processors.naflex import NaFlex
from testing.base import BaseTester
+_CHANNELS = 8
+
+
+def _zero_patches(x: Tensor) -> Tensor:
+ """A patch embedding of patch size 16 that returns zeros, so ``NaFlex``'s output is the position table it adds."""
+ batch_size, _, height, width = x.shape
+ return x.new_zeros(batch_size, _CHANNELS, height // 16, width // 16)
+
+
+def _zero_tokens(x: Tensor) -> Tensor:
+ """The same zeros as a ``(B, N, C)`` token sequence in raster order."""
+ return _zero_patches(x).flatten(2).transpose(1, 2)
+
+
+def _reference_positions(table: Tensor, height: int, width: int) -> Tensor:
+ """The position table resized to a ``height x width`` grid, as transformers resizes it.
+
+ ``Siglip2VisionEmbeddings.resize_positional_embeddings`` (transformers v4.51.0, modeling_siglip2.py): the
+ ``(side, side, C)`` table as ``(1, C, side, side)``, ``F.interpolate(mode="bilinear", align_corners=False,
+ antialias=True)`` in float32 on the CPU, cast back to the table's dtype; returned as ``(height * width, C)``.
+ """
+ side = math.isqrt(table.shape[0])
+ grid = table.reshape(side, side, -1).permute(2, 0, 1).unsqueeze(0).to("cpu", torch.float32)
+ resized = F.interpolate(grid, size=(height, width), mode="bilinear", align_corners=False, antialias=True)
+ return resized.reshape(-1, height * width).transpose(0, 1).to(table.device, table.dtype)
+
class TestNaFlex(BaseTester):
@pytest.fixture
@@ -96,3 +129,238 @@ class TestNaFlex(BaseTester):
input_448 = torch.randn(1, 3, 448, 448, device=device, dtype=dtype)
out = model(input_448)
assert out.shape == (1, 784, 768)
+
+ def test_non_square_grid_with_matching_count(self, device: torch.device, dtype: torch.dtype) -> None:
+ # 128 x 512 at patch 16 is an 8 x 32 grid: 256 patches, as many as the 16 x 16 table has rows, but laid out
+ # differently, so the table is resized to 8 x 32 rather than added in raster order.
+ table = torch.randn(256, _CHANNELS, device=device, dtype=dtype)
+ out = NaFlex(_zero_patches, table)(torch.zeros(3, 3, 128, 512, device=device, dtype=dtype))
+ self.assert_close(out, _reference_positions(table, 8, 32).expand(3, -1, -1))
+
+ @pytest.mark.parametrize(("height", "width"), [(128, 512), (192, 336), (40, 63), (230, 230)])
+ def test_bnc_patch_output_with_patch_size(
+ self, device: torch.device, dtype: torch.dtype, height: int, width: int
+ ) -> None:
+ # A (B, N, C) patch output carries no grid; patch_size=16 gives (H // 16, W // 16): 8 x 32 for 128 x 512 (the
+ # 256 tokens a square reading takes for 16 x 16), 12 x 21 for 192 x 336, and 2 x 3 and 14 x 14 for sides that
+ # are not multiples of 16 (the conv drops the remainder). The same as the (B, C, h, w) output and the reference.
+ table = torch.randn(256, _CHANNELS, device=device, dtype=dtype)
+ images = torch.zeros(3, 3, height, width, device=device, dtype=dtype)
+ out = NaFlex(_zero_tokens, table, patch_size=16)(images)
+ self.assert_close(out, NaFlex(_zero_patches, table)(images))
+ self.assert_close(out, _reference_positions(table, height // 16, width // 16).expand(3, -1, -1))
+
+ def test_bnc_patch_output_with_a_rectangular_patch_size(self, device: torch.device, dtype: torch.dtype) -> None:
+ # (16, 32) patches of a 256 x 512 image: a 16 x 16 grid (read with the axes swapped it would be 8 x 32, which
+ # has as many cells), equal to the conv's (B, C, h, w) output with the table added as is.
+ conv = torch.nn.Conv2d(3, _CHANNELS, (16, 32), stride=(16, 32)).to(device, dtype)
+ table = torch.randn(256, _CHANNELS, device=device, dtype=dtype)
+ images = torch.rand(2, 3, 256, 512, device=device, dtype=dtype)
+ with torch.no_grad():
+ tokens = conv(images).flatten(2).transpose(1, 2)
+ out = NaFlex(lambda x: conv(x).flatten(2).transpose(1, 2), table, patch_size=(16, 32))(images)
+ self.assert_close(out, tokens + table)
+ self.assert_close(out, NaFlex(conv, table)(images))
+
+ def test_bnc_patch_size_whose_grid_does_not_match_raises(self, device: torch.device, dtype: torch.dtype) -> None:
+ # patch_size=16 gives a 64 x 64 image a 4 x 4 grid, 16 cells, but the patch embedding returns 7 tokens.
+ table = torch.randn(256, _CHANNELS, device=device, dtype=dtype)
+ naflex = NaFlex(lambda x: x.new_zeros(x.shape[0], 7, _CHANNELS), table, patch_size=16)
+ with pytest.raises(BaseError, match=r"4 x 4 grid of 16 patches, but the patch embedding returned 7"):
+ naflex(torch.zeros(3, 3, 64, 64, device=device, dtype=dtype))
+
+ @pytest.mark.parametrize(("height", "width", "num_tokens"), [(64, 64, 7), (192, 336, 252)])
+ def test_bnc_without_patch_size_needs_a_square_count(
+ self, device: torch.device, dtype: torch.dtype, height: int, width: int, num_tokens: int
+ ) -> None:
+ table = torch.randn(256, _CHANNELS, device=device, dtype=dtype)
+ naflex = NaFlex(lambda x: x.new_zeros(x.shape[0], num_tokens, _CHANNELS), table)
+ with pytest.raises(BaseError, match=f"{num_tokens} patch embeddings are not a square number. Pass patch_size"):
+ naflex(torch.zeros(3, 3, height, width, device=device, dtype=dtype))
+
+ @pytest.mark.parametrize(
+ ("height", "width", "kernel", "stride", "side"),
+ [
+ (20, 20, 3, 2, 9),
+ (19, 20, 3, 2, 9),
+ (20, 36, 3, (2, 4), 9),
+ (256, 512, (16, 32), (16, 32), 16),
+ (64, 144, (10, 24), (10, 24), 6),
+ ],
+ )
+ def test_bnc_without_patch_size_reads_a_square_grid(
+ self, device: torch.device, dtype: torch.dtype, height: int, width: int, kernel, stride, side: int
+ ) -> None:
+ # Without patch_size, a square number of tokens is read as the square grid: right for these convolutions,
+ # whose grids are side x side. A side x side table is added as is, a 4 x 4 one resized by plain bilinear
+ # interpolation (no axis shrinks).
+ conv = torch.nn.Conv2d(3, _CHANNELS, kernel, stride=stride).to(device, dtype)
+ images = torch.rand(2, 3, height, width, device=device, dtype=dtype)
+ with torch.no_grad():
+ tokens = conv(images).flatten(2).transpose(1, 2)
+ assert tokens.shape[1] == side * side
+ own = torch.randn(side * side, _CHANNELS, device=device, dtype=dtype)
+ self.assert_close(NaFlex(lambda x: conv(x).flatten(2).transpose(1, 2), own)(images), tokens + own)
+ small = torch.randn(16, _CHANNELS, device=device, dtype=dtype)
+ grid = small.reshape(4, 4, -1).permute(2, 0, 1).unsqueeze(0).to("cpu", torch.float32)
+ resized = F.interpolate(grid, size=(side, side), mode="bilinear", align_corners=False)
+ resized = resized.reshape(-1, side * side).transpose(0, 1).to(device, dtype)
+ out = NaFlex(lambda x: conv(x).flatten(2).transpose(1, 2), small)(images)
+ self.assert_close(out, tokens + resized)
+
+ @pytest.mark.parametrize(("height", "width"), [(192, 336), (256, 128)])
+ def test_downsampling_is_antialiased(
+ self, device: torch.device, dtype: torch.dtype, height: int, width: int
+ ) -> None:
+ # 12 x 21 downsamples the 16 x 16 table along the rows, 16 x 8 along the columns.
+ table = torch.randn(256, _CHANNELS, device=device, dtype=dtype)
+ out = NaFlex(_zero_patches, table)(torch.zeros(3, 3, height, width, device=device, dtype=dtype))
+ self.assert_close(out, _reference_positions(table, height // 16, width // 16).expand(3, -1, -1))
+
+ @pytest.mark.parametrize(("height", "width"), [(384, 512), (256, 320)])
+ def test_upsampling_matches_the_reference(
+ self, device: torch.device, dtype: torch.dtype, height: int, width: int
+ ) -> None:
+ # 24 x 32 upsamples both axes of the 16 x 16 table, 16 x 20 the columns only. NaFlex resizes without
+ # antialiasing here; transformers' antialias=True changes nothing when no axis shrinks (2.4e-6 apart in
+ # float32), so the antialiased reference still holds.
+ table = torch.randn(256, _CHANNELS, device=device, dtype=dtype)
+ out = NaFlex(_zero_patches, table)(torch.zeros(3, 3, height, width, device=device, dtype=dtype))
+ self.assert_close(out, _reference_positions(table, height // 16, width // 16).expand(3, -1, -1))
+
+ def test_non_square_table_with_matching_count_is_added_as_is(
+ self, device: torch.device, dtype: torch.dtype
+ ) -> None:
+ # A table that is not a square grid cannot be resized, but one with exactly as many rows as the grid has
+ # patches is added in raster order, as for a square table on its own grid.
+ table = torch.randn(280, _CHANNELS, device=device, dtype=dtype)
+ out = NaFlex(_zero_patches, table)(torch.zeros(3, 3, 224, 320, device=device, dtype=dtype))
+ self.assert_close(out, table.expand(3, -1, -1))
+ # The same for a (B, N, C) output, whose grid is then never read: the 6 tokens of a 48 x 47 image (a 3 x 2
+ # grid that the aspect reading would transpose) take a 6-row table as is.
+ table = torch.randn(6, _CHANNELS, device=device, dtype=dtype)
+ out = NaFlex(_zero_tokens, table)(torch.zeros(3, 3, 48, 47, device=device, dtype=dtype))
+ self.assert_close(out, table.expand(3, -1, -1))
+
+ @pytest.mark.device_agnostic
+ @pytest.mark.parametrize("half", [torch.float16, torch.bfloat16])
+ def test_half_on_cpu_interpolates_in_float32(self, half: torch.dtype) -> None:
+ # CPU has no float16/bfloat16 antialiased bilinear kernel ("compute_index_ranges_weights" not implemented:
+ # NotImplementedError on torch 2.14, RuntimeError on 2.5.1), so the table is resized in float32 and cast back.
+ table = torch.randn(256, _CHANNELS, dtype=half)
+ out = NaFlex(_zero_patches, table)(torch.zeros(3, 3, 192, 336, dtype=half))
+ assert out.dtype == half
+ self.assert_close(out, _reference_positions(table, 12, 21).expand(3, -1, -1), rtol=0.0, atol=0.0)
+
+ def test_parameter_stays_a_parameter(self, device: torch.device, dtype: torch.dtype) -> None:
+ table = torch.nn.Parameter(torch.randn(256, _CHANNELS, device=device, dtype=dtype))
+ naflex = NaFlex(_zero_patches, table)
+ assert [(name, param is table) for name, param in naflex.named_parameters()] == [("position_embedding", True)]
+ assert list(naflex.named_buffers()) == []
+ naflex(torch.zeros(3, 3, 192, 336, device=device, dtype=dtype)).sum().backward()
+ assert table.grad is not None
+ assert table.grad.abs().sum() > 0
+
+ plain = torch.randn(256, _CHANNELS, device=device, dtype=dtype)
+ buffered = NaFlex(_zero_patches, plain)
+ assert list(buffered.named_parameters()) == []
+ assert [(name, buffer is plain) for name, buffer in buffered.named_buffers()] == [("position_embedding", True)]
+
+ @pytest.mark.device_agnostic
+ def test_naflex_onnx_matches_eager(self, tmp_path) -> None:
+ pytest.importorskip("onnx")
+ ort = pytest.importorskip("onnxruntime")
+ pytest.importorskip("onnxscript")
+ # The legacy TorchScript exporter has no symbolic for aten::_upsample_bilinear2d_aa; the dynamo exporter
+ # exports the antialiased resize. 12 x 21 downsamples the 16 x 16 table, so the antialias path runs.
+ naflex = NaFlex(torch.nn.Conv2d(3, _CHANNELS, 16, 16), torch.randn(256, _CHANNELS)).eval()
+ images = torch.rand(3, 3, 192, 336)
+ path = tmp_path / "naflex.onnx"
+ torch.onnx.export(naflex, (images,), str(path), dynamo=True, opset_version=18, input_names=["images"])
+ session = ort.InferenceSession(str(path), providers=["CPUExecutionProvider"])
+ actual = torch.from_numpy(session.run(None, {"images": images.numpy()})[0])
+ with torch.no_grad():
+ expected = naflex(images)
+ self.assert_close(actual, expected, rtol=0.0, atol=1e-5)
+
+ @pytest.mark.device_agnostic
+ @pytest.mark.parametrize(("height", "width"), [(384, 512), (256, 320)])
+ def test_naflex_legacy_onnx_export_of_an_upsampled_table(self, height: int, width: int) -> None:
+ pytest.importorskip("onnx")
+ ort = pytest.importorskip("onnxruntime")
+ # A 24 x 32 grid upsamples the 16 x 16 table on both axes and a 16 x 20 grid keeps the rows and upsamples the
+ # columns: the plain bilinear resize, which the legacy TorchScript exporter supports (it has no symbolic for
+ # the antialiased aten::_upsample_bilinear2d_aa).
+ naflex = NaFlex(torch.nn.Conv2d(3, _CHANNELS, 16, 16), torch.randn(256, _CHANNELS)).eval()
+ images = torch.rand(3, 3, height, width)
+ buffer = io.BytesIO()
+ with warnings.catch_warnings():
+ warnings.simplefilter("ignore")
+ torch.onnx.export(
+ naflex,
+ (images,),
+ buffer, # ty: ignore[invalid-argument-type] # The legacy exporter accepts BytesIO.
+ input_names=["images"],
+ opset_version=17,
+ dynamo=False,
+ )
+ session = ort.InferenceSession(buffer.getvalue(), providers=["CPUExecutionProvider"])
+ actual = torch.from_numpy(session.run(None, {"images": images.numpy()})[0])
+ with torch.no_grad():
+ expected = naflex(images)
+ self.assert_close(actual, expected, rtol=0.0, atol=1e-5)
+
+ @pytest.mark.device_agnostic
+ def test_naflex_onnx_dynamic_size_exported_from_a_smaller_grid(self) -> None:
+ pytest.importorskip("onnx")
+ ort = pytest.importorskip("onnxruntime")
+ pytest.importorskip("onnxscript")
+ if torch_version_lt(2, 14, 0):
+ # torch.export reports NaFlex's grid-size comparison as a constraint violation of the dynamic H and W;
+ # torch.onnx.export of torch 2.14 exports anyway, and that of torch 2.5.1 raises TorchExportError.
+ pytest.skip("checked on torch 2.14: the dynamo exporter of torch 2.5.1 refuses this dynamic export")
+ # The documented recipe: export with dynamic H and W from an image whose 8 x 8 grid is smaller than the
+ # 16 x 16 table along both axes, so the graph resizes with antialiasing at every size. That is right for a
+ # smaller grid (4 x 6) and, since antialiasing changes nothing when upsampling, for a larger one (24 x 32).
+ naflex = NaFlex(torch.nn.Conv2d(3, _CHANNELS, 16, 16), torch.randn(256, _CHANNELS)).eval()
+ size = {2: torch.export.Dim("height", min=16, max=1024), 3: torch.export.Dim("width", min=16, max=1024)}
+ with warnings.catch_warnings():
+ warnings.simplefilter("ignore")
+ program = torch.onnx.export(
+ naflex, (torch.rand(2, 3, 128, 128),), dynamo=True, opset_version=18, dynamic_shapes=(size,)
+ )
+ session = ort.InferenceSession(program.model_proto.SerializeToString(), providers=["CPUExecutionProvider"])
+ for height, width in ((64, 96), (384, 512)):
+ images = torch.rand(2, 3, height, width)
+ actual = torch.from_numpy(session.run(None, {session.get_inputs()[0].name: images.numpy()})[0])
+ with torch.no_grad():
+ expected = naflex(images)
+ self.assert_close(actual, expected, rtol=0.0, atol=1e-5)
+
+ @pytest.mark.device_agnostic
+ def test_float64_table_is_resized_in_float64(self) -> None:
+ # transformers resizes every CPU table in float32; a float64 table keeps float64 here, so it matches the
+ # float64 resize to rounding (a float32 resize is about 1e-7 off). 12 x 21 shrinks the rows (antialiased),
+ # 24 x 32 shrinks no axis (plain bilinear).
+ table = torch.randn(256, _CHANNELS, dtype=torch.float64)
+ grid = table.reshape(16, 16, -1).permute(2, 0, 1).unsqueeze(0)
+ for (height, width), antialias in (((192, 336), True), ((384, 512), False)):
+ h, w = height // 16, width // 16
+ out = NaFlex(_zero_patches, table)(torch.zeros(3, 3, height, width, dtype=torch.float64))
+ resized = F.interpolate(grid, size=(h, w), mode="bilinear", align_corners=False, antialias=antialias)
+ expected = resized.reshape(-1, h * w).transpose(0, 1).expand(3, -1, -1)
+ self.assert_close(out, expected, rtol=0.0, atol=1e-12)
+
+ # 192 x 336: a 12 x 21 grid, antialiased (rows shrink); 384 x 512: 24 x 32, plain bilinear.
+ @pytest.mark.parametrize(("height", "width"), [(192, 336), (384, 512)])
+ def test_dynamo_fullgraph_naflex(
+ self, device: torch.device, dtype: torch.dtype, torch_optimizer, height: int, width: int
+ ) -> None:
+ conv = torch.nn.Conv2d(3, _CHANNELS, 16, 16).to(device, dtype)
+ naflex = NaFlex(conv, torch.randn(256, _CHANNELS, device=device, dtype=dtype)).eval()
+ images = torch.rand(3, 3, height, width, device=device, dtype=dtype)
+
+ naflex_optimized = torch_optimizer(naflex, fullgraph=True)
+
+ with torch.no_grad():
+ self.assert_close(naflex_optimized(images), naflex(images))
diff --git a/tests/models/test_paligemma.py b/tests/models/test_paligemma.py
index d714a3eed..371800f74 100644
--- a/tests/models/test_paligemma.py
+++ b/tests/models/test_paligemma.py
@@ -19,7 +19,7 @@ import pytest
import torch
from kornia.models.paligemma import PaliGemma, PaliGemmaConfig
-from kornia.models.paligemma.modeling_paligemma import GemmaAttention, GemmaMLP
+from kornia.models.paligemma.modeling_paligemma import GemmaAttention, GemmaMLP, GemmaRMSNorm
class TestPaliGemmaModules:
@@ -60,3 +60,68 @@ class TestPaliGemmaModules:
logits = model(input_ids=input_ids, pixel_values=pixel_values)
assert logits.shape == (1, 9, config.vocab_size)
+
+ @pytest.mark.parametrize("dtype", [torch.float32, torch.float16, torch.bfloat16])
+ def test_text_embeddings_are_scaled(self, config, dtype):
+ # Gemma multiplies the input embeddings by sqrt(hidden_size), as a tensor in their dtype (GemmaModel.forward's
+ # normalizer, modeling_gemma.py v4.51.0), and PaliGemma divides the projected image features by the same
+ # factor first (PaliGemmaForConditionalGeneration.get_image_features): text enters scaled, the image unscaled.
+ # In float16 and bfloat16 the factor rounded to the dtype gives other products than the Python float.
+ model = PaliGemma(config).to(dtype).eval()
+ captured = {}
+ model.layers[0].register_forward_pre_hook(
+ lambda module, args, kwargs: captured.__setitem__("decoder_input", args[0]), with_kwargs=True
+ )
+ pixel_values = torch.randn(2, 3, 32, 32, dtype=dtype)
+ input_ids = torch.randint(1, config.vocab_size, (2, 5))
+
+ with torch.no_grad():
+ model(input_ids=input_ids, pixel_values=pixel_values)
+ image = model.multi_modal_projector(model.vision_tower(pixel_values)[1])
+ text = model.embed_tokens(input_ids) * torch.tensor(32**0.5, dtype=dtype) # hidden_size 32
+
+ decoder_input = captured["decoder_input"]
+ assert image.shape[1] == 4 # 32 px at patch 16: 2 x 2 image tokens, before the text
+ torch.testing.assert_close(decoder_input[:, :4], image, rtol=0.0, atol=0.0)
+ torch.testing.assert_close(decoder_input[:, 4:], text, rtol=0.0, atol=0.0)
+
+ def test_padding_idx_is_pad_token_id(self, config):
+ # Gemma's pad_token_id is 0 (configuration_gemma.py v4.51.0). padding_idx = ignore_index = -100 wrapped to
+ # vocab_size - 100: row 200 of a 300-token vocabulary, a real token, zeroed and frozen. (The fixture's 100
+ # tokens would wrap -100 to row 0 and hide the difference.)
+ config.vocab_size = 300
+ model = PaliGemma(config).train()
+ embedding = model.embed_tokens
+
+ assert embedding.padding_idx == 0
+ assert torch.all(embedding.weight[0] == 0)
+ assert not torch.all(embedding.weight[200] == 0)
+ model(input_ids=torch.tensor([[0, 5, 200, 7]]), pixel_values=torch.randn(1, 3, 32, 32)).sum().backward()
+ assert embedding.weight.grad[200].abs().sum() > 0
+ assert torch.all(embedding.weight.grad[0] == 0)
+ # The default config, without building its 257152 x 2048 embedding.
+ assert PaliGemmaConfig().pad_token_id == 0
+
+ def test_mlp_uses_tanh_gelu(self, config):
+ # Gemma's hidden_act is "gelu_pytorch_tanh" (configuration_gemma.py v4.51.0).
+ activation = GemmaMLP(config).act_fn
+ assert isinstance(activation, torch.nn.GELU)
+ assert activation.approximate == "tanh"
+
+ def test_rms_norm_multiplies_in_float32(self):
+ # Gemma's RMSNorm multiplies by (1 + weight) in float32 and casts afterwards, "(x * w).to(float16)"
+ # (GemmaRMSNorm.forward, modeling_gemma.py v4.51.0). The weight starts at zeros, where 1 + w == 1 hides the
+ # order, so it is filled with random values first.
+ generator = torch.Generator().manual_seed(0)
+ norm = GemmaRMSNorm(64)
+ with torch.no_grad():
+ norm.weight.copy_(torch.randn(64, generator=generator))
+ norm = norm.half()
+ x = torch.randn(2, 5, 64, generator=generator).half()
+
+ out = norm(x)
+
+ x32 = x.float()
+ normalized = x32 * torch.rsqrt(x32.pow(2).mean(-1, keepdim=True) + 1e-6)
+ assert out.dtype == torch.float16
+ assert torch.equal(out, (normalized * (1.0 + norm.weight.float())).half())
diff --git a/tests/models/test_siglip2.py b/tests/models/test_siglip2.py
index 46aa25dee..261b91b46 100644
--- a/tests/models/test_siglip2.py
+++ b/tests/models/test_siglip2.py
@@ -17,21 +17,29 @@
"""Tests for SigLip2 model."""
+import math
from dataclasses import replace
from unittest.mock import patch
import pytest
import torch
+import kornia
import kornia.models.siglip2.builder as siglip2_builder
+from kornia.core.exceptions import BaseError
from kornia.models.siglip2 import SigLip2Builder, SigLip2Config, SigLip2Model, SigLip2Result
from kornia.models.siglip2.attention import SigLip2Attention
from kornia.models.siglip2.config import SigLip2TextConfig, SigLip2VisionConfig
from kornia.models.siglip2.preprocessor import SigLip2ImagePreprocessor
from kornia.models.siglip2.text_encoder import SigLip2TextEmbeddings, SigLip2TextEncoder, SigLip2TextModel
-from kornia.models.siglip2.vision_encoder import SigLip2VisionEmbeddings, SigLip2VisionEncoder, SigLip2VisionModel
+from kornia.models.siglip2.vision_encoder import (
+ SigLip2MultiheadAttentionPoolingHead,
+ SigLip2VisionEmbeddings,
+ SigLip2VisionEncoder,
+ SigLip2VisionModel,
+)
-from testing.base import BaseTester
+from testing.base import BaseTester, supports_reflect_padding
@pytest.fixture
@@ -69,6 +77,42 @@ def _create_input_ids(batch_size, seq_len, config, device):
return torch.randint(0, min(100, config.text_config.vocab_size), (batch_size, seq_len), device=device)
+def _tiny_vision_config():
+ """32 px images at patch 4: an 8 x 8 grid of 64 patches."""
+ return SigLip2VisionConfig(
+ image_size=32,
+ patch_size=4,
+ hidden_size=32,
+ num_hidden_layers=2,
+ num_attention_heads=4,
+ intermediate_size=64,
+ )
+
+
+def _patch_rows_4_to_7_masked(device):
+ """A ``(1, 64)`` mask of the 8 x 8 grid that drops patches 32..63, i.e. patch rows 4..7 (pixel rows 16..31)."""
+ mask = torch.ones(1, 64, dtype=torch.bool, device=device)
+ mask[:, 32:] = False
+ return mask
+
+
+# (vocab_size, hidden_size, intermediate_size, num_hidden_layers, num_attention_heads, image_size) of each supported
+# checkpoint: its hub config.json (read 2026-10-16), with the defaults of transformers v4.51.0 SiglipTextConfig and
+# SiglipVisionConfig (configuration_siglip.py: vocab 32000, hidden 768, intermediate 3072, 12 layers, 12 heads, image
+# 224, patch 16, text max_position_embeddings 64) for the fields it omits. No config.json sets a patch size or
+# max_position_embeddings, so every name has patch 16 and 64 text positions.
+_HUB_CONFIGS = {
+ "google/siglip-base-patch16-224": (32000, 768, 3072, 12, 12, 224),
+ "google/siglip2-base-patch16-224": (256000, 768, 3072, 12, 12, 224),
+ "google/siglip2-base-patch16-256": (256000, 768, 3072, 12, 12, 256),
+ "google/siglip2-base-patch16-384": (256000, 768, 3072, 12, 12, 384),
+ "google/siglip2-base-patch16-512": (256000, 768, 3072, 12, 12, 512),
+ "google/siglip2-large-patch16-256": (256000, 1024, 4096, 24, 16, 256),
+ "google/siglip2-large-patch16-384": (256000, 1024, 4096, 24, 16, 384),
+ "google/siglip2-large-patch16-512": (256000, 1024, 4096, 24, 16, 512),
+}
+
+
class TestSigLip2Builder:
"""The download path: kornia's own downloader and safetensors reader, no optional package."""
@@ -124,6 +168,104 @@ class TestSigLip2Builder:
):
siglip2_builder._download_weights("google/nope", None)
+ @pytest.mark.parametrize("model_name", sorted(_HUB_CONFIGS))
+ def test_from_name_table(self, model_name):
+ # Config only: building the model would allocate the full random network (about 375M parameters for base).
+ vocab_size, hidden_size, intermediate_size, num_layers, num_heads, image_size = _HUB_CONFIGS[model_name]
+ config = SigLip2Config.from_name(model_name)
+
+ for sub_config in (config.vision_config, config.text_config):
+ assert sub_config.hidden_size == hidden_size
+ assert sub_config.intermediate_size == intermediate_size
+ assert sub_config.num_hidden_layers == num_layers
+ assert sub_config.num_attention_heads == num_heads
+ assert config.vision_config.patch_size == 16
+ assert config.vision_config.image_size == image_size
+ assert config.text_config.vocab_size == vocab_size
+ assert config.text_config.max_position_embeddings == 64
+ assert config.projection_dim == hidden_size
+
+ @pytest.mark.parametrize(
+ ("model_name", "expected"),
+ [
+ # (vocab_size, hidden_size, num_hidden_layers, num_attention_heads, image_size, patch_size, text positions)
+ ("someone/siglip2-base-patch16-224-finetuned", (256000, 768, 12, 12, 224, 16, 512)),
+ ("someone/siglip2-large-patch16-384-mirror", (256000, 1024, 24, 16, 384, 16, 512)),
+ ("someone/my-siglip", (256000, 768, 12, 12, 224, 16, 512)),
+ # an image size counts only as a whole number, of the repository part after the last "/" first
+ ("org2560/siglip2-base-patch16-384", (256000, 768, 12, 12, 384, 16, 512)),
+ ("org-256/siglip2-base-patch16-384", (256000, 768, 12, 12, 384, 16, 512)),
+ ("x/siglip2-base-patch16-ckpt2560", (256000, 768, 12, 12, 224, 16, 512)),
+ ("x/siglip2-base-patch16-224-ckpt2560", (256000, 768, 12, 12, 224, 16, 512)),
+ # the owner part counts when the repository part has no size
+ ("siglip384/finetune", (256000, 768, 12, 12, 384, 16, 512)),
+ ],
+ )
+ def test_from_name_reads_an_unlisted_name_from_its_parts(self, model_name, expected):
+ # A fine-tune or mirror of a supported checkpoint under another name: base unless the name says "large", the
+ # image size the name contains (224 if none), patch 16, the SigLIP 2 vocabulary, 512 text positions (which
+ # from_pretrained_hf adapts to the checkpoint). Config only: no model is built.
+ config = SigLip2Config.from_name(model_name)
+ vision, text = config.vision_config, config.text_config
+ actual = (
+ text.vocab_size,
+ vision.hidden_size,
+ vision.num_hidden_layers,
+ vision.num_attention_heads,
+ vision.image_size,
+ vision.patch_size,
+ text.max_position_embeddings,
+ )
+ assert actual == expected
+ assert (text.hidden_size, text.num_hidden_layers, text.num_attention_heads) == expected[1:4]
+
+ def test_from_pretrained_hf_loads_an_unlisted_name_that_fits(self, monkeypatch, config):
+ # The tiny config stands in for the configuration read from the name, and its own weights for a fine-tune's.
+ monkeypatch.setattr(SigLip2Config, "from_name", staticmethod(lambda model_name: config))
+ state_dict = SigLip2Model(config).state_dict()
+ monkeypatch.setattr(siglip2_builder, "_download_weights", lambda model_name, cache_dir: state_dict)
+
+ model = SigLip2Builder.from_pretrained_hf("someone/siglip2-base-patch16-224-finetuned")
+
+ assert {m.training for m in model.modules()} == {False}
+ for name, tensor in model.state_dict().items():
+ assert torch.equal(tensor, state_dict[name])
+
+ def test_from_pretrained_hf_names_the_supported_list_when_an_unlisted_checkpoint_does_not_fit(
+ self, monkeypatch, config
+ ):
+ # Weights of a wider model (hidden size 48 instead of 32) stand in for a large checkpoint under a name that
+ # reads as base: load_state_dict's shape mismatch becomes an error naming the supported checkpoints.
+ monkeypatch.setattr(SigLip2Config, "from_name", staticmethod(lambda model_name: config))
+ wider = SigLip2Config(
+ vision_config=replace(config.vision_config, hidden_size=48),
+ text_config=replace(config.text_config, hidden_size=48),
+ projection_dim=config.projection_dim,
+ )
+ state_dict = SigLip2Model(wider).state_dict()
+ monkeypatch.setattr(siglip2_builder, "_download_weights", lambda model_name, cache_dir: state_dict)
+
+ with pytest.raises(RuntimeError, match=r"Supported names: google/siglip-base-patch16-224, ") as error:
+ SigLip2Builder.from_pretrained_hf("someone/my-siglip")
+ assert "base (hidden size 768, 12 layers, 12 heads)" in str(error.value)
+ assert "size mismatch" in str(error.value.__cause__)
+
+ def test_from_pretrained_hf_passes_on_a_listed_checkpoints_load_error(self, monkeypatch, config):
+ # A listed name's checkpoint that does not fit is not a naming question: load_state_dict's own error surfaces.
+ monkeypatch.setattr(SigLip2Config, "from_name", staticmethod(lambda model_name: config))
+ wider = SigLip2Config(
+ vision_config=replace(config.vision_config, hidden_size=48),
+ text_config=replace(config.text_config, hidden_size=48),
+ projection_dim=config.projection_dim,
+ )
+ state_dict = SigLip2Model(wider).state_dict()
+ monkeypatch.setattr(siglip2_builder, "_download_weights", lambda model_name, cache_dir: state_dict)
+
+ with pytest.raises(RuntimeError, match="size mismatch") as error:
+ SigLip2Builder.from_pretrained_hf("google/siglip2-base-patch16-224")
+ assert "outside that list" not in str(error.value)
+ assert error.value.__cause__ is None
+
class TestSigLip2Model(BaseTester):
"""Test suite for SigLip2 model."""
@@ -277,6 +419,52 @@ class TestSigLip2Model(BaseTester):
output_min = model(pixel_values=pixel_values, input_ids=input_ids)
assert output_min.logit_scale.item() >= 1.0, f"Min clamp failed: {output_min.logit_scale.item()} < 1.0"
+ def test_return_loss_is_the_pairwise_sigmoid_loss(self, device, dtype, model, config, monkeypatch):
+ batch_size = 2
+ image_size = config.vision_config.image_size
+ pixel_values = torch.randn(batch_size, 3, image_size, image_size, device=device, dtype=dtype)
+ input_ids = _create_input_ids(batch_size, 10, config, device)
+
+ # transformers' SiglipModel loss (modeling_siglip.py v4.51.0, SiglipModel.forward, after big_vision's
+ # siglip.py): every pair enters, the diagonal labelled +1 and the rest -1,
+ # -logsigmoid((2 I - 1) * logits_per_text).sum(-1).mean().
+ with torch.no_grad():
+ random_init = model(pixel_values=pixel_values, input_ids=input_ids, return_loss=True)
+
+ # A literal: the unit vectors e1 and e2 as both embeddings, logit scale 10 and bias 5, give logits 15 on the
+ # diagonal and 5 off it. Each row's loss is log1p(exp(-15)) + log1p(exp(5)) = 5.0067156543913915 (by hand, in
+ # float64); a loss of the diagonal alone is log1p(exp(-15)) = 3.1e-07.
+ unit_vectors = torch.eye(batch_size, config.projection_dim, device=device, dtype=dtype)
+ monkeypatch.setattr(model, "get_image_features", lambda *args, **kwargs: unit_vectors)
+ monkeypatch.setattr(model, "get_text_features", lambda *args, **kwargs: unit_vectors)
+ with torch.no_grad():
+ model.logit_scale.fill_(math.log(10.0))
+ model.logit_bias.fill_(5.0)
+ output = model(pixel_values=pixel_values, input_ids=input_ids, return_loss=True)
+ self.assert_close(output.loss, torch.tensor(5.0067156543913915, device=device, dtype=dtype))
+
+ # The same formula on the model's own logits at random init.
+ labels = 2 * torch.eye(batch_size, device=device, dtype=dtype) - 1
+ expected = -torch.nn.functional.logsigmoid(labels * random_init.logits_per_text).sum(-1).mean()
+ self.assert_close(random_init.loss, expected)
+
+ def test_return_loss_needs_as_many_images_as_texts(self, device, dtype, model, config):
+ # The loss labels pair i with pair i; a 1 x 1 identity would broadcast +1 to every pair of unequal batches.
+ image_size = config.vision_config.image_size
+ pixel_values = torch.randn(3, 3, image_size, image_size, device=device, dtype=dtype)
+ input_ids = _create_input_ids(1, 10, config, device)
+
+ with torch.no_grad():
+ for images, texts in ((pixel_values, input_ids), (pixel_values[:1], input_ids.expand(3, -1))):
+ with pytest.raises(BaseError, match="as many images as texts"):
+ model(pixel_values=images, input_ids=texts, return_loss=True)
+ # Without the loss, unequal batches give rectangular logits.
+ output = model(pixel_values=pixel_values, input_ids=input_ids)
+
+ assert output.logits_per_image.shape == (3, 1)
+ assert output.logits_per_text.shape == (1, 3)
+ assert output.loss is None
+
def test_gradcheck(self, device, dtype, config):
"""Test gradient computation correctness."""
# Convert model to float64 for gradcheck
@@ -313,6 +501,25 @@ class TestSigLip2Model(BaseTester):
self.assert_close(actual.image_embeds, expected.image_embeds)
self.assert_close(actual.text_embeds, expected.text_embeds)
+ def test_dynamo_fullgraph_masked_vision_model(self, device, dtype, torch_optimizer):
+ """The vision attention mask reaches the encoder and the pooling head inside one compiled graph."""
+ model = SigLip2VisionModel(_tiny_vision_config()).to(device, dtype).eval()
+ pixel_values = torch.randn(1, 3, 32, 32, device=device, dtype=dtype)
+ mask = _patch_rows_4_to_7_masked(device)
+
+ model_optimized = torch_optimizer(model, fullgraph=True)
+
+ with torch.no_grad():
+ expected = model(pixel_values, attention_mask=mask)
+ actual = model_optimized(pixel_values, attention_mask=mask)
+
+ # Inductor keeps fused half-precision intermediates in float32, so a few outputs differ from eager by one
+ # unit in the last place. The last hidden state of this masked model fails the default half tolerance the same
+ # way on the base revision a60a6c932, whose encoder code this change does not touch.
+ low_tolerance = dtype in (torch.float16, torch.bfloat16)
+ self.assert_close(actual[0], expected[0], low_tolerance=low_tolerance)
+ self.assert_close(actual[1], expected[1], low_tolerance=low_tolerance)
+
class TestSigLip2Components(BaseTester):
"""Test suite for SigLip2 individual components."""
@@ -492,3 +699,126 @@ class TestSigLip2Components(BaseTester):
with torch.no_grad():
output = preprocessor(image)
assert output.shape == (1, 3, image_size[0], image_size[1])
+
+ def test_pooling_head_ignores_masked_patches(self, device, dtype):
+ # transformers' Siglip2VisionTransformer passes the patch mask to its pooling head as well
+ # (Siglip2MultiheadAttentionPoolingHead.forward(hidden_state, attention_mask), modeling_siglip2.py v4.51.0), so
+ # the pixels of masked patches cannot reach the pooled embedding.
+ model = SigLip2VisionModel(_tiny_vision_config()).to(device, dtype).eval()
+ pixel_values = torch.randn(1, 3, 32, 32, device=device, dtype=dtype)
+ changed = pixel_values.clone()
+ changed[..., 16:, :] = torch.randn(1, 3, 16, 32, device=device, dtype=dtype)
+ mask = _patch_rows_4_to_7_masked(device)
+
+ with torch.no_grad():
+ pooled, _ = model(pixel_values, attention_mask=mask)
+ pooled_changed, _ = model(changed, attention_mask=mask)
+ # The same mask broadcast over the queries, as (B, N, N) and as (B, 1, N, N).
+ pooled_3d, _ = model(pixel_values, attention_mask=mask[:, None, :].expand(1, 64, 64))
+ pooled_4d, _ = model(pixel_values, attention_mask=mask[:, None, None, :].expand(1, 1, 64, 64))
+ # The usual 3-D padding mask, the outer product, also masks the padded queries: every key of a padded
+ # patch's row is masked, so a key counts as padding only when no query may attend to it.
+ pooled_outer, _ = model(pixel_values, attention_mask=mask[:, :, None] & mask[:, None, :])
+
+ self.assert_close(pooled_changed, pooled)
+ self.assert_close(pooled_3d, pooled)
+ self.assert_close(pooled_4d, pooled)
+ self.assert_close(pooled_outer, pooled)
+
+ def test_pooling_head_broadcasts_a_single_mask_over_the_batch(self, device, dtype):
+ config = _tiny_vision_config()
+ head = SigLip2MultiheadAttentionPoolingHead(config).to(device, dtype).eval()
+ hidden_state = torch.randn(3, 64, config.hidden_size, device=device, dtype=dtype)
+ mask = _patch_rows_4_to_7_masked(device) # (1, 64)
+
+ with torch.no_grad():
+ pooled = head(hidden_state, attention_mask=mask)
+ per_sample = torch.cat([head(hidden_state[b : b + 1], attention_mask=mask) for b in range(3)])
+
+ self.assert_close(pooled, per_sample)
+
+ def test_pooling_head_all_masked_sample_pools_uniformly(self, device, dtype):
+ # transformers' pooling head masks with _prepare_4d_attention_mask, which adds torch.finfo(dtype).min to the
+ # scores of masked keys (modeling_attn_mask_utils.py v4.51.0, AttentionMaskConverter._expand_mask): a sample
+ # with every key masked gets equal scores, so uniform weights, where -inf would give nan. In float16 that holds
+ # only while the scores stay within about +-16 of 0 (finfo.min + score rounds to a multiple of 32); this tiny
+ # random head's scores are far smaller.
+ config = _tiny_vision_config()
+ head = SigLip2MultiheadAttentionPoolingHead(config).to(device, dtype).eval()
+ hidden_state = torch.randn(2, 64, config.hidden_size, device=device, dtype=dtype)
+ mask = torch.ones(2, 64, dtype=torch.bool, device=device)
+ mask[0, 32:] = False # sample 0 partly masked
+ mask[1] = False # sample 1 entirely masked
+
+ with torch.no_grad():
+ pooled = head(hidden_state, attention_mask=mask)
+ pooled_alone = head(hidden_state[:1], attention_mask=mask[:1])
+ # Uniform weights: every head averages the value projections of all 64 tokens.
+ hidden_size = config.hidden_size
+ attention = head.attention
+ values = torch.nn.functional.linear(
+ hidden_state[1:], attention.in_proj_weight[2 * hidden_size :], attention.in_proj_bias[2 * hidden_size :]
+ )
+ attended = attention.out_proj(values.mean(1, keepdim=True))
+ uniform = (attended + head.mlp(head.layernorm(attended)))[:, 0]
+
+ assert torch.isfinite(pooled).all()
+ self.assert_close(pooled[1:], uniform)
+ self.assert_close(pooled[:1], pooled_alone)
+
+ def test_activation_follows_hidden_act(self):
+ # transformers' SiglipTextConfig and SiglipVisionConfig default hidden_act is "gelu_pytorch_tanh"
+ # (configuration_siglip.py v4.51.0), and no released config.json overrides it.
+ assert SigLip2VisionConfig().hidden_act == "gelu_pytorch_tanh"
+ assert SigLip2TextConfig().hidden_act == "gelu_pytorch_tanh"
+ vision_config = _tiny_vision_config()
+ text_config = SigLip2TextConfig(
+ vocab_size=100,
+ hidden_size=32,
+ num_hidden_layers=2,
+ num_attention_heads=4,
+ intermediate_size=64,
+ max_position_embeddings=32,
+ )
+
+ def approximations(hidden_act):
+ vision = SigLip2VisionModel(replace(vision_config, hidden_act=hidden_act))
+ text = SigLip2TextModel(replace(text_config, hidden_act=hidden_act))
+ # Every encoder MLP and the pooling head's MLP of the vision tower, then the text encoder MLPs.
+ mlps = [layer.mlp for layer in vision.encoder.layers] + [vision.head.mlp]
+ mlps += [layer.mlp for layer in text.encoder.layers]
+ return [mlp.activation.approximate for mlp in mlps]
+
+ assert approximations(vision_config.hidden_act) == ["tanh"] * 5
+ assert approximations("gelu_pytorch_tanh") == ["tanh"] * 5
+ assert approximations("gelu_new") == ["tanh"] * 5
+ assert approximations("gelu") == ["none"] * 5
+ with pytest.raises(ValueError, match="relu6"):
+ SigLip2VisionModel(replace(vision_config, hidden_act="relu6"))
+ with pytest.raises(ValueError, match="relu6"):
+ SigLip2TextModel(replace(text_config, hidden_act="relu6"))
+
+ def test_preprocessor_interpolation(self, device, dtype):
+ # The SigLIP 2 checkpoints' preprocessor_config.json says "resample": 2 (bilinear), the SigLIP 1
+ # google/siglip-base-patch16-224 says 3 (bicubic); both rescale by 1/255 and normalise with mean = std = 0.5.
+ if not supports_reflect_padding(device, dtype):
+ pytest.skip("the antialiased resize blurs with reflection_pad2d, unavailable for this device/dtype")
+ images = torch.randint(0, 255, (2, 3, 300, 400), device=device).to(dtype)
+
+ def expected(interpolation):
+ resized = kornia.geometry.resize(
+ images * (1.0 / 255.0), (224, 224), interpolation=interpolation, align_corners=False, antialias=True
+ )
+ return (resized - 0.5) / 0.5
+
+ with torch.no_grad():
+ self.assert_close(SigLip2ImagePreprocessor()(images), expected("bilinear"))
+ self.assert_close(SigLip2ImagePreprocessor.from_config(224)(images), expected("bilinear"))
+ try:
+ torch.nn.functional.interpolate(images[:1, :1, :2, :2], size=(3, 3), mode="bicubic")
+ except NotImplementedError:
+ # torch 2.5.1 has no MPS upsample_bicubic2d; the bilinear default is checked above
+ pytest.skip("bicubic interpolation is unavailable for this device/dtype")
+ self.assert_close(SigLip2ImagePreprocessor(interpolation="bicubic")(images), expected("bicubic"))
+ bicubic = SigLip2ImagePreprocessor.from_config(224, interpolation="bicubic")
+ self.assert_close(bicubic(images), expected("bicubic"))