π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
fix(core): avoid the faulty Windows SDPA kernel in all attention callers (#6613)
Dmytro Mishkin764c4d8371ea
diff --git a/changelog.d/6613.fixed.md b/changelog.d/6613.fixed.mdnew file mode 100644index 000000000..89acc1dab--- /dev/null+++ b/changelog.d/6613.fixed.md@@ -0,0 +1 @@+On Windows with PyTorch older than 2.6, float64 attention on the CPU in SigLip2, Kimi-VL, PaliGemma and the Qwen2.5 vision encoder no longer returns NaNs or wrong values from PyTorch's faulty fused kernel. LightGlue already avoided it.diff --git a/kornia/core/_compat.py b/kornia/core/_compat.pyindex 29b6e037f..a11115af9 100644--- a/kornia/core/_compat.py+++ b/kornia/core/_compat.py@@ -16,12 +16,14 @@#+import sysimport warningsfrom functools import wrapsfrom inspect import isclass, isfunctionfrom typing import Any, Callable, Optional, Tuple, castimport torch+import torch.nn.functional as Fdef torch_version() -> str:@@ -128,6 +130,61 @@ def torch_version_ge(major: int, minor: int, patch: Optional[int] = None) -> booreturn _TORCH_VERSION >= (major, minor, patch)+# The fused CPU kernel of torch 2.5 on Windows can return NaNs or wrong finite values for valid float64 inputs (#5992).+_SDPA_FLOAT64_CPU_KERNEL_IS_FAULTY: bool = sys.platform == "win32" and torch_version_lt(2, 6, 0)+++def scaled_dot_product_attention(+ query: torch.Tensor,+ key: torch.Tensor,+ value: torch.Tensor,+ attn_mask: Optional[torch.Tensor] = None,+ dropout_p: float = 0.0,+ is_causal: bool = False,+ scale: Optional[float] = None,+ kernel_is_faulty: bool = _SDPA_FLOAT64_CPU_KERNEL_IS_FAULTY,+) -> torch.Tensor:+ """Compute scaled dot-product attention around the faulty float64 kernel of torch 2.5 on Windows.++ Takes the arguments of :func:`torch.nn.functional.scaled_dot_product_attention` and returns its result. Kornia calls+ this instead of the torch function, which ``tests/core/test_compat.py`` enforces. On Windows with torch older than+ 2.6, a 4-D float64 query on the CPU would select a fused kernel that returns NaNs or wrong finite values, so it gets+ a singleton leading dimension: that kernel accepts only 4-D inputs, so torch takes its math implementation, without+ a process-wide backend flag or a context manager, which torch 2.5 cannot compile. The mask broadcasts as before.+ Every other input goes straight to the torch function.++ Args:+ query: Query tensor with shape ``(..., N_q, D)``.+ key: Key tensor with shape ``(..., N_k, D)``.+ value: Value tensor with shape ``(..., N_k, D_v)``.+ attn_mask: Optional mask broadcastable to ``(..., N_q, N_k)``.+ dropout_p: Dropout probability of the attention weights.+ is_causal: Whether to apply a causal mask, in which case ``attn_mask`` must be ``None``.+ scale: Scale of the scores, ``1 / sqrt(D)`` if ``None``.+ kernel_is_faulty: Whether this platform has the faulty kernel. A default argument and not a global read, because+ TorchScript cannot read a Python global. Leave the default.++ Returns:+ Attention output with shape ``(..., N_q, D_v)``.++ See Also:+ :func:`torch.nn.functional.scaled_dot_product_attention`: the function this calls, for the full contract.+ """+ if kernel_is_faulty and query.ndim == 4 and query.dtype == torch.float64 and query.device.type == "cpu":+ return F.scaled_dot_product_attention(+ query.unsqueeze(0),+ key.unsqueeze(0),+ value.unsqueeze(0),+ attn_mask=attn_mask,+ dropout_p=dropout_p,+ is_causal=is_causal,+ scale=scale,+ ).squeeze(0)+ return F.scaled_dot_product_attention(+ query, key, value, attn_mask=attn_mask, dropout_p=dropout_p, is_causal=is_causal, scale=scale+ )++def _emit_deprecation_warning(name: str, replace_with: Optional[str], version: Optional[str], extra_reason: Optional[str], stacklevel: int = 3) -> None:diff --git a/kornia/feature/dedode/transformer/layers/attention.py b/kornia/feature/dedode/transformer/layers/attention.pyindex 6237c63ba..adcd2f774 100644--- a/kornia/feature/dedode/transformer/layers/attention.py+++ b/kornia/feature/dedode/transformer/layers/attention.py@@ -25,9 +25,10 @@# https://github.com/facebookresearch/dino/blob/master/vision_transformer.py# https://github.com/rwightman/pytorch-image-models/tree/master/timm/models/vision_transformer.py-import torch.nn.functional as Ffrom torch import Tensor, nn+from kornia.core._compat import scaled_dot_product_attention+class Attention(nn.Module):"""Implement the standard Multi-Head Self-Attention mechanism.@@ -82,7 +83,7 @@ class Attention(nn.Module):x = attn @ velse:# softmax(q k^T * scale) v; the fused kernels do not materialise the N x N weights of every head.- x = F.scaled_dot_product_attention(q, k, v, scale=self.scale)+ x = scaled_dot_product_attention(q, k, v, scale=self.scale)x = x.transpose(1, 2).reshape(B, N, C)x = self.proj(x)return self.proj_drop(x)diff --git a/kornia/feature/lightglue.py b/kornia/feature/lightglue.pyindex 39b2e86ee..e95ef5243 100644--- a/kornia/feature/lightglue.py+++ b/kornia/feature/lightglue.py@@ -16,7 +16,6 @@#import math-import sysimport warningsfrom pathlib import Pathfrom types import SimpleNamespace@@ -26,7 +25,7 @@ import torchimport torch.nn.functional as Ffrom torch import nn-from kornia.core._compat import torch_version_lt+from kornia.core._compat import scaled_dot_product_attentionfrom kornia.core.check import KORNIA_CHECKfrom kornia.core.download import hf_url, load_state_dict_from_urlfrom kornia.core.exceptions import BaseError@@ -144,7 +143,6 @@ class Attention(nn.Module):def __init__(self, allow_flash: bool) -> None:super().__init__()self.allow_flash = allow_flash- self._windows_old_torch = sys.platform == "win32" and torch_version_lt(2, 6, 0)def forward(self, q: torch.Tensor, k: torch.Tensor, v: torch.Tensor, mask: Optional[torch.Tensor] = None@@ -167,17 +165,10 @@ class Attention(nn.Module):if self.allow_flash and q.device.type == "cuda":# use torch 2.0 scaled_dot_product_attention with flashargs = [x.half().contiguous() for x in [q, k, v]]- v = F.scaled_dot_product_attention(*args, attn_mask=mask).to(q.dtype) # type: ignore+ v = scaled_dot_product_attention(*args, attn_mask=mask).to(q.dtype) # type: ignorereturn v if mask is None else v.nan_to_num()args = [x.contiguous() for x in [q, k, v]]- if self._windows_old_torch and q.device.type == "cpu" and q.dtype == torch.float64 and q.ndim == 4:- # The Windows torch 2.5 CPU flash kernel can return NaNs or corrupt finite values for valid float64- # inputs. It only accepts 4D inputs: a singleton batch dimension selects math attention without changing- # process-global backend flags or using a context manager that torch 2.5 cannot compile.- q_, k_, v_ = (x.unsqueeze(0) for x in args)- v = F.scaled_dot_product_attention(q_, k_, v_, attn_mask=mask).squeeze(0)- else:- v = F.scaled_dot_product_attention(*args, attn_mask=mask) # type: ignore+ v = scaled_dot_product_attention(*args, attn_mask=mask) # type: ignorereturn v if mask is None else v.nan_to_num()diff --git a/kornia/models/kimi_vl/moonvit.py b/kornia/models/kimi_vl/moonvit.pyindex 3f1073d95..d0d8d9b99 100644--- a/kornia/models/kimi_vl/moonvit.py+++ b/kornia/models/kimi_vl/moonvit.py@@ -23,6 +23,7 @@ import torchimport torch.nn.functional as Ffrom torch import nn+from kornia.core._compat import scaled_dot_product_attentionfrom kornia.core.check import KORNIA_CHECK, KORNIA_CHECK_SIZESfrom .config import MoonViTConfig@@ -208,7 +209,7 @@ class MoonViTAttention(nn.Module):key = apply_rotary_pos_emb(key, cos, sin)if attention_mask is not None:attention_mask = _sdpa_attention_mask(attention_mask, batch_size, seq_len)- attn_output = F.scaled_dot_product_attention(+ attn_output = scaled_dot_product_attention(query, key, value, attn_mask=attention_mask, dropout_p=self.dropout.p if self.training else 0.0)diff --git a/kornia/models/paligemma/modeling_paligemma.py b/kornia/models/paligemma/modeling_paligemma.pyindex d2df3c7e6..7374962f0 100644--- a/kornia/models/paligemma/modeling_paligemma.py+++ b/kornia/models/paligemma/modeling_paligemma.py@@ -20,9 +20,9 @@ from __future__ import annotationsfrom typing import Optional, Tupleimport torch-import torch.nn.functional as Ffrom torch import nn+from kornia.core._compat import scaled_dot_product_attentionfrom kornia.models.siglip2.vision_encoder import SigLip2VisionModelfrom .configuration_paligemma import PaliGemmaConfig@@ -210,7 +210,7 @@ class GemmaAttention(nn.Module):key_states = torch.repeat_interleave(key_states, dim=1, repeats=self.num_key_value_groups)value_states = torch.repeat_interleave(value_states, dim=1, repeats=self.num_key_value_groups)- attn_output = F.scaled_dot_product_attention(+ attn_output = scaled_dot_product_attention(query_states,key_states,value_states,diff --git a/kornia/models/qwen25/vision.py b/kornia/models/qwen25/vision.pyindex d3fa10f39..df9f428e9 100644--- a/kornia/models/qwen25/vision.py+++ b/kornia/models/qwen25/vision.py@@ -32,6 +32,7 @@ import torchimport torch.nn.functional as Ffrom torch import nn+from kornia.core._compat import scaled_dot_product_attentionfrom kornia.core.safetensors import load_safetensorsfrom .config import Qwen25VisionConfig@@ -154,7 +155,7 @@ class Qwen25VisionAttention(nn.Module):qf, kf = q.to(compute_dtype), k.to(compute_dtype)q = (qf * cos + _rotate_half(qf) * sin).to(x.dtype)k = (kf * cos + _rotate_half(kf) * sin).to(x.dtype)- out = F.scaled_dot_product_attention(q, k, v, attn_mask=attn_mask)+ out = scaled_dot_product_attention(q, k, v, attn_mask=attn_mask)return self.proj(out.transpose(1, 2).reshape(b, n, d))diff --git a/kornia/models/siglip2/attention.py b/kornia/models/siglip2/attention.pyindex 1b4a46f73..d892e783c 100644--- a/kornia/models/siglip2/attention.py+++ b/kornia/models/siglip2/attention.py@@ -23,9 +23,9 @@ import mathfrom typing import Optionalimport torch-import torch.nn.functional as Ffrom torch import nn+from kornia.core._compat import scaled_dot_product_attentionfrom kornia.core.check import KORNIA_CHECK, KORNIA_CHECK_SIZES__all__ = ["SigLip2Attention"]@@ -153,7 +153,7 @@ class SigLip2Attention(nn.Module):)dropout_p = self.dropout.p if self.training and self.dropout.p > 0.0 else 0.0- attention_output = F.scaled_dot_product_attention(+ attention_output = scaled_dot_product_attention(query,key,value,diff --git a/tests/core/test_compat.py b/tests/core/test_compat.pyindex d03c2bc4e..e34212d32 100644--- a/tests/core/test_compat.py+++ b/tests/core/test_compat.py@@ -15,7 +15,7 @@# limitations under the License.#-"""Tests for the ``kornia.core._compat.deprecated`` decorator."""+"""Tests for ``kornia.core._compat``: the ``deprecated`` decorator and the attention helper."""from __future__ import annotations@@ -25,15 +25,24 @@ import enumimport functoolsimport inspectimport pickle+import reimport warningsfrom contextlib import contextmanager+from pathlib import Pathfrom typing import Any, Iterator, Selfimport pytestimport torch+import korniaimport kornia.utils-from kornia.core._compat import deprecated+from kornia.core._compat import deprecated, scaled_dot_product_attention+from kornia.feature.dedode.transformer.layers.attention import Attention as DeDoDeAttention+from kornia.models.paligemma.configuration_paligemma import PaliGemmaConfig+from kornia.models.paligemma.modeling_paligemma import GemmaAttention+from kornia.models.qwen25.vision import Qwen25VisionAttention++from testing.base import BaseTester_HEAD = "Since kornia 0.8.3 the `old` is deprecated in favor of `new`."@@ -833,3 +842,118 @@ class TestDeprecatedClassLimits:with _caught() as caught, pytest.raises(TypeError, match=r"Point\(\) takes no arguments"):Point(1)assert len(caught) == 1+++class TestScaledDotProductAttention(BaseTester):+ """The helper that keeps kornia off the faulty float64 CPU kernel of torch 2.5 on Windows (#5992)."""++ @staticmethod+ def _simulate_the_fault(monkeypatch, faulty_platform: bool) -> list[int]:+ # Reproduce the kernel's fault on any host: a 4-D float64 CPU query gives NaN, as it selects the fused kernel.+ defaults = scaled_dot_product_attention.__defaults__+ monkeypatch.setattr(scaled_dot_product_attention, "__defaults__", (*defaults[:-1], faulty_platform))+ real = torch.nn.functional.scaled_dot_product_attention+ ndims = []++ def faulty(query, key, value, **kwargs):+ ndims.append(query.ndim)+ if query.ndim == 4 and query.dtype == torch.float64 and query.device.type == "cpu":+ return torch.full_like(query, float("nan"))+ return real(query, key, value, **kwargs)++ monkeypatch.setattr(torch.nn.functional, "scaled_dot_product_attention", faulty)+ return ndims++ @pytest.mark.parametrize("masked", [False, True])+ @pytest.mark.parametrize("scale", [None, 0.25])+ def test_faulty_kernel_is_avoided(self, device, monkeypatch, masked, scale):+ if device.type != "cpu":+ pytest.skip("the kernel is CPU-only")+ dtype = torch.float64+ q, k, v = (torch.rand(2, 3, 5, 8, device=device, dtype=dtype) for _ in range(3))+ mask = None+ scores = q @ k.transpose(-2, -1) * (8**-0.5 if scale is None else scale)+ if masked:+ mask = torch.rand(2, 3, 5, 5, device=device) > 0.5+ mask[..., 0] = True+ scores = scores.masked_fill(~mask, -torch.inf)+ expected = scores.softmax(-1) @ v+ self._simulate_the_fault(monkeypatch, faulty_platform=True)+ self.assert_close(scaled_dot_product_attention(q, k, v, attn_mask=mask, scale=scale), expected)++ @pytest.mark.parametrize(+ "faulty_platform, shape, dtype, expected_ndim",+ [+ (True, (1, 2, 3, 4), torch.float64, 5),+ (True, (1, 2, 3, 4), torch.float32, 4),+ (True, (2, 3, 4), torch.float64, 3),+ (False, (1, 2, 3, 4), torch.float64, 4),+ ],+ )+ def test_only_the_faulty_input_is_rerouted(self, device, monkeypatch, faulty_platform, shape, dtype, expected_ndim):+ if device.type != "cpu":+ pytest.skip("the kernel is CPU-only")+ ndims = self._simulate_the_fault(monkeypatch, faulty_platform)+ q = torch.rand(*shape, device=device, dtype=dtype)+ assert scaled_dot_product_attention(q, q, q).shape == q.shape+ assert ndims == [expected_ndim]++ def test_other_devices_are_not_rerouted(self, monkeypatch):+ ndims = self._simulate_the_fault(monkeypatch, faulty_platform=True)+ q = torch.empty(1, 2, 3, 4, device="meta", dtype=torch.float64)+ scaled_dot_product_attention(q, q, q)+ assert ndims == [4]++ @pytest.mark.parametrize("faulty_platform", [False, True])+ def test_options_reach_torch(self, monkeypatch, faulty_platform):+ self._simulate_the_fault(monkeypatch, faulty_platform)+ seen = []++ def spy(query, key, value, **kwargs):+ seen.append(kwargs)+ return query++ monkeypatch.setattr(torch.nn.functional, "scaled_dot_product_attention", spy)+ q = torch.rand(1, 2, 3, 4, dtype=torch.float64)+ mask = torch.ones(3, 3, dtype=torch.bool)+ scaled_dot_product_attention(q, q, q, attn_mask=mask, dropout_p=0.5, is_causal=True, scale=0.25)+ assert seen == [{"attn_mask": mask, "dropout_p": 0.5, "is_causal": True, "scale": 0.25}]++ @pytest.mark.parametrize(+ "make_module",+ [+ lambda: DeDoDeAttention(dim=16, num_heads=4),+ lambda: Qwen25VisionAttention(16, 4),+ lambda: GemmaAttention(PaliGemmaConfig(), 0),+ ],+ ids=["dedode", "qwen25", "gemma"],+ )+ def test_scripted_callers_compile(self, make_module):+ # TorchScript cannot read a Python global, whatever its value: the helper takes the flag as a default argument.+ torch.jit.script(make_module().eval())++ @pytest.mark.parametrize("faulty_platform", [False, True])+ def test_scripted_matches_eager(self, faulty_platform):+ # Pass the flag: TorchScript keeps the first compile of a function, so patching the default would not reach it.+ q, k, v = (torch.rand(2, 3, 5, 8, dtype=torch.float64) for _ in range(3))+ actual = torch.jit.script(scaled_dot_product_attention)(q, k, v, kernel_is_faulty=faulty_platform)+ self.assert_close(actual, scaled_dot_product_attention(q, k, v, kernel_is_faulty=faulty_platform))++ def test_gradcheck(self, device, monkeypatch):+ if device.type != "cpu":+ pytest.skip("the kernel is CPU-only")+ self._simulate_the_fault(monkeypatch, faulty_platform=True)+ q, k, v = (torch.rand(1, 1, 2, 4, device=device, dtype=torch.float64, requires_grad=True) for _ in range(3))+ self.gradcheck(scaled_dot_product_attention, (q, k, v))++ def test_kornia_calls_the_helper_rather_than_the_torch_function(self):+ # DeDoDe gained a direct call after LightGlue got the workaround, and the models had always had one: a CI leg+ # that needs Windows and torch 2.5, and runs only on the schedule, is too late and too far to catch the next.+ root = Path(kornia.__file__).parent+ pattern = re.compile(r"\b(F|functional)\.scaled_dot_product_attention\(")+ callers = [+ str(path.relative_to(root))+ for path in sorted(root.rglob("*.py"))+ if path.name != "_compat.py" and pattern.search(path.read_text(encoding="utf-8"))+ ]+ assert not callers, f"use kornia.core._compat.scaled_dot_product_attention in {callers}"diff --git a/tests/feature/test_lightglue.py b/tests/feature/test_lightglue.pyindex 668996472..7c4288c7d 100644--- a/tests/feature/test_lightglue.py+++ b/tests/feature/test_lightglue.py@@ -20,6 +20,7 @@ import unittest.mockimport pytestimport torch+from kornia.core._compat import scaled_dot_product_attentionfrom kornia.core.check import are_checks_enabled, disable_checks, enable_checksfrom kornia.core.exceptions import BaseErrorfrom kornia.feature.integrated import LightGlueMatcher@@ -219,11 +220,18 @@ def test_lightglue_leaves_global_flash_sdp_setting_alone(flash):# ---------------------------------------------------------------------------+def _simulate_faulty_platform(monkeypatch) -> None:+ defaults = scaled_dot_product_attention.__defaults__+ monkeypatch.setattr(scaled_dot_product_attention, "__defaults__", (*defaults[:-1], True))++class TestAttention(BaseTester):@pytest.mark.parametrize("batch_size", [1, 2])@pytest.mark.parametrize("legacy_windows", [False, True])@pytest.mark.parametrize("masked", [False, True])- def test_cpu_attention_matches_explicit_softmax_5992(self, device, dtype, batch_size, legacy_windows, masked):+ def test_cpu_attention_matches_explicit_softmax_5992(+ self, device, dtype, monkeypatch, batch_size, legacy_windows, masked+ ):if device.type != "cpu" or dtype not in (torch.float32, torch.float64):pytest.skip("regression for Windows CPU float64, with float32 as a control")g = torch.Generator().manual_seed(0)@@ -251,14 +259,14 @@ class TestAttention(BaseTester):attention = Attention(allow_flash=True)if legacy_windows:# Exercise the real fallback on every host, as well as the native platform selection above.- attention._windows_old_torch = True+ _simulate_faulty_platform(monkeypatch)backend_flags = (torch.backends.cuda.flash_sdp_enabled(),torch.backends.cuda.math_sdp_enabled(),torch.backends.cuda.mem_efficient_sdp_enabled(),torch.backends.cuda.cudnn_sdp_enabled(),)- with unittest.mock.patch("kornia.feature.lightglue.F.scaled_dot_product_attention", side_effect=legacy_sdpa):+ with unittest.mock.patch("kornia.core._compat.F.scaled_dot_product_attention", side_effect=legacy_sdpa):actual = attention(q, k, v, mask)assert actual.isfinite().all()self.assert_close(actual, expected)@@ -270,33 +278,33 @@ class TestAttention(BaseTester):)@pytest.mark.parametrize("masked", [False, True])- def test_windows_float64_fallback_gradcheck(self, device, masked):+ def test_windows_float64_fallback_gradcheck(self, device, monkeypatch, masked):if device.type != "cpu":pytest.skip("the fallback is CPU-only")+ _simulate_faulty_platform(monkeypatch)attention = Attention(allow_flash=True)- attention._windows_old_torch = Trueq, k, v = [torch.rand(1, 1, 2, 4, device=device, dtype=torch.float64, requires_grad=True) for _ in range(3)]mask = torch.tensor([[False, False], [True, True]], device=device) if masked else Noneself.gradcheck(lambda q, k, v: attention(q, k, v, mask), (q, k, v))- def test_dynamo_windows_float64_fallback(self, device, torch_optimizer, optimizer_backend):+ def test_dynamo_windows_float64_fallback(self, device, monkeypatch, torch_optimizer, optimizer_backend):if device.type != "cpu" or not optimizer_backend or optimizer_backend == "jit":pytest.skip("the fallback needs CPU torch.compile coverage")+ _simulate_faulty_platform(monkeypatch)attention = Attention(allow_flash=True)- attention._windows_old_torch = Trueq, k, v = [torch.rand(1, 1, 2, 4, device=device, dtype=torch.float64) for _ in range(3)]mask = torch.tensor([[False, False], [True, True]], device=device)compiled = torch_optimizer(attention, fullgraph=True)self.assert_close(compiled(q, k, v, mask), attention(q, k, v, mask))@pytest.mark.skipif(not dynamo_is_available(), reason="no Dynamo on this torch/python pair")- def test_eager_backend_traces_windows_float64_fallback(self, device):+ def test_eager_backend_traces_windows_float64_fallback(self, device, monkeypatch):# conftest deselects *dynamo* and *compile* tests unless KORNIA_TEST_OPTIMIZER is set, which CI does only on# torch 2.14. This name also runs on the scheduled torch 2.5.1 legs, where the fallback is live on Windows.if device.type != "cpu":pytest.skip("the fallback is CPU-only")+ _simulate_faulty_platform(monkeypatch)attention = Attention(allow_flash=True)- attention._windows_old_torch = Trueq, k, v = [torch.rand(1, 1, 2, 4, device=device, dtype=torch.float64) for _ in range(3)]mask = torch.tensor([[False, False], [True, True]], device=device)torch._dynamo.reset()