π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
fix(models): MoonViT and SigLip2 attention reject masks that do not cover every key (#6070)
Dmytro Mishkinb537a5daa12c
diff --git a/changelog.d/6070.fixed.md b/changelog.d/6070.fixed.mdnew file mode 100644index 000000000..8b3014b0a--- /dev/null+++ b/changelog.d/6070.fixed.md@@ -0,0 +1,7 @@+`SigLip2Attention` and `MoonViTAttention`, with `MoonViTEncoder` and `MoonViT`, check the trailing dimensions of an+attention mask: the last one, the keys, must be the sequence length, and in a 3-D or 4-D mask the one before it, the+queries, the sequence length or 1. A mask with a key dimension of 1, such as `(B, 1)` or `(B, N, 1)`, used to be+broadcast over every key: on the CPU and in CUDA float64 it gave the output of no mask, and in CUDA float32, float16 and+bfloat16 `scaled_dot_product_attention` raised `RuntimeError: (*bias): last dimension must be contiguous`. A query+dimension other than 1 or the sequence length raised a broadcasting `RuntimeError`. Both now raise a `ShapeError`, a+`ValueError`, that names the sequence length.diff --git a/kornia/models/kimi_vl/moonvit.py b/kornia/models/kimi_vl/moonvit.pyindex a5cbfa027..323c90018 100644--- a/kornia/models/kimi_vl/moonvit.py+++ b/kornia/models/kimi_vl/moonvit.py@@ -23,7 +23,7 @@ import torchimport torch.nn.functional as Ffrom torch import nn-from kornia.core.check import KORNIA_CHECK+from kornia.core.check import KORNIA_CHECK, KORNIA_CHECK_SIZESfrom .config import MoonViTConfig@@ -86,15 +86,31 @@ class MoonViTRotaryEmbedding(nn.Module):return freqs_cis.real, freqs_cis.imag-def _sdpa_attention_mask(attention_mask: torch.Tensor, batch_size: int) -> torch.Tensor:+def _sdpa_attention_mask(attention_mask: torch.Tensor, batch_size: int, seq_len: 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.+ is, so a mask this function returned passes through it again unchanged and uncopied. Every form has the ``N`` keys+ as its last dimension, and a 3-D or 4-D mask ``N`` queries or 1 before it."""if not attention_mask.is_floating_point():attention_mask = attention_mask.bool()+ if attention_mask.dim() >= 2:+ # A key dimension of 1 would broadcast one value over every patch: the same as no mask on the CPU, and SDPA's+ # unrelated "last dimension must be contiguous" error in CUDA float32 and half.+ sizes: list[Optional[int]] = [None] * attention_mask.dim()+ sizes[-1] = seq_len+ if attention_mask.dim() > 2:+ sizes[-2] = 1 if attention_mask.shape[-2] == 1 else seq_len+ KORNIA_CHECK_SIZES(+ attention_mask,+ sizes,+ lambda: (+ f"MoonViTAttention reads an attention mask over the {seq_len} patches: the keys are its last "+ f"dimension, and in a 3-D or 4-D mask the queries, {seq_len} or 1, the one before it."+ ),+ )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@@ -163,7 +179,9 @@ class MoonViTAttention(nn.Module):(padding) and :math:`(B, N, N)` query-key pairs; a leading dimension of 1 shares the mask across thebatch, 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+ of :func:`~torch.nn.functional.scaled_dot_product_attention`. The last dimension of every form is the+ :math:`N` keys, and in a 3-D or 4-D mask the one before it is the :math:`N` queries or 1, which+ shares the key mask across the queries; other sizes raise. An integer mask is read as boolean; afloat mask is added to the scores.Returns:@@ -189,7 +207,7 @@ 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:- attention_mask = _sdpa_attention_mask(attention_mask, batch_size)+ attention_mask = _sdpa_attention_mask(attention_mask, batch_size, seq_len)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)@@ -317,7 +335,7 @@ class MoonViTEncoder(nn.Module):after all MoonViT layers have been applied."""if attention_mask is not None:- attention_mask = _sdpa_attention_mask(attention_mask, x.shape[0])+ attention_mask = _sdpa_attention_mask(attention_mask, x.shape[0], x.shape[1])for layer in self.layers:x = layer(x, cos, sin, attention_mask)return xdiff --git a/kornia/models/siglip2/attention.py b/kornia/models/siglip2/attention.pyindex d3273310a..1b4a46f73 100644--- a/kornia/models/siglip2/attention.py+++ b/kornia/models/siglip2/attention.py@@ -26,7 +26,7 @@ import torchimport torch.nn.functional as Ffrom torch import nn-from kornia.core.check import KORNIA_CHECK+from kornia.core.check import KORNIA_CHECK, KORNIA_CHECK_SIZES__all__ = ["SigLip2Attention"]@@ -93,6 +93,8 @@ class SigLip2Attention(nn.Module):- (batch_size, 1, seq_len, seq_len): already in the layout``torch.nn.functional.scaled_dot_product_attention`` expects.+ The last dimension of every form is the ``seq_len`` keys, and in a 3-D or 4-D mask the one before+ it is the ``seq_len`` queries or 1, which shares the key mask across the queries; other sizes raise.A query row whose mask is entirely ``0`` follows the behavior of``scaled_dot_product_attention`` for a fully masked row: ``0`` on PyTorch 2.5 and later,``nan`` before it.@@ -135,6 +137,20 @@ class SigLip2Attention(nn.Module):attn_mask = attention_mask.bool()else:raise ValueError(f"Unsupported attention_mask dimension: {attention_mask.dim()}")+ # A key dimension of 1 would broadcast one value over every token: the same as no mask on the CPU, and+ # SDPA's unrelated "last dimension must be contiguous" error in CUDA float32 and half.+ sizes: list[Optional[int]] = [None] * attention_mask.dim()+ sizes[-1] = seq_len+ if attention_mask.dim() > 2:+ sizes[-2] = 1 if attention_mask.shape[-2] == 1 else seq_len+ KORNIA_CHECK_SIZES(+ attention_mask,+ sizes,+ lambda: (+ f"SigLip2Attention reads an attention mask over the {seq_len} tokens: the keys are its last "+ f"dimension, and in a 3-D or 4-D mask the queries, {seq_len} or 1, the one before it."+ ),+ )dropout_p = self.dropout.p if self.training and self.dropout.p > 0.0 else 0.0attention_output = F.scaled_dot_product_attention(diff --git a/tests/models/test_kimi_vl.py b/tests/models/test_kimi_vl.pyindex efa93639e..2701ab645 100644--- a/tests/models/test_kimi_vl.py+++ b/tests/models/test_kimi_vl.py@@ -21,7 +21,7 @@ import pytestimport torchimport kornia.models.kimi_vl.builder as kimi_vl_builder-from kornia.core.exceptions import BaseError+from kornia.core.exceptions import BaseError, ShapeErrorfrom kornia.models.kimi_vl import KimiVLBuilder, KimiVLConfig, KimiVLModelfrom kornia.models.kimi_vl.config import KimiVLProjectorConfig, MoonViTConfigfrom kornia.models.kimi_vl.model import KimiVLProjector@@ -412,6 +412,33 @@ class TestKimiVLComponents(BaseTester):with torch.no_grad(), pytest.raises(BaseError, match=r"leading dimension .* pass it as 4-D"):attention(x, cos, sin, attention_mask=mask)+ @pytest.mark.parametrize("module", ["attention", "encoder"])+ @pytest.mark.parametrize("mask_shape", [(2, 1), (2, 16, 1), (2, 1, 16, 1), (2, 1, 1, 1), (2, 3, 16)])+ def test_moonvit_mask_covers_every_patch(self, device, dtype, config, module, mask_shape):+ # A key dimension of 1 broadcast one value over all N patches: on the CPU and in CUDA float64 such a mask was+ # the same as no mask, and in CUDA float32 and half it raised SDPA's "last dimension must be contiguous". A+ # query dimension that is neither 1 nor N raised SDPA's broadcasting error. Both raise naming the patch count.+ net = (MoonViTAttention if module == "attention" else MoonViTEncoder)(config.vision_config)+ net = net.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(ShapeError, match=r"16 patches"):+ net(x, cos, sin, attention_mask=mask)++ def test_moonvit_attention_three_dim_mask_broadcasts_over_the_queries(self, device, dtype, config):+ # A (B, 1, N) mask is a per-sample key mask shared by every query, the 3-D form of a (B, N) padding mask.+ 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++ with torch.no_grad():+ self.assert_close(+ attention(x, cos, sin, attention_mask=mask[:, None]), 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.diff --git a/tests/models/test_siglip2.py b/tests/models/test_siglip2.pyindex 0a80939ff..81921a9bc 100644--- a/tests/models/test_siglip2.py+++ b/tests/models/test_siglip2.py@@ -26,7 +26,7 @@ import torchimport korniaimport kornia.models.siglip2.builder as siglip2_builder-from kornia.core.exceptions import BaseError+from kornia.core.exceptions import BaseError, ShapeErrorfrom kornia.models.siglip2 import SigLip2Builder, SigLip2Config, SigLip2Model, SigLip2Resultfrom kornia.models.siglip2.attention import SigLip2Attentionfrom kornia.models.siglip2.config import SigLip2TextConfig, SigLip2VisionConfig@@ -890,6 +890,30 @@ class TestSigLip2Components(BaseTester):tol = {"rtol": 5e-2, "atol": 5e-2} if dtype in (torch.float16, torch.bfloat16) else {}self.assert_close(output, output_without_mask, **tol)+ @pytest.mark.parametrize("mask_shape", [(2, 1), (2, 10, 1), (2, 1, 10, 1), (2, 1, 1, 1), (2, 3, 10)])+ def test_attention_mask_covers_every_token(self, device, dtype, mask_shape):+ # A key dimension of 1 broadcast one value over all tokens: on the CPU and in CUDA float64 such a mask was the+ # same as no mask, and in CUDA float32 and half it raised SDPA's "last dimension must be contiguous". A query+ # dimension that is neither 1 nor the sequence length raised SDPA's broadcasting error.+ attention = SigLip2Attention(hidden_size=32, num_heads=4).to(device, dtype).eval()+ hidden_states = torch.randn(2, 10, 32, device=device, dtype=dtype)+ mask = torch.ones(mask_shape, dtype=torch.bool, device=device)++ with torch.no_grad(), pytest.raises(ShapeError, match=r"10 tokens"):+ attention(hidden_states, attention_mask=mask)++ def test_attention_three_dim_mask_broadcasts_over_the_queries(self, device, dtype):+ # A (B, 1, N) mask is a per-sample key mask shared by every query, the 3-D form of a (B, N) padding mask.+ attention = SigLip2Attention(hidden_size=32, num_heads=4).to(device, dtype).eval()+ hidden_states = torch.randn(2, 10, 32, device=device, dtype=dtype)+ mask = torch.ones(2, 10, dtype=torch.bool, device=device)+ mask[1, 5:] = False++ with torch.no_grad():+ self.assert_close(+ attention(hidden_states, attention_mask=mask[:, None]), attention(hidden_states, attention_mask=mask)+ )+@pytest.mark.parametrize(("batch_size", "input_size"),[