π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
Fix PyTorch 2.1-2.4 compatibility failures (#4043)
Dmytro Mishkina6401efa60dd
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 4a3c4354a..e0c74c4de 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -25,6 +25,30 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0### Bug fixes+* Fix the inverted `SigLip2` attention-mask polarity, so every call that passes an `attention_mask` changes (#4043).+ All three mask branches of `SigLip2Attention` (2-D `(B, N)`, 3-D `(B, N, N)` and 4-D `(B, 1, N, N)`) negated the+ mask before handing it to `torch.nn.functional.scaled_dot_product_attention`, whose boolean form reads `True` as+ *attend*, not as *mask out*. Every position the caller asked to attend to was masked out and every padded position+ attended to, so an all-ones mask left every query row fully masked. The symptom is version-dependent because a+ fully masked row returns `0` from SDPA on PyTorch 2.5 and later and `nan` on PyTorch 2.4 and earlier:+ `SigLip2.get_text_features(..., attention_mask=...)` has been returning a zeroed attention output on current+ PyTorch and `nan` text features on the declared `torch>=2.0` floor. 2-D padding masks are now broadcast over the+ key axis only, matching `SiglipTextTransformer.create_bidirectional_mask` in Hugging Face `transformers`, so a+ partially padded sequence no longer produces a fully masked row. A row whose mask is entirely zero β an empty+ caption in a batch β is still fully masked and still follows the SDPA behavior above.++* Fix `find_essential` and `run_5point` raising `TypeError: all() received an invalid combination of arguments` on+ PyTorch before 2.2 (#4043). `run_5point`, `_solve_2x2_tikhonov_safe` and the scripted Nister helper each reduced+ over two axes at once with `Tensor.any(dim=(-2, -1))` / `Tensor.all(dim=(-1, -2))`, and multi-dimension `any`/`all`+ only landed in PyTorch 2.2, so the whole five-point solver was unusable on the declared `torch>=2.0` floor. The+ reductions now flatten the two trailing axes first, which is equivalent on every version.++* Fix `torch.jit.script` of `rgb_to_yuv`, `yuv_to_rgb`, `rgb_to_xyz` and `xyz_to_rgb` on older PyTorch (#4043). Their+ shared `kornia.color.utils._apply_linear_transformation` helper annotated its optional argument with the PEP 604+ `torch.Tensor | None` form, which the TorchScript compiler on the declared floor does not accept (reproduced on+ PyTorch 2.1.2, while PyTorch 2.9.1 compiles it), so scripting any of the four conversions failed. The annotation is+ `Optional[torch.Tensor]` now, which every supported version accepts.+* Define singleton pixel axes at normalized center, reject non-positive normalization sizes, preserve empty warpdestinations, and deprecate the now-unused `eps` normalization parameters (#4006). The four`{de,}normalize_pixel_coordinates{,3d}` helpers and `normal_transform_pixel{,3d}` now derive their scale from thediff --git a/kornia/color/utils.py b/kornia/color/utils.pyindex 437648584..ccd85262d 100644--- a/kornia/color/utils.py+++ b/kornia/color/utils.py@@ -15,12 +15,14 @@# limitations under the License.#+from typing import Optional+import torchfrom torch.nn import functional as Fdef _apply_linear_transformation(- image: torch.Tensor, kernel: torch.Tensor, bias: torch.Tensor | None = None+ image: torch.Tensor, kernel: torch.Tensor, bias: Optional[torch.Tensor] = None) -> torch.Tensor:"""Apply a 3x3 linear color transformation with device-aware optimization.diff --git a/kornia/geometry/epipolar/essential.py b/kornia/geometry/epipolar/essential.pyindex 386761233..92ba2ddbf 100644--- a/kornia/geometry/epipolar/essential.py+++ b/kornia/geometry/epipolar/essential.py@@ -72,7 +72,7 @@ def run_5point(points1: torch.Tensor, points2: torch.Tensor, weights: Optional[tX = torch.cat([x1 * x2, x1 * y2, x1, y1 * x2, y1 * y2, y1, x2, y2, ones], dim=-1)# use Nister's 5PC to solve essential matrixE = null_to_Nister_solution(X, batch_size)- bad = torch.isnan(E).all(dim=(-1, -2)).all(dim=-1) # (B,)+ bad = torch.isnan(E).flatten(-2).all(-1).all(-1) # (B,)if bad.any():eye3 = torch.eye(3, device=E.device, dtype=E.dtype).view(1, 1, 3, 3).expand(batch_size, 10, 3, 3)E = torch.where(bad.view(batch_size, 1, 1, 1), eye3, E)@@ -180,7 +180,7 @@ def _solve_2x2_tikhonov_safe(A: torch.Tensor, b: torch.Tensor, eps: float = 1e-1x = torch.where(bad.unsqueeze(-1).unsqueeze(-1), x_fb, x_dir)# if still non-finite, mark bad and zero it- nonfinite = torch.isnan(x).any(dim=(-2, -1)) | torch.isinf(x).any(dim=(-2, -1))+ nonfinite = torch.isnan(x).flatten(-2).any(-1) | torch.isinf(x).flatten(-2).any(-1)bad = bad | nonfinitex = torch.where(bad.unsqueeze(-1).unsqueeze(-1), torch.zeros_like(x), x)@@ -275,7 +275,7 @@ def _null_to_Nister_solution_script(eliminated = torch.linalg.solve(A10, b_poly) # (B,10,10)# Detect NaN/Inf from singular solve and fix with damping solve- bad = torch.isnan(eliminated).any(dim=(-2, -1)) | torch.isinf(eliminated).any(dim=(-2, -1)) # (B,)+ bad = torch.isnan(eliminated).flatten(-2).any(-1) | torch.isinf(eliminated).flatten(-2).any(-1) # (B,)if bad.any():# Damped solve only for bad rows but WITHOUT compaction:# build damped A = A10 + Ξ»I, where Ξ» depends on scalediff --git a/kornia/models/siglip2/attention.py b/kornia/models/siglip2/attention.pyindex 4ec629b86..d3273310a 100644--- a/kornia/models/siglip2/attention.py+++ b/kornia/models/siglip2/attention.py@@ -82,10 +82,20 @@ class SigLip2Attention(nn.Module):Args:hidden_states: Input tensor of shape (batch_size, seq_len, hidden_size).- attention_mask: Optional attention mask. Can be:- - (batch_size, seq_len): 1D mask where 1 = attend, 0 = mask- - (batch_size, seq_len, seq_len): 2D mask where 1 = attend, 0 = mask- - (batch_size, 1, seq_len, seq_len): 4D mask (broadcastable)+ attention_mask: Optional attention mask, where ``1``/``True`` means attend and ``0``/``False``+ means mask out. Can be:++ - (batch_size, seq_len): a padding mask, broadcast over the key axis only, matching+ ``SiglipTextTransformer.create_bidirectional_mask`` in Hugging Face ``transformers``.+ A padded query row is therefore *not* masked and its output is finite but meaningless;+ callers are expected to discard those positions.+ - (batch_size, seq_len, seq_len): a per-query mask, broadcast over the head axis.+ - (batch_size, 1, seq_len, seq_len): already in the layout+ ``torch.nn.functional.scaled_dot_product_attention`` expects.++ 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.Returns:Output tensor of shape (batch_size, seq_len, hidden_size).@@ -112,19 +122,17 @@ class SigLip2Attention(nn.Module):if attention_mask is not None:# Handle different mask formatsif attention_mask.dim() == 2:- # (batch_size, seq_len) -> (batch_size, 1, seq_len, seq_len)- # Create 2D mask: both query and key positions must be valid- # Convert to boolean: 1 = attend (False = don't mask), 0 = mask (True = mask out)- mask_bool = attention_mask.bool()- # Expand to (batch_size, 1, seq_len, seq_len) where True means mask out- # We need: if either query or key is masked, then mask that attention- attn_mask = ~(mask_bool.unsqueeze(1).unsqueeze(2) & mask_bool.unsqueeze(1).unsqueeze(3))+ # (batch_size, seq_len) -> (batch_size, 1, 1, seq_len)+ # Mask keys only so padded query positions do not create fully masked+ # rows, which produce NaNs in older SDPA implementations.+ # Boolean SDPA masks use True = attend and False = mask out.+ attn_mask = attention_mask.bool().unsqueeze(1).unsqueeze(2)elif attention_mask.dim() == 3:# (batch_size, seq_len, seq_len) -> (batch_size, 1, seq_len, seq_len)- attn_mask = ~attention_mask.bool().unsqueeze(1)+ attn_mask = attention_mask.bool().unsqueeze(1)elif attention_mask.dim() == 4:- # Already in correct format (batch_size, 1, seq_len, seq_len)- attn_mask = ~attention_mask.bool()+ # Already in the SDPA layout (batch_size, 1, seq_len, seq_len); True = attend+ attn_mask = attention_mask.bool()else:raise ValueError(f"Unsupported attention_mask dimension: {attention_mask.dim()}")diff --git a/testing/base.py b/testing/base.pyindex 66d99e215..fe140eaff 100644--- a/testing/base.py+++ b/testing/base.py@@ -33,12 +33,26 @@ from kornia.core._compat import torch_version_ltDtype = Union[torch.dtype, None]Tensor = torch.Tensor-DYNAMO_UNAVAILABLE_REASON = "torch.compile requires torch>=2.6 on Python>=3.13"+DYNAMO_UNAVAILABLE_REASON = "torch.compile requires torch>=2.4 on Python>=3.12 and torch>=2.6 on Python>=3.13"+DYNAMIC_EXPORT_UNAVAILABLE_REASON = (+ f"named torch.export dynamic shapes require torch>=2.2, and {DYNAMO_UNAVAILABLE_REASON}"+)def dynamo_is_available() -> bool:"""Return whether this Torch/Python pair can run Dynamo-backed capture."""- return not (torch_version_lt(2, 6, 0) and sys.version_info >= (3, 13))+ return not (+ (torch_version_lt(2, 4, 0) and sys.version_info >= (3, 12))+ or (torch_version_lt(2, 6, 0) and sys.version_info >= (3, 13))+ )+++def dynamic_export_is_available() -> bool:+ """Return whether ``torch.export`` accepts named dynamic shapes on this Torch/Python pair.++ ``torch.export.Dim`` and the ``dynamic_shapes`` argument both landed in PyTorch 2.2.+ """+ return dynamo_is_available() and hasattr(getattr(torch, "export", None), "Dim")# {dtype: (rtol, atol)}diff --git a/tests/augmentation/test_base.py b/tests/augmentation/test_base.pyindex ac8f067f7..ca94744d8 100644--- a/tests/augmentation/test_base.py+++ b/tests/augmentation/test_base.py@@ -26,6 +26,7 @@ from kornia.augmentation._2d.intensity.gaussian_blur import RandomGaussianBlurfrom kornia.augmentation._3d.geometric.affine import RandomAffine3Dfrom kornia.augmentation._3d.intensity.motion_blur import RandomMotionBlur3Dfrom kornia.augmentation.base import _BasicAugmentationBase+from kornia.core._compat import torch_version_ltfrom testing.base import BaseTester@@ -223,6 +224,8 @@ class TestIntensityAugmentationBase3D:def test_autocast(self, batch_prob, device, dtype):if not hasattr(torch, "autocast"):pytest.skip("PyTorch version without autocast support")+ if device.type == "cpu" and torch_version_lt(2, 3, 0):+ pytest.skip("3D CPU autocast requires bfloat16 eye support from PyTorch 2.3")# Uses some subclass of `IntensityAugmentationBase3D` which perform some op which can mismatch the dtype# Will cover RigidAffineAugmentationBase3D and AugmentationBase3D too@@ -244,6 +247,8 @@ class TestGeometricAugmentationBase3D:def test_autocast(self, batch_prob, device, dtype):if not hasattr(torch, "autocast"):pytest.skip("PyTorch version without autocast support")+ if device.type == "cpu" and torch_version_lt(2, 3, 0):+ pytest.skip("3D CPU autocast requires bfloat16 eye support from PyTorch 2.3")# Uses some subclass of `GeometricAugmentationBase3D` which perform some op which can mismatch the dtype# Will cover RigidAffineAugmentationBase3D and AugmentationBase3D toodiff --git a/tests/augmentation/test_onnx_export.py b/tests/augmentation/test_onnx_export.pyindex a44abe650..94c95c8b1 100644--- a/tests/augmentation/test_onnx_export.py+++ b/tests/augmentation/test_onnx_export.py@@ -54,6 +54,11 @@ import pytestimport torchimport kornia.augmentation as K+from kornia.core._compat import torch_version_ge, torch_version_lt++pytestmark = pytest.mark.skipif(+ torch_version_lt(2, 4, 0), reason="augmentation ONNX regression tests require opset 20 support from PyTorch 2.4"+)def _hflip() -> torch.nn.Module:@@ -158,21 +163,25 @@ EXPORTABLE_OPS: list[Tuple[str, Callable[[], torch.nn.Module]]] = [XFAIL_OPS: list[Tuple[str, Callable[[], torch.nn.Module], str]] = []+def _legacy_onnx_export(module: torch.nn.Module, x: torch.Tensor, buf: io.BytesIO) -> None:+ """Export through the legacy tracer across supported PyTorch versions."""+ kwargs: dict[str, Any] = {+ "opset_version": 20,+ "input_names": ["input"],+ "output_names": ["output"],+ }+ if torch_version_ge(2, 5, 0):+ kwargs["dynamo"] = False+ torch.onnx.export(module, (x,), buf, **kwargs)++def _try_export(module: torch.nn.Module, x: torch.Tensor) -> int:"""Run ``torch.onnx.export`` against an in-memory buffer and return the byte count."""module.eval()buf = io.BytesIO()with warnings.catch_warnings():warnings.simplefilter("ignore")- torch.onnx.export(- module,- (x,),- buf,- opset_version=20,- input_names=["input"],- output_names=["output"],- dynamo=False,- )+ _legacy_onnx_export(module, x, buf)return len(buf.getvalue())@@ -293,15 +302,7 @@ def _run_onnx(module: torch.nn.Module, x: torch.Tensor) -> Any:buf = io.BytesIO()with warnings.catch_warnings():warnings.simplefilter("ignore")- torch.onnx.export(- module,- (x,),- buf,- opset_version=20,- dynamo=False,- input_names=["input"],- output_names=["output"],- )+ _legacy_onnx_export(module, x, buf)sess = ort.InferenceSession(buf.getvalue())return sess.run(["output"], {"input": x.numpy()})[0]diff --git a/tests/geometry/test_conversions.py b/tests/geometry/test_conversions.pyindex 986d84bec..4154fc74b 100644--- a/tests/geometry/test_conversions.py+++ b/tests/geometry/test_conversions.py@@ -30,7 +30,7 @@ import pytestimport torchimport kornia-from kornia.core._compat import torch_version+from kornia.core._compat import torch_version, torch_version_ltfrom kornia.core.check import KORNIA_CHECK, KORNIA_CHECK_SHAPEfrom kornia.core.exceptions import BaseError, ShapeErrorfrom kornia.core.ops import eye_like@@ -50,7 +50,14 @@ from kornia.geometry.conversions import ()from kornia.geometry.quaternion import Quaternion-from testing.base import DYNAMO_UNAVAILABLE_REASON, BaseTester, assert_close, dynamo_is_available+from testing.base import (+ DYNAMIC_EXPORT_UNAVAILABLE_REASON,+ DYNAMO_UNAVAILABLE_REASON,+ BaseTester,+ assert_close,+ dynamic_export_is_available,+ dynamo_is_available,+)@pytest.fixture(autouse=True)@@ -3304,9 +3311,13 @@ def test_wart_float16_underflowed_default_eps_flips_branches(device):# -> 0.0 (not sqrt(eps) = 1e-4: eps underflows the sum inside the sqrt)# convert_points_from_homogeneous(torch.tensor([[2., 4., 2e-8]], dtype=torch.float16))# -> [[2., 4.]] (w underflows to 0 and takes the abs(w) <= eps passthrough branch)- zero = torch.tensor(0.0, device=device, dtype=torch.float16)- rho = kornia.geometry.conversions.cart2pol(zero, zero)[0]- assert_close(rho, zero, atol=0.0, rtol=0.0)+ # The cart2pol half is narrowed rather than skipped whole: it reaches torch.atan2, whose CPU+ # float16 kernel ("atan2_cpu" not implemented for 'Half') only landed in PyTorch 2.2, while the+ # convert_points_from_homogeneous claim below has no such floor and stays pinned everywhere.+ if not (device.type == "cpu" and torch_version_lt(2, 2, 0)):+ zero = torch.tensor(0.0, device=device, dtype=torch.float16)+ rho = kornia.geometry.conversions.cart2pol(zero, zero)[0]+ assert_close(rho, zero, atol=0.0, rtol=0.0)out = kornia.geometry.conversions.convert_points_from_homogeneous(torch.tensor([[2.0, 4.0, 2e-8]], device=device, dtype=torch.float16)@@ -3503,7 +3514,7 @@ def test_pixel_coordinate_singleton_policy_scripts(op_name, args, device, dtype)("denormalize_pixel_coordinates3d", 3),],)[email protected](not dynamo_is_available(), reason=DYNAMO_UNAVAILABLE_REASON)[email protected](not dynamic_export_is_available(), reason=DYNAMIC_EXPORT_UNAVAILABLE_REASON)def test_pixel_coordinate_export_crosses_singleton_boundary(op_name, ndim):op = getattr(kornia.geometry.conversions, op_name)@@ -3538,6 +3549,7 @@ def test_pixel_coordinate_export_crosses_singleton_boundary(op_name, ndim):("normal_transform_pixel3d", (4, 5, 6)),],)[email protected](not dynamo_is_available(), reason=DYNAMO_UNAVAILABLE_REASON)def test_non_default_eps_does_not_break_fullgraph_compile(op_name, sizes):op = getattr(kornia.geometry, op_name)value = torch.zeros(1, len(sizes))@@ -3568,7 +3580,7 @@ def test_non_default_eps_does_not_break_fullgraph_compile(op_name, sizes):],ids=["float32", "bfloat16-rounding-boundary", "float16-rounding-boundary"],)[email protected](not dynamo_is_available(), reason=DYNAMO_UNAVAILABLE_REASON)[email protected](not dynamic_export_is_available(), reason=DYNAMIC_EXPORT_UNAVAILABLE_REASON)def test_normal_transform_export_crosses_singleton_boundary(is_3d, dtype, runtime_sizes):class ExportTransform(torch.nn.Module):def forward(self, image):diff --git a/tests/geometry/test_grid.py b/tests/geometry/test_grid.pyindex 13bd745f8..6b54bc4b1 100644--- a/tests/geometry/test_grid.py+++ b/tests/geometry/test_grid.py@@ -20,7 +20,13 @@ import torchimport kornia-from testing.base import DYNAMO_UNAVAILABLE_REASON, assert_close, dynamo_is_available+from testing.base import (+ DYNAMIC_EXPORT_UNAVAILABLE_REASON,+ DYNAMO_UNAVAILABLE_REASON,+ assert_close,+ dynamic_export_is_available,+ dynamo_is_available,+)def test_create_meshgrid(device, dtype):@@ -169,7 +175,7 @@ def test_normalized_meshgrid_trace_matches_eager_at_unrepresentable_sizes(is_3d,@pytest.mark.parametrize("normalized_coordinates", [False, True], ids=["pixel", "normalized"])@pytest.mark.parametrize("is_3d", [False, True], ids=["2d", "3d"])[email protected](not dynamo_is_available(), reason=DYNAMO_UNAVAILABLE_REASON)[email protected](not dynamic_export_is_available(), reason=DYNAMIC_EXPORT_UNAVAILABLE_REASON)def test_meshgrid_export_crosses_singleton_boundary(is_3d, normalized_coordinates):class MeshGrid(torch.nn.Module):def forward(self, image):@@ -203,6 +209,7 @@ def test_meshgrid_export_crosses_singleton_boundary(is_3d, normalized_coordinate@pytest.mark.parametrize("default_dtype", [torch.float32, torch.float64])@pytest.mark.parametrize("is_3d", [False, True], ids=["2d", "3d"])[email protected](not dynamo_is_available(), reason=DYNAMO_UNAVAILABLE_REASON)def test_pixel_meshgrid_default_dtype_matches_compile(is_3d, default_dtype):class MeshGrid(torch.nn.Module):def forward(self, image):diff --git a/tests/geometry/test_linalg.py b/tests/geometry/test_linalg.pyindex 83375bd9e..f6dec142b 100644--- a/tests/geometry/test_linalg.py+++ b/tests/geometry/test_linalg.py@@ -20,6 +20,7 @@ import torchimport korniaimport kornia.geometry.linalg as kgl+from kornia.core._compat import torch_version_ltfrom testing.base import BaseTesterfrom testing.geometry.create import create_random_homography@@ -81,6 +82,10 @@ class TestTransformPoints(BaseTester):@pytest.mark.parametrize("points_dtype", [torch.float16, torch.float32, torch.float64])def test_mixed_dtypes(self, device, trans_dtype, points_dtype):# Regression test for https://github.com/kornia/kornia/issues/3705+ if trans_dtype == torch.float16 and device.type == "cpu" and torch_version_lt(2, 2, 0):+ # transform_points harmonises at the bmm site in the transform's dtype, and CPU+ # float16 bmm ("bmm" not implemented for 'Half') only landed in PyTorch 2.2.+ pytest.skip("CPU float16 bmm requires PyTorch 2.2")points_src = torch.rand(2, 3, 2, device=device, dtype=points_dtype)trans = kornia.core.ops.eye_like(3, points_src).to(trans_dtype)out = kgl.transform_points(trans, points_src)diff --git a/tests/models/test_siglip2.py b/tests/models/test_siglip2.pyindex e6539c73e..d2c217ab2 100644--- a/tests/models/test_siglip2.py+++ b/tests/models/test_siglip2.py@@ -126,6 +126,7 @@ class TestSigLip2Model(BaseTester):features = model.get_text_features(input_ids, attention_mask=attention_mask)assert features.shape == (batch_size, config.projection_dim)+ assert torch.isfinite(features).all()# Check normalizationnorms = features.norm(dim=-1)self.assert_close(norms, torch.ones_like(norms), rtol=1e-5, atol=1e-5)@@ -135,7 +136,9 @@ class TestSigLip2Model(BaseTester):batch_size = 2seq_len = 10- input_ids = _create_input_ids(batch_size, seq_len, config, device)+ input_ids = torch.zeros(batch_size, seq_len, dtype=torch.long, device=device)+ input_ids[0, :5] = torch.arange(1, 6, device=device)+ input_ids[1, :8] = torch.arange(11, 19, device=device)# Create attention mask with different lengthsattention_mask = torch.ones(batch_size, seq_len, device=device)@@ -146,6 +149,8 @@ class TestSigLip2Model(BaseTester):features = model.get_text_features(input_ids, attention_mask=attention_mask)assert features.shape == (batch_size, config.projection_dim)+ assert torch.isfinite(features).all()+ assert not torch.allclose(features[0], features[1])def test_return_loss(self, device, dtype, model, config):"""Test forward pass with return_loss=True and verify logit_scale clamping."""@@ -336,9 +341,15 @@ class TestSigLip2Components(BaseTester):with torch.no_grad():output = attention(hidden_states, attention_mask=attention_mask)+ output_without_mask = attention(hidden_states)# Attention returns a single tensor, not a tupleassert output.shape == (batch_size, seq_len, hidden_size)+ # An all-ones mask must be a no-op. Passing any ``attn_mask`` disqualifies the CUDA flash+ # backend, so the two calls can run different SDPA kernels and agree only up to kernel-level+ # rounding, which is the same order as the default half-precision tolerance.+ 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("batch_size", [1, 2, 4])@pytest.mark.parametrize("input_size", [(256, 256), (300, 400), (512, 512)])