Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

fix(models)!: SigLip2 autocast pooling, Kimi-VL mask forms, unbuildable SigLip2 names, NaFlex square-reading warning (#6051)

Dmytro Mishkin8a5abbb84dce
diff --git a/changelog.d/6044.breaking.md b/changelog.d/6044.breaking.md
index 0251b83e1..5d131b4ee 100644
--- a/changelog.d/6044.breaking.md
+++ b/changelog.d/6044.breaking.md
@@ -3,3 +3,10 @@ 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.
+
+Some vision-language outputs of `kornia.models` change with no error, so weights fine-tuned with an earlier kornia give other outputs:
+
+- SigLip2's MLPs use the tanh approximation of GELU by default (`hidden_act="gelu_pytorch_tanh"`, the new config default), as the SigLIP 2 checkpoints do, where every MLP used exact GELU; `hidden_act="gelu"` keeps exact GELU.
+- `SigLip2ImagePreprocessor` and its `from_config` resize bilinearly by default, as the SigLIP 2 checkpoints do (`"resample": 2` in their `preprocessor_config.json`), where they resized bicubically. That includes the SigLIP 1 checkpoint `google/siglip-base-patch16-224`, whose preprocessor resizes bicubically: pass `interpolation="bicubic"` for it.
+- `PaliGemma` follows Gemma: it scales the text embeddings by `sqrt(hidden_size)`, its embedding's padding row is the new `PaliGemmaConfig.pad_token_id` (default 0), its MLP uses tanh GELU, and `GemmaRMSNorm` multiplies by `1 + weight` in float32 before casting; none of these held before. The padding row was `ignore_index = -100`, which wrapped to row `vocab_size - 100`, a real token whose embedding was zeroed and received no gradient.
+- `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).
diff --git a/changelog.d/6044.fixed.md b/changelog.d/6044.fixed.md
index 16a6b93dd..4519cf529 100644
--- a/changelog.d/6044.fixed.md
+++ b/changelog.d/6044.fixed.md
@@ -3,8 +3,6 @@ The vision-language models of `kornia.models` follow their reference implementat
- `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.
+- A `(B, N, C)` patch output of `NaFlex`'s patch embedding 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.
+- 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 gives that configuration (hidden size, layers, heads, patch size, image size, vocabulary) and lists the supported names. 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/changelog.d/6051.added.md b/changelog.d/6051.added.md
new file mode 100644
index 000000000..85f308df4
--- /dev/null
+++ b/changelog.d/6051.added.md
@@ -0,0 +1 @@
+`SigLip2Model.forward` takes a `pixel_attention_mask` for the vision tower, as transformers' `Siglip2Model.forward` does: it reaches `get_image_features`, so the image embeddings, the logits and the `return_loss` loss leave out the masked patches.
diff --git a/changelog.d/6051.breaking.md b/changelog.d/6051.breaking.md
new file mode 100644
index 000000000..3e5a933f2
--- /dev/null
+++ b/changelog.d/6051.breaking.md
@@ -0,0 +1,5 @@
+Vision-language calls of `kornia.models` that ran now raise, or read a name or a mask differently:
+
+- `SigLip2Config.from_name`, `SigLip2Builder.from_name` and `SigLip2Builder.from_pretrained_hf` raise `ValueError` for a name outside their supported list whose architecture its parts cannot give: a `google/` name, such as `google/siglip2-so400m-patch14-384` or the SigLIP 1 `google/siglip-large-patch16-256`; a SigLIP 1 repository under another owner, such as `someone/siglip-large-patch16-256`, unless it is a fine-tune or mirror of `google/siglip-base-patch16-224`; and a repository part with the word `so400m`, `giant` or `naflex`, or `patch<n>` for a patch size other than 16. `from_name` returned a base or large patch-16 SigLIP 2 model of the wrong shape or vocabulary for these names, and `from_pretrained_hf` failed on loading its weights.
+- These calls read the architecture of a name outside their supported list from the whole words of its repository part only, a word being a run of letters and digits: `large-models/siglip2-base-patch16-224` and `someone/siglip2-base-patch16-224-enlarged` are base, where any `large` in the name made them large.
+- `MoonViTAttention`, `MoonViT` and `KimiVLModel` read a 2-D attention mask as `(B, N)` padding and a 3-D one as `(B, N, N)`, one mask per sample, as `SigLip2Attention` does, whatever the batch size, and raise for one whose leading dimension is neither the batch size nor 1. A per-head `(H, N, N)` mask and an `(N, N)` mask shared by the batch were passed to `scaled_dot_product_attention` as they were, so they raise now unless `B` equals `H` or `N`, where they are read per sample: pass them as `(1, H, N, N)` and `(1, 1, N, N)`.
diff --git a/changelog.d/6051.fixed.md b/changelog.d/6051.fixed.md
new file mode 100644
index 000000000..f0f42e591
--- /dev/null
+++ b/changelog.d/6051.fixed.md
@@ -0,0 +1,6 @@
+More vision-language fixes in `kornia.models`, following #6044:
+
+- Under `torch.autocast`, an image whose patches are all masked no longer pools to `nan` in `SigLip2VisionModel`'s attention-pooling head: the head filled the masked scores with the float32 minimum, which rounds to `-inf` in float16 and bfloat16, and now builds the mask in the dtype the scores are computed in, with that dtype's minimum (a float64 model, which autocast leaves alone, keeps float64's). Such an image gets uniform weights under bfloat16 autocast, as without autocast. Under float16 autocast it gets float16's rounding, as in float16 without autocast: roughly uniform weights, and a non-finite output for a head whose scores are all below about -16.
+- `MoonViTAttention`, `MoonViT` and `KimiVLModel` read a `(B, N)` attention mask as a padding mask over each sample's keys, as `SigLip2Attention` does. It went to `scaled_dot_product_attention` as an `N x N` query x key mask: a batch size other than 1 and `N` raised a size mismatch, and `B == N` masked query rows by batch index. An integer mask, such as a tokenizer's `int64` padding mask, is read as a boolean one, where `scaled_dot_product_attention` raised for it.
+- `NaFlex` warns, naming `patch_size`, when it reads a `(B, N, C)` patch output without `patch_size` as a square grid that takes rectangular patches: 256 tokens of a `128 x 512` image, the `8 x 32` grid of #6004 at patch 16, are read as `16 x 16`. It added the table in that layout silently. A rectangular patch embedding gets the same warning, and `patch_size` silences it; a square-patch convolution padded by at most half its kernel never gets it. The warning names the line that calls the module.
+- `SigLip2Config.from_name`, `SigLip2Builder.from_name` and `SigLip2Builder.from_pretrained_hf` read names in any case: `Google/SigLIP2-Large-Patch16-384` is the supported checkpoint, which `from_pretrained_hf` downloads and caches under its listed spelling, and `someone/SigLIP2-Large-patch16-256` the large architecture, where it was read as base. A fine-tune or mirror of `google/siglip-base-patch16-224` under another owner, such as `someone/siglip-base-patch16-224-finetuned`, gets SigLIP 1's 32000-token vocabulary, where it got SigLIP 2's.
diff --git a/docs/source/models.rst b/docs/source/models.rst
index 9272d2625..3492c1a77 100644
--- a/docs/source/models.rst
+++ b/docs/source/models.rst
@@ -2,16 +2,21 @@ kornia.models
=============
.. meta::
- :description: The Kornia models overview provides detailed information about key built-in models for computer vision tasks, including real-time object detection (RT-DETR), edge detection (DexiNed) and semantic segmentation (a wrapper for segmentation_models_pytorch networks). It offers comprehensive documentation on each model, including methods, parameters, and example usage to streamline the integration of these models into computer vision workflows.
-
-
-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``. 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.
+ :description: The Kornia models overview provides detailed information about key built-in models for computer vision tasks, including real-time object detection (RT-DETR), edge detection (DexiNed), super-resolution (Real-ESRGAN), semantic segmentation (a wrapper for segmentation_models_pytorch networks) and the Kimi-VL and Qwen2.5-VL vision encoders. It offers comprehensive documentation on each model, including methods, parameters, and example usage to streamline the integration of these models into computer vision workflows.
+
+
+Builders for Kornia's ready-to-use models (object detection, edge detection, super-resolution, semantic segmentation
+and Kimi-VL), each returning a regular ``nn.Module``. The object detection, edge detection and super-resolution
+builders load pretrained weights by default and ``KimiVLBuilder.from_pretrained_hf`` loads them always, downloading
+them on first use. ``SegmentationModelsBuilder`` downloads nothing: it wraps a network you built yourself. The page
+also covers the vision tower of Qwen2.5-VL, whose weights kornia does not host: ``Qwen25VisionTransformer.from_pretrained``
+reads a checkpoint you downloaded yourself (see :ref:`Qwen25VisionTransformer`). For the papers behind the models, see
+the :doc:`Models </models/index>` section. Every model here accepts a batched ``(B, 3, H, W)`` float image in
+``[0, 1]``, except Kimi-VL, Qwen2.5-VL and a ``SegmentationModelsBuilder`` model built without ``preproc_params``,
+which passes its input to the network unchanged. 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``). The Qwen2.5-VL vision tower takes it normalized with the CLIP mean and
+std. :func:`kornia.io.get_sample_images` provides a couple of sample images for quick experiments.
.. _RTDETRDetectorBuilder:
diff --git a/kornia/core/utils.py b/kornia/core/utils.py
index a5a2b3af0..ce402aba2 100644
--- a/kornia/core/utils.py
+++ b/kornia/core/utils.py
@@ -21,7 +21,7 @@ import platform
import sys
from collections.abc import Mapping, Sequence
from dataclasses import asdict, fields, is_dataclass
-from types import UnionType
+from types import FrameType, UnionType
from typing import Any, Dict, List, Optional, Tuple, Type, TypeVar, Union, get_args, get_origin, get_type_hints
import torch
@@ -642,6 +642,11 @@ _torch_is_compiling = getattr(torch.compiler, "is_compiling", None) or getattr(t
_torch_is_exporting = getattr(torch.compiler, "is_exporting", None)
+def _in_torch_or_kornia(frame: FrameType) -> bool:
+ """Whether ``frame`` runs code of torch or kornia, to attribute a warning to the first frame outside them."""
+ return str(frame.f_globals.get("__name__", "")).split(".", 1)[0] in ("torch", "kornia")
+
+
@torch.jit.unused
def is_compiling() -> bool:
"""Whether execution is inside ``torch.compile`` or ``torch.export`` capture.
diff --git a/kornia/models/kimi_vl/model.py b/kornia/models/kimi_vl/model.py
index 3414da7ec..ecba9c657 100644
--- a/kornia/models/kimi_vl/model.py
+++ b/kornia/models/kimi_vl/model.py
@@ -109,9 +109,10 @@ class KimiVLModel(nn.Module):
``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.
+ attention_mask: (B, N), (B, N, N) or (B, 1, N, N) optional boolean mask for the vision encoder over its N
+ patches, ``True`` where a patch may attend to another. A (B, N) mask marks the patches every patch may
+ attend to (padding is ``False``), and a (B, N, N) mask holds one mask per sample; both are shared by
+ the heads (see :class:`~kornia.models.kimi_vl.moonvit.MoonViTAttention`).
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 6c09b6f1f..a5cbfa027 100644
--- a/kornia/models/kimi_vl/moonvit.py
+++ b/kornia/models/kimi_vl/moonvit.py
@@ -23,6 +23,8 @@ import torch
import torch.nn.functional as F
from torch import nn
+from kornia.core.check import KORNIA_CHECK
+
from .config import MoonViTConfig
@@ -84,6 +86,34 @@ class MoonViTRotaryEmbedding(nn.Module):
return freqs_cis.real, freqs_cis.imag
+def _sdpa_attention_mask(attention_mask: torch.Tensor, batch_size: int) -> torch.Tensor:
+ """Return an attention mask of :class:`MoonViTAttention` in the 4-D layout of scaled dot-product attention.
+
+ A non-float mask becomes boolean. A 2-D or 3-D mask holds one mask per sample, broadcast over the heads:
+ ``(B, N) -> (B, 1, 1, N)`` masks keys and ``(B, N, N) -> (B, 1, N, N)`` query-key pairs. A 4-D mask is returned as
+ is, so a mask this function returned passes through it again unchanged and uncopied.
+ """
+ if not attention_mask.is_floating_point():
+ attention_mask = attention_mask.bool()
+ if attention_mask.dim() in (2, 3):
+ # Passed as is, SDPA would line a 3-D mask's leading dimension up with the heads and read a 2-D one as an
+ # N x N query x key mask, so an (H, N, N) or (N, N) mask would mean something else whenever B happened to equal
+ # H or N: such masks raise and go in as 4-D. The message is a function, formatted only on failure: an f-string
+ # evaluated on every call makes Dynamo specialize the batch size and the patch count, so a dynamic-shape
+ # torch.compile would recompile for each new input shape.
+ KORNIA_CHECK(
+ attention_mask.shape[0] in (1, batch_size),
+ lambda: (
+ f"MoonViTAttention reads a {attention_mask.dim()}-D attention mask per sample, as (B, N) padding or "
+ f"(B, N, N), but the leading dimension of the {tuple(attention_mask.shape)} mask is neither the batch "
+ f"size {batch_size} nor 1. For a per-head or a shared query x key mask, pass it as 4-D: (1, H, N, N) "
+ "or (1, 1, N, N)."
+ ),
+ )
+ attention_mask = attention_mask[:, None, None] if attention_mask.dim() == 2 else attention_mask[:, None]
+ return attention_mask
+
+
class MoonViTAttention(nn.Module):
"""Multi-head self-attention layer used by the MoonViT vision encoder.
@@ -127,10 +157,14 @@ 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 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`.
+ attention_mask: Optional boolean mask, ``True`` where a query may attend to a key. A 2-D or 3-D mask
+ holds one mask per sample, shared by the heads, as
+ :class:`~kornia.models.siglip2.attention.SigLip2Attention` reads it: :math:`(B, N)` masks keys
+ (padding) and :math:`(B, N, N)` query-key pairs; a leading dimension of 1 shares the mask across the
+ batch, and any other raises. A 4-D mask, such as :math:`(B, 1, N, N)` or a per-head
+ :math:`(1, H, N, N)`, is passed as is and broadcasts against the :math:`(B, H, N, N)` attention scores
+ of :func:`~torch.nn.functional.scaled_dot_product_attention`. An integer mask is read as boolean; a
+ float mask is added to the scores.
Returns:
Tensor with shape :math:`(B, N, D)` containing the attended visual token
@@ -154,10 +188,8 @@ 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)
+ if attention_mask is not None:
+ attention_mask = _sdpa_attention_mask(attention_mask, batch_size)
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
)
@@ -277,13 +309,15 @@ class MoonViTEncoder(nn.Module):
size, ``N`` is the flattened patch count, and ``D`` is hidden size.
cos: Cosine rotary embedding table shared by all encoder layers.
sin: Sine rotary embedding table shared by all encoder layers.
- attention_mask: Optional attention mask passed unchanged to every
- transformer layer.
+ attention_mask: Optional attention mask in any form :class:`MoonViTAttention` reads, brought into the 4-D
+ layout once and shared by every transformer layer.
Returns:
Tensor with shape :math:`(B, N, D)` containing the encoded patch sequence
after all MoonViT layers have been applied.
"""
+ if attention_mask is not None:
+ attention_mask = _sdpa_attention_mask(attention_mask, x.shape[0])
for layer in self.layers:
x = layer(x, cos, sin, attention_mask)
return x
@@ -317,8 +351,10 @@ class MoonViT(nn.Module):
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.
+ attention_mask: (B, N), (B, N, N) or (B, 1, N, N) optional boolean mask over the N patches, ``True`` where
+ a patch may attend to another. A (B, N) mask marks the patches every patch may attend to (padding is
+ ``False``), and a (B, N, N) mask holds one mask per sample; both are shared by the heads. See
+ :class:`MoonViTAttention` for the other forms.
Returns:
(B, seq_len, hidden_size)
diff --git a/kornia/models/paligemma/modeling_paligemma.py b/kornia/models/paligemma/modeling_paligemma.py
index 705d53b86..cf8de21a0 100644
--- a/kornia/models/paligemma/modeling_paligemma.py
+++ b/kornia/models/paligemma/modeling_paligemma.py
@@ -343,8 +343,12 @@ class PaliGemma(nn.Module):
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)
+ # features enter unscaled (transformers divides them by the same factor before Gemma multiplies the sequence).
+ # torch.full fills it on the device; torch.tensor would copy a host value there, a sync on every forward.
+ normalizer = torch.full(
+ (), self.config.hidden_size**0.5, device=inputs_embeds.device, dtype=inputs_embeds.dtype
+ )
+ inputs_embeds = inputs_embeds * normalizer
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 b981a2576..fb1d831c3 100644
--- a/kornia/models/processors/naflex.py
+++ b/kornia/models/processors/naflex.py
@@ -17,6 +17,9 @@
from __future__ import annotations
import math
+import sys
+import warnings
+from types import FrameType
from typing import Callable, Optional, Union
import torch
@@ -25,6 +28,7 @@ from torch.nn import functional as F
from kornia.core._compat import torch_version_lt
from kornia.core.check import KORNIA_CHECK
+from kornia.core.utils import _in_torch_or_kornia, is_compiling
__all__ = ["NaFlex"]
@@ -48,7 +52,11 @@ class NaFlex(nn.Module):
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.
+ ``patch_size=16``, and as :math:`16 \times 16` without it. A square reading that takes rectangular patches,
+ on an image whose sides differ by at least the patch height or width of its longer side, warns with a
+ ``UserWarning`` naming ``patch_size`` (outside ``torch.compile`` and ``torch.export``), since it is wrong
+ for square patches; ``patch_size`` silences it, also for a patch embedding that is rectangular. A
+ square-patch convolution padded by at most half its kernel never warns.
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
@@ -165,6 +173,8 @@ class NaFlex(nn.Module):
BaseError: if that grid does not have ``num_patches`` cells, or without ``patch_size`` if
``num_patches`` is not a square number.
"""
+ # The checks format the sizes only on failure: an f-string evaluated on every call makes Dynamo specialize the
+ # image size, so a dynamic-shape torch.compile would recompile for each new size.
if self.patch_size is not None:
patch_h, patch_w = self.patch_size
h_grid, w_grid = height // patch_h, width // patch_w
@@ -186,4 +196,30 @@ class NaFlex(nn.Module):
"return (B, C, h, w)."
),
)
+ # A square grid on an image whose sides differ by at least one patch of the longer side takes rectangular
+ # patches. That is right for a rectangular patch embedding, but for square patches the grid is not square
+ # (#6004: 8 x 32 at patch 16 for 128 x 512) and the table goes in the wrong layout. N, H and W cannot tell the
+ # two apart, so warn. A square-patch convolution of stride s, overlapping or not, with padding up to half its
+ # kernel never warns: its grid is square only for sides H < W less than s apart, and H >= (side - 1) * s, so
+ # (W - H) * side < (side - 1) * s + (W - H) <= W.
+ if not is_compiling() and abs(height - width) * side >= max(height, width):
+ _warn_at_caller(
+ f"NaFlex reads the {num_patches} patch embeddings of a {height} x {width} image as a {side} x {side} "
+ f"grid, which takes {height / side:.3g} x {width / side:.3g} pixel patches. If the patches are square, "
+ "the grid is not square and the position table is added in the wrong layout: pass patch_size to "
+ "NaFlex (which also silences this warning), or make the patch embedding return (B, C, h, w)."
+ )
return side, side
+
+
+def _warn_at_caller(message: str) -> None:
+ """Warn with a ``UserWarning`` attributed to the first frame outside kornia and torch.
+
+ NaFlex warns from inside its ``forward``, which ``nn.Module.__call__`` reaches through torch frames and which may
+ run inside another kornia model, so no fixed ``stacklevel`` names the line that needs ``patch_size``.
+ """
+ level = 2 # warnings.warn's stacklevel for the frame that called this function
+ frame: Optional[FrameType] = sys._getframe(1)
+ while frame is not None and _in_torch_or_kornia(frame):
+ frame, level = frame.f_back, level + 1
+ warnings.warn(message, UserWarning, stacklevel=level if frame is not None else 2)
diff --git a/kornia/models/siglip2/builder.py b/kornia/models/siglip2/builder.py
index ca1be13bc..b83f62493 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 _SUPPORTED_MODELS, SigLip2Config
+from .config import _SUPPORTED_MODELS, SigLip2Config, _listed_name
from .model import SigLip2Model
_logger = logging.getLogger(__name__)
@@ -96,6 +96,10 @@ class SigLip2Builder:
Returns:
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.
+
+ Raises:
+ ValueError: for a name outside the supported list whose architecture its parts cannot give, such as
+ ``google/siglip2-so400m-patch14-384`` (see ``SigLip2Config.from_name``).
"""
config = SigLip2Config.from_name(model_name)
return SigLip2Model(config)
@@ -132,9 +136,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).
+ A listed name in another case is that checkpoint, downloaded and cached under the spelling above. 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 the words of its repository part (base unless one of them is
+ ``large``, patch size 16, the image size in its name).
Args:
model_name: HuggingFace model identifier. Default: "google/siglip2-base-patch16-224".
@@ -147,8 +152,10 @@ class SigLip2Builder:
:ref:`pretrained-models-conventions`).
Raises:
+ ValueError: before downloading, for a name outside the supported list whose architecture its parts cannot
+ give (see ``SigLip2Config.from_name``).
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.
+ read from its name; the message gives that configuration and lists the supported names.
.. note::
The repository must publish its weights as a single
@@ -157,8 +164,10 @@ class SigLip2Builder:
# create config from model name
config = SigLip2Config.from_name(model_name)
- # download model weights
- state_dict = _download_weights(model_name, cache_dir)
+ # download model weights; a listed name in another case under its listed spelling, so that the cache file name,
+ # which is built from the spelling, is the one every other spelling of that checkpoint uses
+ listed = _listed_name(model_name)
+ state_dict = _download_weights(listed or model_name, cache_dir)
# infer max_position_embeddings from checkpoint if not in config
config = _infer_max_position_embeddings(config, state_dict)
@@ -174,14 +183,16 @@ class SigLip2Builder:
try:
model.load_state_dict(state_dict, strict=True)
except RuntimeError as e:
- if model_name in _SUPPORTED_MODELS:
+ if listed is not None:
raise
+ vision, text = config.vision_config, config.text_config
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."
+ f"this name: hidden size {vision.hidden_size}, {vision.num_hidden_layers} layers, "
+ f"{vision.num_attention_heads} heads, patch size {vision.patch_size}, image size {vision.image_size}, "
+ f"vocabulary {text.vocab_size}. Supported names: {', '.join(_SUPPORTED_MODELS)}. A repository outside "
+ "that list loads only when its checkpoint has the architecture read from its name (see "
+ "SigLip2Config.from_name)."
) from e
return model.eval()
diff --git a/kornia/models/siglip2/config.py b/kornia/models/siglip2/config.py
index 6394a3ffc..544477baa 100644
--- a/kornia/models/siglip2/config.py
+++ b/kornia/models/siglip2/config.py
@@ -124,13 +124,41 @@ _SUPPORTED_MODELS: dict[str, tuple[int, int, int, int, int]] = {
}
+def _listed_name(model_name: str) -> Optional[str]:
+ """The ``_SUPPORTED_MODELS`` key that ``model_name`` names in any case, else ``None``."""
+ key = model_name.lower()
+ return key if key in _SUPPORTED_MODELS else None
+
+
+def _repository_words(model_name: str) -> list[str]:
+ """The lowercase words of the repository part of ``model_name``, after its last ``/``, in order.
+
+ A word is a run of letters and digits, so any other character separates words: ``"SigLIP2_Large.ft"`` is
+ ``["siglip2", "large", "ft"]``. The architecture of a name outside ``_SUPPORTED_MODELS`` is read from these words
+ alone, each compared whole: ``"LargeCorp/siglip2-base"`` is not large, ``"x/siglip2-base-enlarged"`` is not large
+ either, and ``"x/dispatch2-siglip2-base-patch16"`` does not say patch size 2.
+ """
+ return re.findall(r"[0-9a-z]+", model_name.lower().rsplit("/", 1)[-1])
+
+
+def _says_siglip1(words: list[str]) -> bool:
+ """Whether repository ``words`` name a SigLIP 1 checkpoint: ``siglip`` (not ``siglip2``) then base or large."""
+ return any(word == "siglip" and size in ("base", "large") for word, size in zip(words, words[1:]))
+
+
+def _says_siglip1_base_224(words: list[str]) -> bool:
+ """Whether repository ``words`` contain ``siglip base patch16 224``: a fine-tune or mirror of that checkpoint."""
+ return any(words[i : i + 4] == ["siglip", "base", "patch16", "224"] for i in range(len(words) - 3))
+
+
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``.
+ Used by ``SigLip2Config.from_name`` for a name outside ``_SUPPORTED_MODELS`` that ``_unreadable_name`` accepts, in
+ any case. The architecture comes from the words of the repository part (see ``_repository_words``): large if one
+ of them is ``large``, base otherwise, and the SigLIP 1 vocabulary only for a fine-tune or mirror of
+ ``google/siglip-base-patch16-224``. The image size is the first of 224, 256, 384 and 512 that is a whole number of
+ the repository part, else of the owner part before the last ``/``, else 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.
@@ -141,12 +169,38 @@ def _read_name_parts(model_name: str) -> tuple[int, int, int, int, int]:
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:
+ words = _repository_words(model_name)
+ vocab_size = 32000 if _says_siglip1_base_224(words) else 256000
+ if "large" in words:
return vocab_size, 1024, 24, 16, image_size
return vocab_size, 768, 12, 12, image_size
+def _unreadable_name(model_name: str) -> Optional[str]:
+ """Why ``_read_name_parts`` cannot give the architecture of a name outside ``_SUPPORTED_MODELS``, else ``None``.
+
+ The parts reading builds a base or large SigLIP 2 model at patch size 16. A ``google/`` name outside the table is
+ a released checkpoint whose configuration was not checked (SigLIP 1 has the 32000-token vocabulary, so400m a
+ hidden size of 1152), as is a SigLIP 1 repository (the words ``siglip base`` or ``siglip large``) other than a
+ fine-tune or mirror of ``google/siglip-base-patch16-224``. A repository part with the word so400m, giant or naflex,
+ or a word ``patch<n>`` with n other than 16, names an architecture the reading cannot build. Only the words of the
+ repository part count (see ``_repository_words``).
+ """
+ if model_name.lower().startswith("google/"):
+ return "it is a google/ checkpoint outside the supported list"
+ words = _repository_words(model_name)
+ for marker in ("so400m", "giant", "naflex"):
+ if marker in words:
+ return f"the name says {marker!r}, an architecture other than base or large at patch size 16"
+ for word in words:
+ patch = re.fullmatch(r"patch(\d+)", word)
+ if patch is not None and patch.group(1) != "16":
+ return f"the name says patch size {patch.group(1)}, not 16"
+ if _says_siglip1(words) and not _says_siglip1_base_224(words):
+ return "it names a SigLIP 1 checkpoint other than google/siglip-base-patch16-224"
+ return None
+
+
@dataclass
class SigLip2Config:
"""Configuration for SigLip2 model.
@@ -190,25 +244,47 @@ class SigLip2Config:
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.
+ Names are read in any case. Any other name, such as a fine-tune or a mirror of one of these checkpoints, is
+ read from its parts. Its architecture comes from the words of the repository part after the last ``/``, a word
+ being a run of letters and digits compared whole: the large architecture if one of them is ``large`` and the
+ base one otherwise, patch size 16, and the SigLIP 2 vocabulary (SigLIP 1's for a fine-tune or mirror of
+ ``google/siglip-base-patch16-224``, whose words contain ``siglip base patch16 224``). The owner part does not
+ count, so ``LargeCorp/siglip2-base-patch16-224`` is base, and neither does part of a word, so
+ ``someone/siglip2-base-patch16-224-enlarged`` is base too. The image size is the first of 224, 256, 384 and 512
+ that is a whole number in the repository part, else in the owner part, else 224, and the text has 512
+ 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.
+
+ A name whose parts say an architecture this reading cannot build raises: a ``google/`` name outside the list
+ (another released checkpoint, such as ``google/siglip2-so400m-patch14-384`` or the SigLIP 1
+ ``google/siglip-large-patch16-256``), a SigLIP 1 repository (the words ``siglip base`` or ``siglip large``)
+ other than a fine-tune or mirror of ``google/siglip-base-patch16-224`` (such as
+ ``someone/siglip-large-patch16-256``), or a repository part with the word ``so400m``, ``giant`` or ``naflex``,
+ or ``patch<n>`` for a patch size other than 16.
Args:
model_name: HuggingFace model identifier.
Returns:
SigLip2Config instance configured for the specified model.
+
+ Raises:
+ ValueError: for a name outside the list whose architecture its parts cannot give.
"""
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]
+ listed = _listed_name(model_name)
+ if listed is not None:
+ vocab_size, hidden_size, num_layers, num_heads, image_size = _SUPPORTED_MODELS[listed]
text_kwargs["max_position_embeddings"] = 64
else:
+ reason = _unreadable_name(model_name)
+ if reason is not None:
+ raise ValueError(
+ f"SigLip2Config.from_name cannot build {model_name!r}: {reason}. Supported names: "
+ f"{', '.join(_SUPPORTED_MODELS)}. Another name is read as a fine-tune or mirror of one of these, "
+ "with the base or large architecture at patch size 16."
+ )
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
diff --git a/kornia/models/siglip2/model.py b/kornia/models/siglip2/model.py
index c37708774..5d897f406 100644
--- a/kornia/models/siglip2/model.py
+++ b/kornia/models/siglip2/model.py
@@ -138,7 +138,9 @@ class SigLip2Model(nn.Module):
Args:
pixel_values: Input images of shape (batch_size, num_channels, height, width).
- attention_mask: Optional attention mask for vision encoder of shape (batch_size, seq_len).
+ attention_mask: Optional mask of the patches for the vision encoder and its pooling head, ``1``/``True``
+ for a patch to keep: (batch_size, num_patches), or the 3-D and 4-D forms ``SigLip2VisionModel``
+ accepts.
normalize: Whether to normalize the output features.
Returns:
@@ -195,6 +197,7 @@ class SigLip2Model(nn.Module):
attention_mask: Optional[torch.Tensor] = None,
position_ids: Optional[torch.Tensor] = None,
return_loss: bool = False,
+ pixel_attention_mask: Optional[torch.Tensor] = None,
) -> SigLip2Result:
"""Forward pass.
@@ -205,6 +208,9 @@ class SigLip2Model(nn.Module):
position_ids: Optional position IDs for text encoder.
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.
+ pixel_attention_mask: Optional mask of the image patches for the vision encoder and its pooling head,
+ ``1``/``True`` for a patch to keep, in any form ``SigLip2VisionModel`` accepts (see
+ :meth:`get_image_features`), as transformers' ``Siglip2Model.forward`` takes it.
Returns:
SigLip2Result containing:
@@ -222,7 +228,11 @@ class SigLip2Model(nn.Module):
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
+ image_embeds = (
+ self.get_image_features(pixel_values, attention_mask=pixel_attention_mask, normalize=True)
+ if pixel_values is not None
+ else None
+ )
text_embeds = (
self.get_text_features(input_ids, attention_mask=attention_mask, position_ids=position_ids, normalize=True)
if input_ids is not None
diff --git a/kornia/models/siglip2/vision_encoder.py b/kornia/models/siglip2/vision_encoder.py
index ebfe75e84..1d82b02a8 100644
--- a/kornia/models/siglip2/vision_encoder.py
+++ b/kornia/models/siglip2/vision_encoder.py
@@ -24,6 +24,8 @@ from typing import Optional
import torch
from torch import nn
+from kornia.core.utils import is_compiling
+
from .attention import SigLip2Attention
from .config import SigLip2VisionConfig, _activation
@@ -194,7 +196,11 @@ class SigLip2MultiheadAttentionPoolingHead(nn.Module):
``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.
+ uniform, and a head whose scores are all below about -16 gives a non-finite output. Under
+ :func:`torch.autocast` the scores of a float32, float16 or bfloat16 input are computed in the
+ autocast dtype, so the mask is built in that dtype with its minimum (the float32 minimum would round
+ to ``-inf`` in float16 or bfloat16), and the float16 caveat applies to float16 autocast; a float64
+ input, which autocast leaves alone, keeps the float64 mask.
Returns:
Tensor with shape :math:`(B, D)` containing the pooled visual
@@ -215,8 +221,19 @@ class SigLip2MultiheadAttentionPoolingHead(nn.Module):
# _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)
+ score_dtype = hidden_state.dtype
+ device_type = hidden_state.device.type
+ # torch.is_autocast_enabled raises for a device type without autocast, such as meta, so eager mode asks
+ # torch.amp.is_autocast_available first. Under torch.compile it does not: that call breaks the graph
+ # before torch 2.6, and a compiled model runs on a device type with autocast.
+ has_autocast = is_compiling() or torch.amp.is_autocast_available(device_type)
+ if score_dtype != torch.float64 and has_autocast and torch.is_autocast_enabled(device_type):
+ # nn.MultiheadAttention computes the scores of a float16, bfloat16 or float32 input in the autocast
+ # dtype (autocast leaves float64 alone), where another dtype's minimum can round to -inf: build the
+ # mask in that dtype.
+ score_dtype = torch.get_autocast_dtype(device_type)
+ key_padding_mask = torch.zeros(keep.shape, dtype=score_dtype, device=hidden_state.device)
+ key_padding_mask = key_padding_mask.masked_fill(~keep, torch.finfo(score_dtype).min)
key_padding_mask = key_padding_mask.expand(batch_size, -1)
# multi-head attention: probe as query, hidden_state as key/value
diff --git a/kornia/utils/__init__.py b/kornia/utils/__init__.py
index a2a4e77aa..2af5c5d98 100644
--- a/kornia/utils/__init__.py
+++ b/kornia/utils/__init__.py
@@ -43,6 +43,7 @@ from kornia.core.ops import (
vec_like as _vec_like,
)
from kornia.core.utils import T as _T
+from kornia.core.utils import _in_torch_or_kornia
from kornia.core.utils import (
batched_forward as _batched_forward,
)
@@ -359,10 +360,6 @@ def torch_meshgrid(tensors: List[torch.Tensor], indexing: str): # the 0.8.2 sig
return torch.meshgrid(tensors, indexing=indexing)
-def _in_torch_or_kornia(frame: FrameType) -> bool:
- return str(frame.f_globals.get("__name__", "")).split(".", 1)[0] in ("torch", "kornia")
-
-
def _warn_map_location_to_cpu() -> None:
"""Warn at the line that called ``torch.load``.
diff --git a/tests/models/test_kimi_vl.py b/tests/models/test_kimi_vl.py
index e5c23fa39..efa93639e 100644
--- a/tests/models/test_kimi_vl.py
+++ b/tests/models/test_kimi_vl.py
@@ -21,6 +21,7 @@ import pytest
import torch
import kornia.models.kimi_vl.builder as kimi_vl_builder
+from kornia.core.exceptions import BaseError
from kornia.models.kimi_vl import KimiVLBuilder, KimiVLConfig, KimiVLModel
from kornia.models.kimi_vl.config import KimiVLProjectorConfig, MoonViTConfig
from kornia.models.kimi_vl.model import KimiVLProjector
@@ -60,6 +61,16 @@ def model(device, dtype, config):
return KimiVLModel(config).to(device, dtype)
+def _moonvit_attention_inputs(config, batch_size, seq_len, device, dtype):
+ """Random ``(B, N, D)`` tokens and the ``(N, d / 2)`` RoPE cosine and sine for :class:`MoonViTAttention`."""
+ hidden_size = config.vision_config.hidden_size
+ head_dim = hidden_size // config.vision_config.num_attention_heads
+ x = torch.randn(batch_size, seq_len, hidden_size, device=device, dtype=dtype)
+ cos = torch.randn(seq_len, head_dim // 2, device=device, dtype=dtype)
+ sin = torch.randn(seq_len, head_dim // 2, device=device, dtype=dtype)
+ return x, cos, sin
+
+
class TestKimiVLBuilder(BaseTester):
def test_from_config(self, config):
model = KimiVLBuilder.from_config(config)
@@ -241,6 +252,27 @@ class TestKimiVLModel(BaseTester):
# 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))
+ @pytest.mark.parametrize("module", ["attention", "encoder"])
+ @pytest.mark.parametrize("form", ["padding", "pairs"])
+ def test_dynamo_mask_check_is_dynamic(self, device, dtype, torch_optimizer, config, module, form):
+ # The mask check formats the shapes only when it fails: an f-string evaluated on every call made Dynamo
+ # specialize the batch size and the patch count, so every new (B, N) compiled a graph of its own.
+ from torch._dynamo.testing import CompileCounter
+
+ net = (MoonViTAttention if module == "attention" else MoonViTEncoder)(config.vision_config)
+ net = net.to(device, dtype).eval()
+ counter = CompileCounter()
+ compiled = torch_optimizer(net, backend=counter, fullgraph=True, dynamic=True)
+ # no batch or patch count equals another axis (H = 4 heads, d / 2 = 4, D = 32), so duck sizing cannot tie them
+ for batch_size, n in ((5, 10), (6, 12), (7, 14)):
+ x, cos, sin = _moonvit_attention_inputs(config, batch_size, n, device, dtype)
+ shape = (batch_size, n) if form == "padding" else (batch_size, n, n)
+ mask = torch.ones(shape, dtype=torch.bool, device=device)
+ mask[0, ..., n // 2 :] = False
+ with torch.no_grad():
+ self.assert_close(compiled(x, cos, sin, mask), net(x, cos, sin, mask), low_tolerance=True)
+ assert counter.frame_count == 1
+
class TestKimiVLComponents(BaseTester):
def test_apply_rotary_pos_emb_preserves_float64_precision(self, device):
@@ -326,6 +358,29 @@ class TestKimiVLComponents(BaseTester):
output = encoder(x, cos, sin)
assert output.shape == (batch_size, seq_len, hidden_size)
+ def test_moonvit_encoder_reads_the_mask_once_for_all_layers(self, device, dtype, config):
+ # The encoder brings the mask into the 4-D layout once and hands every layer that one tensor, rather than each
+ # of its layers (27 in the released checkpoint) converting and checking it again: an int64 (B, N) padding mask
+ # becomes one (B, 1, 1, N) boolean mask, and the output is the one the 4-D mask gives.
+ encoder = MoonViTEncoder(config.vision_config).to(device, dtype).eval()
+ n = 16
+ x, cos, sin = _moonvit_attention_inputs(config, 2, n, device, dtype)
+ mask = torch.ones(2, n, dtype=torch.int64, device=device)
+ mask[1, n // 2 :] = 0
+
+ received = []
+ for layer in encoder.layers:
+ layer.attn.register_forward_pre_hook(lambda module, args: received.append(args[3]))
+ with torch.no_grad():
+ output = encoder(x, cos, sin, mask)
+ expected = encoder(x, cos, sin, mask.bool()[:, None, None, :])
+
+ first = received[0]
+ assert first.dtype == torch.bool
+ assert first.shape == (2, 1, 1, n)
+ assert all(layer_mask is first for layer_mask in received[1 : len(encoder.layers)])
+ self.assert_close(output, expected)
+
def test_moonvit_attention(self, device, dtype, config):
attention = MoonViTAttention(config.vision_config).to(device, dtype)
batch_size = 2
@@ -342,6 +397,89 @@ class TestKimiVLComponents(BaseTester):
output = attention(x, cos, sin)
assert output.shape == (batch_size, seq_len, hidden_size)
+ @pytest.mark.parametrize("mask_shape", [(4, 16, 16), (16, 16), (3, 16)])
+ def test_moonvit_attention_two_and_three_dim_masks_lead_with_the_batch_size(
+ self, device, dtype, config, mask_shape
+ ):
+ # A 2-D mask is a (B, N) padding mask and a 3-D one a (B, N, N) mask per sample, whatever the batch size, as
+ # SigLip2Attention reads them. A leading dimension that is neither B nor 1 raises, naming the 4-D form, rather
+ # than broadcast as a per-head (H, N, N) or a shared (N, N) mask: those would be read per sample whenever B
+ # happens to equal H or N. Here B = 2 and the fixture has H = 4 heads.
+ attention = MoonViTAttention(config.vision_config).to(device, dtype).eval()
+ x, cos, sin = _moonvit_attention_inputs(config, 2, 16, device, dtype)
+ mask = torch.ones(mask_shape, dtype=torch.bool, device=device)
+
+ with torch.no_grad(), pytest.raises(BaseError, match=r"leading dimension .* pass it as 4-D"):
+ attention(x, cos, sin, attention_mask=mask)
+
+ def test_moonvit_attention_four_dim_per_head_mask(self, device, dtype, config):
+ # A per-head mask goes in as (1, H, N, N) or (B, H, N, N), which scaled_dot_product_attention broadcasts against
+ # the (B, H, N, N) scores: masking only head 0's keys changes head 0's output only.
+ attention = MoonViTAttention(config.vision_config).to(device, dtype).eval()
+ heads, n = config.vision_config.num_attention_heads, 16
+ head_dim = config.vision_config.hidden_size // heads
+ x, cos, sin = _moonvit_attention_inputs(config, 2, n, device, dtype)
+ mask = torch.ones(1, heads, n, n, dtype=torch.bool, device=device)
+ mask[0, 0, :, n // 2 :] = False
+
+ captured = []
+ attention.out_proj.register_forward_pre_hook(lambda module, args: captured.append(args[0]))
+ with torch.no_grad():
+ attention(x, cos, sin, attention_mask=mask)
+ attention(x, cos, sin)
+ masked, unmasked = (c.view(2, n, heads, head_dim) for c in captured)
+ assert not torch.allclose(masked[:, :, 0], unmasked[:, :, 0])
+ self.assert_close(masked[:, :, 1:], unmasked[:, :, 1:])
+
+ @pytest.mark.parametrize("batch_size", [2, 16])
+ def test_moonvit_attention_two_dim_mask_is_a_padding_mask(self, device, dtype, config, batch_size):
+ # A (B, N) mask is a padding mask over the keys, read as (B, 1, 1, N) as SigLip2Attention reads it. Its leading
+ # dimension is the batch size also when B == N (16 here), where scaled_dot_product_attention would take it for
+ # an N x N query x key mask.
+ attention = MoonViTAttention(config.vision_config).to(device, dtype).eval()
+ n = 16
+ x, cos, sin = _moonvit_attention_inputs(config, batch_size, n, device, dtype)
+ mask = torch.ones(batch_size, n, dtype=torch.bool, device=device)
+ mask[1, n // 2 :] = False # sample 1 attends to the first half of the keys only
+
+ with torch.no_grad():
+ output = attention(x, cos, sin, attention_mask=mask)
+ self.assert_close(output, attention(x, cos, sin, attention_mask=mask[:, None, None, :]))
+ self.assert_close(output[1:2], attention(x[1:2], cos, sin, attention_mask=mask[1:2]))
+
+ def test_moonvit_attention_mask_with_a_leading_one_is_shared_by_the_batch(self, device, dtype, config):
+ # A (1, N) padding mask and a (1, N, N) mask broadcast over the batch; (1, 1, N, N) is the 4-D form of the
+ # latter.
+ attention = MoonViTAttention(config.vision_config).to(device, dtype).eval()
+ n = 16
+ x, cos, sin = _moonvit_attention_inputs(config, 2, n, device, dtype)
+ keys = torch.ones(1, n, dtype=torch.bool, device=device)
+ keys[:, n // 2 :] = False
+ pairs = torch.ones(1, n, n, dtype=torch.bool, device=device).tril()
+
+ with torch.no_grad():
+ self.assert_close(
+ attention(x, cos, sin, attention_mask=keys), attention(x, cos, sin, attention_mask=keys.expand(2, n))
+ )
+ self.assert_close(
+ attention(x, cos, sin, attention_mask=pairs), attention(x, cos, sin, attention_mask=pairs[None])
+ )
+
+ def test_moonvit_attention_reads_an_integer_mask_as_boolean(self, device, dtype, config):
+ # A 0/1 integer mask, such as a tokenizer's int64 padding mask, is read as the boolean mask; a float mask is
+ # added to the scores, as scaled_dot_product_attention reads it.
+ attention = MoonViTAttention(config.vision_config).to(device, dtype).eval()
+ n = 16
+ x, cos, sin = _moonvit_attention_inputs(config, 2, n, device, dtype)
+ mask = torch.ones(2, n, dtype=torch.bool, device=device)
+ mask[1, n // 2 :] = False
+ additive = torch.zeros(2, n, device=device, dtype=dtype).masked_fill(~mask, float("-inf"))
+
+ with torch.no_grad():
+ expected = attention(x, cos, sin, attention_mask=mask)
+ self.assert_close(attention(x, cos, sin, attention_mask=mask.long()), expected)
+ self.assert_close(attention(x, cos, sin, attention_mask=additive), expected)
+
def test_moonvit_rotary_embedding(self, device, dtype, config):
dim = config.vision_config.hidden_size // config.vision_config.num_attention_heads
rope = MoonViTRotaryEmbedding(dim).to(device, dtype)
diff --git a/tests/models/test_naflex.py b/tests/models/test_naflex.py
index 307995cbd..e2222ef76 100644
--- a/tests/models/test_naflex.py
+++ b/tests/models/test_naflex.py
@@ -14,9 +14,11 @@
# See the License for the specific language governing permissions and
# limitations under the License.
#
+import contextlib
import io
import math
import warnings
+from collections.abc import Iterator
import pytest
import torch
@@ -56,6 +58,18 @@ def _reference_positions(table: Tensor, height: int, width: int) -> Tensor:
return resized.reshape(-1, height * width).transpose(0, 1).to(table.device, table.dtype)
+def _square_reading_warning(expected: bool) -> Iterator[None]:
+ """Expect NaFlex's warning that a square reading takes rectangular patches, or make that warning an error."""
+ if expected:
+ with pytest.warns(UserWarning, match="pass patch_size"):
+ yield
+ else:
+ with warnings.catch_warnings():
+ warnings.filterwarnings("error", message="NaFlex reads")
+ yield
+
+
class TestNaFlex(BaseTester):
@pytest.fixture
def model(self) -> NaFlex:
@@ -179,24 +193,33 @@ class TestNaFlex(BaseTester):
naflex(torch.zeros(3, 3, height, width, device=device, dtype=dtype))
@pytest.mark.parametrize(
- ("height", "width", "kernel", "stride", "side"),
+ ("height", "width", "kernel", "stride", "side", "rectangular"),
[
- (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),
+ (20, 20, 3, 2, 9, False),
+ (19, 20, 3, 2, 9, False),
+ (20, 36, 3, (2, 4), 9, True),
+ (256, 512, (16, 32), (16, 32), 16, True),
+ (64, 144, (10, 24), (10, 24), 6, True),
],
)
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
+ self,
+ device: torch.device,
+ dtype: torch.dtype,
+ height: int,
+ width: int,
+ kernel,
+ stride,
+ side: int,
+ rectangular: bool,
) -> 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).
+ # interpolation (no axis shrinks). The rectangular strides, whose square grid NaFlex cannot tell apart from
+ # #6004's non-square grid of square patches, get the warning that names patch_size.
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():
+ with torch.no_grad(), _square_reading_warning(rectangular):
tokens = conv(images).flatten(2).transpose(1, 2)
assert tokens.shape[1] == side * side
own = torch.randn(side * side, _CHANNELS, device=device, dtype=dtype)
@@ -208,6 +231,39 @@ class TestNaFlex(BaseTester):
out = NaFlex(lambda x: conv(x).flatten(2).transpose(1, 2), small)(images)
self.assert_close(out, tokens + resized)
+ @pytest.mark.parametrize(
+ ("height", "width", "kernel", "stride", "padding", "side"),
+ [(208, 223, 16, 16, 8, 14), (9, 12, 7, 4, 3, 3), (33, 47, 16, 16, 8, 3), (12, 15, 4, 4, 2, 4)],
+ )
+ def test_bnc_without_patch_size_does_not_warn_for_a_padded_square_patch_convolution(
+ self, device: torch.device, dtype: torch.dtype, height: int, width: int, kernel, stride, padding, side: int
+ ) -> None:
+ # Padding up to half the kernel adds output positions, so these square-patch convolutions give a square grid
+ # on sides more than min(H, W) / side apart: the square reading is right and must not warn.
+ conv = torch.nn.Conv2d(3, _CHANNELS, kernel, stride=stride, padding=padding).to(device, dtype)
+ images = torch.rand(1, 3, height, width, device=device, dtype=dtype)
+ table = torch.randn(side * side, _CHANNELS, device=device, dtype=dtype)
+ with torch.no_grad(), _square_reading_warning(False):
+ tokens = conv(images).flatten(2).transpose(1, 2)
+ assert tokens.shape[1] == side * side
+ self.assert_close(NaFlex(lambda x: conv(x).flatten(2).transpose(1, 2), table)(images), tokens + table)
+
+ def test_bnc_without_patch_size_warns_when_the_square_grid_needs_rectangular_patches(
+ self, device: torch.device, dtype: torch.dtype
+ ) -> None:
+ # #6004's case: the 256 tokens of a 128 x 512 image at patch 16 are an 8 x 32 grid, but without patch_size
+ # they are read as 16 x 16, a grid that only 8 x 32 pixel patches give. NaFlex cannot tell the two apart, so
+ # the square reading stays and warns, naming patch_size; with patch_size the 8 x 32 grid is read silently.
+ table = torch.randn(256, _CHANNELS, device=device, dtype=dtype)
+ images = torch.zeros(1, 3, 128, 512, device=device, dtype=dtype)
+ with pytest.warns(UserWarning, match=r"as a 16 x 16 grid, which takes 8 x 32 pixel patches") as record:
+ NaFlex(_zero_tokens, table)(images)
+ # attributed to the line that called the module, not to a frame inside kornia or torch.nn.Module
+ assert [warning.filename for warning in record] == [__file__]
+ with _square_reading_warning(False):
+ out = NaFlex(_zero_tokens, table, patch_size=16)(images)
+ self.assert_close(out, _reference_positions(table, 8, 32).expand(1, -1, -1))
+
@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
@@ -364,3 +420,39 @@ class TestNaFlex(BaseTester):
with torch.no_grad():
self.assert_close(naflex_optimized(images), naflex(images))
+
+ def test_dynamo_patch_size_check_is_dynamic(
+ self, device: torch.device, dtype: torch.dtype, torch_optimizer
+ ) -> None:
+ # The patch_size grid check formats the sizes only when it fails: an f-string evaluated on every call made
+ # Dynamo specialize the image size, so every new size compiled a graph of its own.
+ from torch._dynamo.testing import CompileCounter
+
+ naflex = NaFlex(_zero_tokens, torch.randn(16, _CHANNELS, device=device, dtype=dtype), patch_size=16)
+ counter = CompileCounter()
+ compiled = torch_optimizer(naflex, backend=counter, fullgraph=True, dynamic=True)
+ # 6 x 10, 7 x 11 and 8 x 13 grids: every axis upsamples the 4 x 4 table, so the antialias guard holds throughout
+ for height, width in ((96, 160), (112, 176), (128, 208)):
+ images = torch.rand(2, 3, height, width, device=device, dtype=dtype)
+ with torch.no_grad():
+ self.assert_close(compiled(images), naflex(images))
+ assert counter.frame_count == 1
+
+ def test_dynamo_fullgraph_naflex_square_reading_of_rectangular_patches(
+ self, device: torch.device, dtype: torch.dtype, torch_optimizer
+ ) -> None:
+ # The warning about a square reading that takes rectangular patches is eager-only: it must not break the graph.
+ # Zero tokens of (16, 32) patches, a 16 x 16 grid of a 256 x 512 image, so the output is the resized 8 x 8 table
+ # (a convolution would add cuDNN's TF32 rounding on CUDA).
+ naflex = NaFlex(
+ lambda x: x.new_zeros(x.shape[0], (x.shape[2] // 16) * (x.shape[3] // 32), _CHANNELS),
+ torch.randn(64, _CHANNELS, device=device, dtype=dtype),
+ )
+ images = torch.rand(2, 3, 256, 512, device=device, dtype=dtype)
+
+ naflex_optimized = torch_optimizer(naflex, fullgraph=True)
+
+ with torch.no_grad(), pytest.warns(UserWarning, match="pass patch_size"):
+ expected = naflex(images)
+ with torch.no_grad():
+ self.assert_close(naflex_optimized(images), expected)
diff --git a/tests/models/test_paligemma.py b/tests/models/test_paligemma.py
index 371800f74..f9447e012 100644
--- a/tests/models/test_paligemma.py
+++ b/tests/models/test_paligemma.py
@@ -21,8 +21,10 @@ import torch
from kornia.models.paligemma import PaliGemma, PaliGemmaConfig
from kornia.models.paligemma.modeling_paligemma import GemmaAttention, GemmaMLP, GemmaRMSNorm
+from testing.base import BaseTester
-class TestPaliGemmaModules:
+
+class TestPaliGemmaModules(BaseTester):
@pytest.fixture
def config(self):
conf = PaliGemmaConfig()
@@ -37,66 +39,87 @@ class TestPaliGemmaModules:
conf.vision_config.patch_size = 16
return conf
- def test_mlp(self, config):
- model = GemmaMLP(config)
- x = torch.randn(1, 10, config.hidden_size)
+ def test_mlp(self, device, dtype, config):
+ model = GemmaMLP(config).to(device, dtype)
+ x = torch.randn(1, 10, config.hidden_size, device=device, dtype=dtype)
output = model(x)
assert output.shape == (1, 10, config.hidden_size)
+ assert output.dtype == dtype
- def test_attention(self, config):
- model = GemmaAttention(config)
- x = torch.randn(1, 10, config.hidden_size)
- position_ids = torch.arange(10).unsqueeze(0)
+ def test_attention(self, device, dtype, config):
+ model = GemmaAttention(config).to(device, dtype)
+ x = torch.randn(1, 10, config.hidden_size, device=device, dtype=dtype)
+ position_ids = torch.arange(10, device=device).unsqueeze(0)
output = model(x, position_ids=position_ids)
assert output.shape == (1, 10, config.hidden_size)
+ assert output.dtype == dtype
- def test_forward(self, config):
- model = PaliGemma(config)
+ def test_forward(self, device, dtype, config):
+ model = PaliGemma(config).to(device, dtype)
model.eval()
- pixel_values = torch.randn(1, 3, 32, 32)
- input_ids = torch.randint(0, config.vocab_size, (1, 5))
+ pixel_values = torch.randn(1, 3, 32, 32, device=device, dtype=dtype)
+ input_ids = torch.randint(0, config.vocab_size, (1, 5), device=device)
logits = model(input_ids=input_ids, pixel_values=pixel_values)
assert logits.shape == (1, 9, config.vocab_size)
+ assert logits.dtype == dtype
- @pytest.mark.parametrize("dtype", [torch.float32, torch.float16, torch.bfloat16])
- def test_text_embeddings_are_scaled(self, config, dtype):
+ def test_text_embeddings_are_scaled(self, device, dtype, config):
# 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()
+ model = PaliGemma(config).to(device, 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))
+ pixel_values = torch.randn(2, 3, 32, 32, device=device, dtype=dtype)
+ input_ids = torch.randint(1, config.vocab_size, (2, 5), device=device)
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
+ text = model.embed_tokens(input_ids) * torch.tensor(32**0.5, device=device, 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)
+ self.assert_close(decoder_input[:, :4], image, rtol=0.0, atol=0.0)
+ self.assert_close(decoder_input[:, 4:], text, rtol=0.0, atol=0.0)
+
+ def test_forward_does_not_synchronize_cuda(self, device, dtype, config):
+ # The sqrt(hidden_size) scale is made on the device: a host scalar copied to the GPU on every forward stalls
+ # the stream and cannot run inside CUDA graph capture.
+ if device.type != "cuda":
+ pytest.skip("CUDA synchronization")
+ model = PaliGemma(config).to(device, dtype).eval()
+ pixel_values = torch.randn(1, 3, 32, 32, device=device, dtype=dtype)
+ input_ids = torch.randint(0, config.vocab_size, (1, 5), device=device)
- def test_padding_idx_is_pad_token_id(self, config):
+ with torch.no_grad():
+ model(input_ids=input_ids, pixel_values=pixel_values) # warm-up: lazy CUDA initialization syncs
+ mode = torch.cuda.get_sync_debug_mode() # restored afterwards, so a run that audits syncs keeps its mode
+ torch.cuda.set_sync_debug_mode("error")
+ try:
+ model(input_ids=input_ids, pixel_values=pixel_values)
+ finally:
+ torch.cuda.set_sync_debug_mode(mode)
+
+ def test_padding_idx_is_pad_token_id(self, device, dtype, 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()
+ model = PaliGemma(config).to(device, dtype).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()
+ input_ids = torch.tensor([[0, 5, 200, 7]], device=device)
+ model(input_ids=input_ids, pixel_values=torch.randn(1, 3, 32, 32, device=device, dtype=dtype)).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.
@@ -108,7 +131,7 @@ class TestPaliGemmaModules:
assert isinstance(activation, torch.nn.GELU)
assert activation.approximate == "tanh"
- def test_rms_norm_multiplies_in_float32(self):
+ def test_rms_norm_multiplies_in_float32(self, device):
# 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.
@@ -116,12 +139,12 @@ class TestPaliGemmaModules:
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()
+ norm = norm.to(device, torch.float16)
+ x = torch.randn(2, 5, 64, generator=generator).to(device, torch.float16)
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())
+ self.assert_close(out, (normalized * (1.0 + norm.weight.float())).half(), rtol=0.0, atol=0.0)
diff --git a/tests/models/test_siglip2.py b/tests/models/test_siglip2.py
index 261b91b46..6b1fe18ba 100644
--- a/tests/models/test_siglip2.py
+++ b/tests/models/test_siglip2.py
@@ -77,6 +77,14 @@ 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 _from_name_or_error(model_name):
+ """``SigLip2Config.from_name(model_name)``, or the type of the error it raises, to compare two names' readings."""
+ try:
+ return SigLip2Config.from_name(model_name)
+ except ValueError as error:
+ return type(error)
+
+
def _tiny_vision_config():
"""32 px images at patch 4: an 8 x 8 grid of 64 patches."""
return SigLip2VisionConfig(
@@ -199,12 +207,19 @@ class TestSigLip2Builder:
("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)),
+ # names are read in any case, and what the owner part says about the architecture does not count
+ ("someone/SigLIP2-Large-Patch16-256", (256000, 1024, 24, 16, 256, 16, 512)),
+ ("giantlab/siglip2-base-patch16-224-ft", (256000, 768, 12, 12, 224, 16, 512)),
+ ("patch14ai/siglip2-base-patch16-224", (256000, 768, 12, 12, 224, 16, 512)),
+ # a fine-tune or mirror of the supported SigLIP 1 checkpoint has its 32000-token vocabulary
+ ("someone/siglip-base-patch16-224-finetuned", (32000, 768, 12, 12, 224, 16, 512)),
+ ("someone/SigLIP-Base-Patch16-224", (32000, 768, 12, 12, 224, 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.
+ # A fine-tune or mirror of a supported checkpoint under another name: base unless a word of the repository
+ # part is "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 = (
@@ -219,6 +234,105 @@ class TestSigLip2Builder:
assert actual == expected
assert (text.hidden_size, text.num_hidden_layers, text.num_attention_heads) == expected[1:4]
+ @pytest.mark.parametrize(
+ "model_name",
+ [
+ # #6004: so400m has hidden size 1152 and patch 14, giant is wider still, and the SigLIP 1 checkpoints have
+ # the 32000-token vocabulary; the name parser would build a base patch-16 SigLIP 2 model for each.
+ "google/siglip2-so400m-patch14-384",
+ "google/siglip2-giant-opt-patch16-384",
+ "google/siglip-large-patch16-256",
+ "google/siglip-base-patch16-384",
+ "google/siglip2-base-patch32-256",
+ "google/siglip2-base-patch16-naflex",
+ # the same architectures under another owner
+ "someone/siglip2-so400m-patch14-384-finetuned",
+ "someone/siglip2-giant-opt-patch16-256-mirror",
+ "someone/siglip2-base-patch32-256-mirror",
+ "someone/siglip2-base-patch16-naflex-ft",
+ # SigLIP 1 checkpoints other than the supported base 224 one, under another owner
+ "someone/siglip-large-patch16-256",
+ "someone/siglip-base-patch16-384",
+ "someone/siglip-base-patch16-256-multilingual",
+ "Someone/SigLIP-Large-Patch16-256-mirror",
+ ],
+ )
+ def test_from_name_rejects_a_name_it_cannot_read(self, model_name):
+ # A google/ checkpoint outside the table, or a repository part with the word so400m, giant, naflex or a patch
+ # size other than 16, names an architecture the parts reading cannot build: it raises rather than return a
+ # model of the wrong shape. Neither call builds a model.
+ with pytest.raises(ValueError, match=r"cannot build .* Supported names: google/siglip-base-patch16-224, "):
+ SigLip2Config.from_name(model_name)
+ with pytest.raises(ValueError, match="cannot build"):
+ SigLip2Builder.from_name(model_name)
+
+ @pytest.mark.parametrize(
+ "repository",
+ [
+ "siglip2-base-patch16-224-finetuned",
+ "siglip2-large-patch16-384-mirror",
+ "my-siglip",
+ "siglip-base-patch16-224-finetuned",
+ "siglip2-so400m-patch14-384-finetuned",
+ "siglip2-base-patch32-256-mirror",
+ "siglip-large-patch16-256",
+ ],
+ )
+ @pytest.mark.parametrize("owner", ["LargeCorp", "large-models", "giantlab", "so400m-fans", "naflex", "patch14ai"])
+ def test_from_name_reads_the_architecture_from_the_repository_part_only(self, repository, owner):
+ # An owner that says large, giant, so400m, naflex or a patch size gets the reading of a neutral owner, for a
+ # name that reads and for one that raises alike ("LargeCorp/siglip2-base-..." was the large architecture).
+ assert _from_name_or_error(f"{owner}/{repository}") == _from_name_or_error(f"someone/{repository}")
+
+ @pytest.mark.parametrize(
+ ("model_name", "expected"),
+ [
+ # (hidden_size, image_size), and patch size 16 and the SigLIP 2 vocabulary throughout: a marker inside a
+ # longer word of the repository part is not the marker
+ ("someone/siglip2-base-patch16-224-enlarged", (768, 224)),
+ ("someone/siglip2-base-patch16-224-giantdata", (768, 224)),
+ ("someone/siglip2-base-patch16-224-naflexible", (768, 224)),
+ ("someone/siglip2-base-patch16-224-so400mx", (768, 224)),
+ ("someone/dispatch2-siglip2-base-patch16-224", (768, 224)),
+ ("someone/notsiglip-large-patch16-256", (1024, 256)),
+ # words are separated by any character that is not a letter or a digit
+ ("someone/siglip2_large_patch16_384", (1024, 384)),
+ ("someone/SigLIP2.Large.Patch16.512", (1024, 512)),
+ ],
+ )
+ def test_from_name_reads_whole_words(self, model_name, expected):
+ config = SigLip2Config.from_name(model_name)
+ assert (config.vision_config.hidden_size, config.vision_config.image_size) == expected
+ assert (config.vision_config.patch_size, config.text_config.vocab_size) == (16, 256000)
+
+ @pytest.mark.parametrize(
+ "model_name", ["someone/siglip2_so400m_patch14_384", "someone/siglip2-base.patch32", "someone/siglip_large_ft"]
+ )
+ def test_from_name_rejects_whole_words_after_any_separator(self, model_name):
+ with pytest.raises(ValueError, match="cannot build"):
+ SigLip2Config.from_name(model_name)
+
+ @pytest.mark.parametrize(
+ "model_name",
+ [
+ "someone/siglip2-base-patch16-224-finetuned",
+ "someone/siglip2-large-patch16-384-mirror",
+ "someone/siglip-base-patch16-224-finetuned",
+ "org-256/siglip2-finetune",
+ "someone/siglip2-so400m-patch14-384",
+ "someone/siglip-large-patch16-256",
+ ],
+ )
+ def test_from_name_reads_an_unlisted_name_in_any_case(self, model_name):
+ expected = _from_name_or_error(model_name)
+ assert _from_name_or_error(model_name.upper()) == expected
+ assert _from_name_or_error(model_name.swapcase().replace("SOMEONE", "Someone")) == expected
+
+ @pytest.mark.parametrize("model_name", ["Google/SigLIP2-Large-Patch16-384", "GOOGLE/siglip-base-patch16-224"])
+ def test_from_name_table_ignores_case(self, model_name):
+ # A supported checkpoint named in another case is that checkpoint, with its 64 text positions.
+ assert SigLip2Config.from_name(model_name) == SigLip2Config.from_name(model_name.lower())
+
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))
@@ -247,10 +361,38 @@ class TestSigLip2Builder:
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)
+ # The message reports the configuration actually read from the name, here the tiny stand-in.
+ assert "hidden size 32, 2 layers, 4 heads, patch size 4, image size 32, vocabulary 100" 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):
+ @pytest.mark.parametrize(
+ ("model_name", "downloaded"),
+ [
+ # a listed name in another case is downloaded, and so cached, under its listed spelling, not as a second
+ # copy (the Hub redirects the case variant to the same repository)
+ ("Google/SigLIP2-Base-Patch16-224", "google/siglip2-base-patch16-224"),
+ ("GOOGLE/siglip-base-patch16-224", "google/siglip-base-patch16-224"),
+ # an unlisted name keeps the caller's spelling: kornia does not know its repository's
+ ("Someone/SigLIP2-Base-Patch16-224-ft", "Someone/SigLIP2-Base-Patch16-224-ft"),
+ ],
+ )
+ def test_from_pretrained_hf_downloads_a_listed_name_under_its_listed_spelling(
+ self, monkeypatch, config, model_name, downloaded
+ ):
+ monkeypatch.setattr(SigLip2Config, "from_name", staticmethod(lambda model_name: config))
+ state_dict = SigLip2Model(config).state_dict()
+ repositories = []
+
+ def download(model_name, cache_dir):
+ repositories.append(model_name)
+ return state_dict
+
+ monkeypatch.setattr(siglip2_builder, "_download_weights", download)
+ SigLip2Builder.from_pretrained_hf(model_name)
+ assert repositories == [downloaded]
+
+ @pytest.mark.parametrize("model_name", ["google/siglip2-base-patch16-224", "Google/SigLIP2-Base-Patch16-224"])
+ def test_from_pretrained_hf_passes_on_a_listed_checkpoints_load_error(self, monkeypatch, config, model_name):
# 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(
@@ -262,7 +404,7 @@ class TestSigLip2Builder:
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")
+ SigLip2Builder.from_pretrained_hf(model_name)
assert "outside that list" not in str(error.value)
assert error.value.__cause__ is None
@@ -465,6 +607,25 @@ class TestSigLip2Model(BaseTester):
assert output.logits_per_text.shape == (1, 3)
assert output.loss is None
+ def test_pixel_attention_mask_reaches_the_image_embeddings_and_the_loss(self, device, dtype, model, config):
+ # transformers' Siglip2Model.forward takes a pixel_attention_mask for the vision tower (modeling_siglip2.py
+ # v4.51.0). Here it reaches get_image_features, so the pixels of masked patches change neither the image
+ # embeddings nor the loss.
+ pixel_values = torch.randn(2, 3, 32, 32, device=device, dtype=dtype)
+ changed = pixel_values.clone()
+ changed[..., 16:, :] = torch.randn(2, 3, 16, 32, device=device, dtype=dtype)
+ mask = _patch_rows_4_to_7_masked(device).expand(2, -1)
+ input_ids = _create_input_ids(2, 10, config, device)
+
+ with torch.no_grad():
+ output = model(pixel_values, input_ids, return_loss=True, pixel_attention_mask=mask)
+ output_changed = model(changed, input_ids, return_loss=True, pixel_attention_mask=mask)
+ features = model.get_image_features(pixel_values, attention_mask=mask)
+
+ self.assert_close(output.image_embeds, features)
+ self.assert_close(output_changed.image_embeds, output.image_embeds)
+ self.assert_close(output_changed.loss, output.loss)
+
def test_gradcheck(self, device, dtype, config):
"""Test gradient computation correctness."""
# Convert model to float64 for gradcheck
@@ -501,6 +662,23 @@ class TestSigLip2Model(BaseTester):
self.assert_close(actual.image_embeds, expected.image_embeds)
self.assert_close(actual.text_embeds, expected.text_embeds)
+ def test_dynamo_return_loss_check_is_dynamic(self, device, dtype, torch_optimizer, model, config):
+ # The equal-batches check of return_loss formats the batch sizes only when it fails: an f-string evaluated on
+ # every call made Dynamo specialize the batch size, so every new batch compiled a graph of its own.
+ from torch._dynamo.testing import CompileCounter
+
+ counter = CompileCounter()
+ compiled = torch_optimizer(model, backend=counter, fullgraph=True, dynamic=True)
+ # no batch equals another axis (3 channels, 4 heads, 8 head dims, 10 tokens), so duck sizing cannot tie it
+ for batch_size in (5, 6, 7):
+ pixel_values = torch.randn(batch_size, 3, 32, 32, device=device, dtype=dtype)
+ input_ids = _create_input_ids(batch_size, 10, config, device)
+ with torch.no_grad():
+ actual = compiled(pixel_values=pixel_values, input_ids=input_ids, return_loss=True)
+ expected = model(pixel_values=pixel_values, input_ids=input_ids, return_loss=True)
+ self.assert_close(actual.loss, expected.loss, low_tolerance=True)
+ assert counter.frame_count == 1
+
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()
@@ -766,6 +944,89 @@ class TestSigLip2Components(BaseTester):
self.assert_close(pooled[1:], uniform)
self.assert_close(pooled[:1], pooled_alone)
+ @pytest.mark.parametrize("autocast_dtype", [torch.bfloat16, torch.float16])
+ def test_pooling_head_all_masked_sample_pools_uniformly_under_autocast(self, device, dtype, autocast_dtype):
+ # Under autocast the hidden state stays float32 while nn.MultiheadAttention computes the scores in the
+ # autocast dtype, where float32's finfo.min rounds to -inf: the fill has to be finite in the autocast dtype,
+ # or a sample with every key masked pools to nan.
+ if dtype != torch.float32:
+ pytest.skip("autocast casts float32 inputs only")
+ 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():
+ expected = head(hidden_state, attention_mask=mask)
+ with torch.autocast(device.type, dtype=autocast_dtype):
+ pooled = head(hidden_state, attention_mask=mask)
+
+ assert torch.isfinite(pooled).all()
+ # the autocast run rounds the projections to the autocast dtype
+ self.assert_close(pooled.to(dtype), expected, rtol=5e-2, atol=5e-2)
+
+ @pytest.mark.parametrize(
+ ("param_dtype", "autocast_dtype"), [(torch.bfloat16, torch.float16), (torch.float64, torch.float16)]
+ )
+ def test_pooling_head_all_masked_sample_pools_uniformly_in_the_score_dtype(
+ self, device, dtype, param_dtype, autocast_dtype
+ ):
+ # The scores are computed in the autocast dtype for a float16, bfloat16 or float32 input and in float64 for a
+ # float64 one, which autocast leaves alone. A bfloat16 mask filled with float16's minimum held -65536, which
+ # overflows to -inf in float16 (nan); a float64 mask filled with it kept the score differences (not uniform).
+ if dtype != torch.float32:
+ pytest.skip("one run per device: the dtypes are the parameters")
+ if param_dtype == torch.float64 and device.type == "mps":
+ pytest.skip("MPS does not support float64")
+ if param_dtype == torch.bfloat16 and device.type == "cpu":
+ pytest.skip("CPU float16 autocast rejects the bfloat16 parameters of layer_norm")
+ config = _tiny_vision_config()
+ head = SigLip2MultiheadAttentionPoolingHead(config).to(device, param_dtype).eval()
+ hidden_state = torch.randn(1, 64, config.hidden_size, device=device, dtype=param_dtype)
+ mask = torch.zeros(1, 64, dtype=torch.bool, device=device)
+ captured = {}
+ forward = head.attention.forward
+ head.attention.forward = lambda *args, **kwargs: captured.setdefault("out", forward(*args, **kwargs))
+
+ with torch.no_grad(), torch.autocast(device.type, dtype=autocast_dtype):
+ pooled = head(hidden_state, attention_mask=mask)
+
+ assert torch.isfinite(pooled).all()
+ weights = captured["out"][1].float()
+ self.assert_close(weights, torch.full_like(weights, 1 / 64), rtol=0.0, atol=0.0)
+
+ def test_dynamo_fullgraph_pooling_head_under_autocast(self, device, dtype, torch_optimizer):
+ # The autocast fill is chosen inside the compiled graph too. torch.amp.is_autocast_available cannot be traced
+ # before torch 2.6 (a graph break, so fullgraph raised on torch 2.5.1), so the head asks it in eager mode only.
+ if dtype != torch.float32:
+ pytest.skip("autocast casts float32 inputs only")
+ autocast_dtype = torch.bfloat16 if device.type == "cpu" else torch.float16
+ 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[1] = False # sample 1 entirely masked: nan with the float32 fill under autocast
+
+ compiled = torch_optimizer(head, fullgraph=True)
+ with torch.no_grad(), torch.autocast(device.type, dtype=autocast_dtype):
+ pooled = compiled(hidden_state, attention_mask=mask)
+ expected = head(hidden_state, attention_mask=mask)
+
+ assert torch.isfinite(pooled).all()
+ self.assert_close(pooled, expected, low_tolerance=True)
+
+ def test_pooling_head_masked_on_the_meta_device(self):
+ # torch.is_autocast_enabled raises for a device type without autocast, such as meta, which shape inference and
+ # deferred initialization use: the head asks torch.amp.is_autocast_available first in eager mode.
+ config = _tiny_vision_config()
+ head = SigLip2MultiheadAttentionPoolingHead(config).to("meta").eval()
+ hidden_state = torch.empty(2, 64, config.hidden_size, device="meta")
+ mask = torch.ones(2, 64, dtype=torch.bool, device="meta")
+
+ assert head(hidden_state, attention_mask=mask).shape == (2, config.hidden_size)
+
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.