π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
test: fix false-red MPS coverage (#4147)
Dmytro Mishkindfad8156ef8e
diff --git a/testing/base.py b/testing/base.pyindex 228c6c83b..0d441c620 100644--- a/testing/base.py+++ b/testing/base.py@@ -137,7 +137,11 @@ def supports_2d_border_padding(device: torch.device) -> bool:return _supports_2d_border_padding_probe(device.type)-_UNIMPLEMENTED_KERNEL_MSG = "not implemented for"+_UNSUPPORTED_KERNEL_MSGS = (+ "not implemented for",+ "Unsupported Bicubic interpolation",+ "Unsupported Nearest interpolation",+)class _UnsupportedProbeDtype(Exception):@@ -169,15 +173,75 @@ def _supports_kernel_probe(op: Callable[[str, torch.dtype], object], device_type"""try:op(device_type, dtype)- except _UnsupportedProbeDtype:+ except (_UnsupportedProbeDtype, NotImplementedError):return Falseexcept RuntimeError as e:- if _UNIMPLEMENTED_KERNEL_MSG in str(e):+ if any(message in str(e) for message in _UNSUPPORTED_KERNEL_MSGS):return Falseraisereturn True+def _bilinear_2d_grid_sample_op(device_type: str, dtype: torch.dtype) -> None:+ inp = _probe_zeros(device_type, dtype, 1, 1, 2, 2)+ grid = _probe_zeros(device_type, dtype, 1, 1, 1, 2)+ F.grid_sample(inp, grid, mode="bilinear", align_corners=True)+++def supports_bilinear_2d_grid_sample(device: torch.device, dtype: torch.dtype) -> bool:+ """Whether this device supports bilinear interpolation in 2D ``grid_sample`` for ``dtype``.++ Probed at runtime and cached per (device type, dtype), so tests guarded by this helper+ auto-enable once PyTorch adds the missing interpolation kernel.+ """+ return _supports_kernel_probe(_bilinear_2d_grid_sample_op, device.type, dtype)+++def _bicubic_2d_grid_sample_op(device_type: str, dtype: torch.dtype) -> None:+ inp = _probe_zeros(device_type, dtype, 1, 1, 2, 2)+ grid = _probe_zeros(device_type, dtype, 1, 1, 1, 2)+ F.grid_sample(inp, grid, mode="bicubic", align_corners=True)+++def supports_bicubic_2d_grid_sample(device: torch.device, dtype: torch.dtype) -> bool:+ """Whether this device supports bicubic interpolation in 2D ``grid_sample`` for ``dtype``.++ Probed at runtime and cached per (device type, dtype), so tests guarded by this helper+ auto-enable once PyTorch adds the missing interpolation kernel.+ """+ return _supports_kernel_probe(_bicubic_2d_grid_sample_op, device.type, dtype)+++def _bilinear_3d_grid_sample_op(device_type: str, dtype: torch.dtype) -> None:+ inp = _probe_zeros(device_type, dtype, 1, 1, 2, 2, 2)+ grid = _probe_zeros(device_type, dtype, 1, 1, 1, 1, 3)+ F.grid_sample(inp, grid, mode="bilinear", align_corners=True)+++def supports_bilinear_3d_grid_sample(device: torch.device, dtype: torch.dtype) -> bool:+ """Whether this device supports bilinear interpolation in 3D ``grid_sample`` for ``dtype``.++ Probed at runtime and cached per (device type, dtype), so tests guarded by this helper+ auto-enable once PyTorch adds the missing interpolation kernel.+ """+ return _supports_kernel_probe(_bilinear_3d_grid_sample_op, device.type, dtype)+++def _nearest_3d_grid_sample_op(device_type: str, dtype: torch.dtype) -> None:+ inp = _probe_zeros(device_type, dtype, 1, 1, 2, 2, 2)+ grid = _probe_zeros(device_type, dtype, 1, 1, 1, 1, 3)+ F.grid_sample(inp, grid, mode="nearest", align_corners=True)+++def supports_nearest_3d_grid_sample(device: torch.device, dtype: torch.dtype) -> bool:+ """Whether this device supports nearest interpolation in 3D ``grid_sample`` for ``dtype``.++ Probed at runtime and cached per (device type, dtype), so tests guarded by this helper+ auto-enable once PyTorch adds the missing interpolation kernel.+ """+ return _supports_kernel_probe(_nearest_3d_grid_sample_op, device.type, dtype)++def _replicate_padding_op(device_type: str, dtype: torch.dtype) -> None:F.pad(_probe_zeros(device_type, dtype, 1, 1, 2, 2), (1, 1, 1, 1), mode="replicate")diff --git a/tests/augmentation/container/test_augmentation_sequential.py b/tests/augmentation/container/test_augmentation_sequential.pyindex 748eff744..6e02eb4f9 100644--- a/tests/augmentation/container/test_augmentation_sequential.py+++ b/tests/augmentation/container/test_augmentation_sequential.py@@ -112,6 +112,8 @@ class TestAugmentationSequential:def test_mixed_image_bbox_dtypes(self, device, image_dtype):# Regression test for https://github.com/kornia/kornia/issues/3705 and #3706:# bbox stays in fp32 while the image uses a half/double compute dtype.+ if device.type == "mps" and image_dtype == torch.float64:+ pytest.skip("MPS does not support float64")if device.type == "cpu" and image_dtype in (torch.float16, torch.bfloat16) and torch_version_lt(2, 6, 0):pytest.skip("PyTorch <2.6 has no CPU Half/BFloat16 grid_sample kernel")torch.manual_seed(0)diff --git a/tests/augmentation/test_random_generator.py b/tests/augmentation/test_random_generator.pyindex 3f77b7748..cd27f084c 100644--- a/tests/augmentation/test_random_generator.py+++ b/tests/augmentation/test_random_generator.py@@ -35,7 +35,6 @@ from kornia.augmentation.random_generator import (ResizedCropGenerator,center_crop_generator,)-from kornia.core._compat import torch_version_gefrom testing.base import assert_close@@ -469,9 +468,11 @@ class TestColorJitterGen(RandomGeneratorBaseTests):)(torch.Size([8]))def test_random_gen(self, device, dtype):- # TODO(jian): crashes with pytorch 1.10, cuda and fp64- if (torch_version_ge(1, 10) and "cuda" in str(device)) or dtype == torch.float64:- pytest.skip("AssertionError: cannot reproduce the same result")+ # The generator documents that samples are not reproducible across devices or dtypes.+ if device.type != "cpu" or dtype != torch.float32:+ pytest.skip(+ "Random parameters are device- and dtype-dependent; expected values were computed on CPU float32"+ )torch.manual_seed(42)batch_size = 8gen = ColorJitterGenerator(@@ -549,8 +550,10 @@ class TestColorJitterGen(RandomGeneratorBaseTests):)def test_same_on_batch(self, device, dtype):- if "cuda" in str(device) or dtype == torch.float64:- pytest.skip("AssertionError: cannot reproduce the same result")+ if device.type != "cpu" or dtype != torch.float32:+ pytest.skip(+ "Random parameters are device- and dtype-dependent; expected values were computed on CPU float32"+ )torch.manual_seed(42)batch_size = 8gen = ColorJitterGenerator(diff --git a/tests/contrib/test_conv_distance_transformer.py b/tests/contrib/test_conv_distance_transformer.pyindex 12bd14cff..3fb778827 100755--- a/tests/contrib/test_conv_distance_transformer.py+++ b/tests/contrib/test_conv_distance_transformer.py@@ -22,7 +22,7 @@ import korniafrom kornia.core.exceptions import BaseError, TypeCheckErrorfrom kornia.geometry.grid import create_meshgrid, create_meshgrid3d-from testing.base import BaseTester+from testing.base import BaseTester, supports_conv2d, supports_replicate_paddingclass TestConvDistanceTransform(BaseTester):@@ -192,25 +192,55 @@ class TestConvDistanceTransform(BaseTester):loss_3d.backward()def test_offset_parenthesis_fix(self, device, dtype):+ if not supports_replicate_padding(device, dtype):+ pytest.skip("This device does not support replicate padding for the regression dtype")+ if not supports_conv2d(device, dtype):+ pytest.skip("This device does not support convolution for the regression dtype")+img = torch.zeros(1, 1, 8, 4, device=device, dtype=dtype)img[0, 0, 1, :] = 1.0- out = kornia.contrib.distance_transform(img, kernel_size=3, h=0.01)+ # exp(-1 / 0.01) is a float32 subnormal that MPS flushes to zero. h=0.1 keeps+ # the regression's expected offset away from backend-specific underflow behavior (#4152).+ out = kornia.contrib.distance_transform(img, kernel_size=3, h=0.1)expected = torch.tensor([- [0.9998, 0.9998, 0.9998, 0.9998],+ [0.9969, 0.9969, 0.9969, 0.9969],[0.0000, 0.0000, 0.0000, 0.0000],- [0.9998, 0.9998, 0.9998, 0.9998],- [1.9998, 1.9998, 1.9998, 1.9998],- [2.9998, 2.9998, 2.9998, 2.9998],- [3.9998, 3.9998, 3.9998, 3.9998],- [4.9998, 4.9998, 4.9998, 4.9998],- [5.9998, 5.9998, 5.9998, 5.9998],+ [0.9969, 0.9969, 0.9969, 0.9969],+ [1.9969, 1.9969, 1.9969, 1.9969],+ [2.9969, 2.9969, 2.9969, 2.9969],+ [3.9969, 3.9969, 3.9969, 3.9969],+ [4.9969, 4.9969, 4.9969, 4.9969],+ [5.9969, 5.9969, 5.9969, 5.9969],],device=device,dtype=dtype,)- self.assert_close(out[0, 0], expected, rtol=1e-3, atol=1e-3)+ tolerance = 5e-3 if dtype == torch.bfloat16 else 1e-3+ self.assert_close(out[0, 0], expected, rtol=tolerance, atol=tolerance)++ @pytest.mark.xfail(+ raises=AssertionError,+ reason="distance_transform silently collapses to zero when its kernel underflows β kornia#4152",+ strict=True,+ )+ def test_convention_small_h_keeps_nonzero_distances_4152(self, device, dtype):+ if not (dtype in (torch.float16, torch.bfloat16) or (device.type == "mps" and dtype == torch.float32)):+ pytest.skip("This device and dtype do not reproduce the small-h underflow in kornia#4152")+ if not supports_replicate_padding(device, dtype):+ pytest.skip("This device does not support replicate padding for the regression dtype")+ if not supports_conv2d(device, dtype):+ pytest.skip("This device does not support convolution for the regression dtype")++ img = torch.zeros(1, 1, 8, 4, device=device, dtype=dtype)+ img[0, 0, 1, :] = 1.0+ out = kornia.contrib.distance_transform(img, kernel_size=3, h=0.01)+ expected_column = torch.tensor(+ [0.9998, 0.0, 0.9998, 1.9998, 2.9998, 3.9998, 4.9998, 5.9998], device=device, dtype=dtype+ )++ self.assert_close(out[0, 0, :, 0], expected_column)def test_dynamo(self, device, dtype, torch_optimizer):input2d = torch.rand(1, 1, 16, 16, device=device, dtype=dtype)diff --git a/tests/core/test_helpers.py b/tests/core/test_helpers.pyindex 60aa8e8f5..91528d8ff 100644--- a/tests/core/test_helpers.py+++ b/tests/core/test_helpers.py@@ -123,12 +123,16 @@ class TestSvdCast:class TestSolveCast:def test_smoke(self, device, dtype):torch.manual_seed(0)- A = torch.randn(2, 3, 1, 4, 4, device=device, dtype=dtype)- B = torch.randn(2, 3, 1, 4, 6, device=device, dtype=dtype)+ # Exercise a reproducible, well-conditioned system instead of letting a random draw+ # decide whether the fixed residual bound is meaningful on a given backend.+ A = torch.eye(4).to(dtype).expand(2, 3, 1, 4, 4).clone()+ A.add_(torch.randn_like(A), alpha=0.05)+ B = torch.randn(2, 3, 1, 4, 6, dtype=dtype).to(device)+ A = A.to(device)X = _torch_solve_cast(A, B)- error = torch.dist(B, A.matmul(X))- tol_val: float = 1e-1 if dtype == torch.float16 else 1e-4+ error = torch.dist(B, A.matmul(X)) / B.norm().clamp_min(torch.finfo(dtype).eps)+ tol_val: float = max(1e-4, torch.finfo(dtype).eps)assert_close(error, torch.zeros_like(error), atol=tol_val, rtol=tol_val)diff --git a/tests/feature/test_siftdesc.py b/tests/feature/test_siftdesc.pyindex 51d67a4c0..b7b1c6d1b 100644--- a/tests/feature/test_siftdesc.py+++ b/tests/feature/test_siftdesc.py@@ -213,10 +213,13 @@ class TestSIFTConstantPatchIsFinite(BaseTester):def test_l2_normalize_zero_vector_has_a_zero_gradient(self, device, desc_dtype):from kornia.core.utils import _l2_normalize+ if device.type == "mps" and desc_dtype == torch.float64:+ pytest.skip("MPS does not support float64")x = torch.zeros(3, 8, device=device, dtype=desc_dtype, requires_grad=True)_l2_normalize(x, dim=1).sum().backward()assert x.grad is not None and bool((x.grad == 0).all()), x.grad# and a non-zero vector keeps `F.normalize`'s value and gradient+ torch.manual_seed(0)y = torch.rand(3, 8, device=device, dtype=desc_dtype, requires_grad=True)y_ref = y.detach().clone().requires_grad_(True)_l2_normalize(y, dim=1).sum().backward()@@ -257,7 +260,10 @@ class TestSIFTConstantPatchIsFinite(BaseTester):assert out.dtype == torch.float16self.assert_close(out.float().norm(dim=1), torch.ones(1, device=device), atol=2e-3, rtol=0)assert (_l2_normalize(torch.zeros_like(x), dim=1) == 0).all()- for dt in (torch.bfloat16, torch.float32, torch.float64):+ comparison_dtypes = (torch.bfloat16, torch.float32)+ if device.type != "mps":+ comparison_dtypes += (torch.float64,)+ for dt in comparison_dtypes:y = torch.rand(3, 8, device=device, dtype=dt)assert torch.equal(_l2_normalize(y, dim=1), torch.nn.functional.normalize(y, dim=1, eps=1e-12))diff --git a/tests/feature/test_xfeat.py b/tests/feature/test_xfeat.pyindex 4938abd09..4d849c3d4 100644--- a/tests/feature/test_xfeat.py+++ b/tests/feature/test_xfeat.py@@ -21,7 +21,7 @@ import torchfrom kornia.feature.lightglue import LightGluefrom kornia.feature.xfeat import InterpolateSparse2d, XFeat, XFeatModel-from testing.base import BaseTester+from testing.base import BaseTester, supports_bicubic_2d_grid_sample, supports_bilinear_2d_grid_sample# ---------------------------------------------------------------------------# XFeatModel backbone tests@@ -90,14 +90,21 @@ class TestXFeatModel(BaseTester):class TestInterpolateSparse2d(BaseTester):def test_smoke(self, device, dtype):+ if not supports_bilinear_2d_grid_sample(device, dtype):+ pytest.skip("This device does not support bilinear interpolation for 2D grid_sample")interp = InterpolateSparse2d("bilinear").to(device)x = torch.rand(1, 32, 8, 8, device=device, dtype=dtype)pos = torch.zeros(1, 5, 2, device=device, dtype=dtype)out = interp(x, pos, 8, 8)assert out.shape == (1, 5, 32)- def test_cardinality(self, device, dtype):- interp = InterpolateSparse2d("bicubic").to(device)+ @pytest.mark.parametrize("mode", ["bilinear", "bicubic"])+ def test_cardinality(self, mode, device, dtype):+ if mode == "bilinear" and not supports_bilinear_2d_grid_sample(device, dtype):+ pytest.skip("This device does not support bilinear interpolation for 2D grid_sample")+ if mode == "bicubic" and not supports_bicubic_2d_grid_sample(device, dtype):+ pytest.skip("This device does not support bicubic interpolation for 2D grid_sample")+ interp = InterpolateSparse2d(mode).to(device)B, C, H, W, N = 2, 16, 32, 48, 20x = torch.rand(B, C, H, W, device=device, dtype=dtype)pos = torch.rand(B, N, 2, device=device, dtype=dtype) * torch.tensor([W - 1, H - 1], device=device, dtype=dtype)diff --git a/tests/filters/test_motion.py b/tests/filters/test_motion.pyindex b040babb6..5ac63fb7d 100644--- a/tests/filters/test_motion.py+++ b/tests/filters/test_motion.py@@ -27,7 +27,7 @@ from kornia.filters import (motion_blur3d,)-from testing.base import BaseTester+from testing.base import BaseTester, supports_bilinear_3d_grid_sample, supports_nearest_3d_grid_sampleclass TestMotionBlur(BaseTester):@@ -127,6 +127,14 @@ class TestMotionBlur3D(BaseTester):@pytest.mark.parametrize("mode", ["bilinear", "nearest"])@pytest.mark.parametrize("params_as_tensor", [True, False])def test_smoke(self, shape, kernel_size, angle, direction, mode, params_as_tensor, device, dtype):+ if params_as_tensor:+ supports_mode = (+ supports_nearest_3d_grid_sample(device, dtype)+ if mode == "nearest"+ else supports_bilinear_3d_grid_sample(device, dtype)+ )+ if not supports_mode:+ pytest.skip(f"This device does not support {mode} interpolation for 3D grid_sample")B, _C, _D, _H, _W = shapedata = torch.rand(shape, device=device, dtype=dtype)@@ -157,7 +165,13 @@ class TestMotionBlur3D(BaseTester):@pytest.mark.parametrize("direction", [-1.0, 1.0])@pytest.mark.parametrize("params_as_tensor", [True, False])def test_get_motion_kernel3d(self, batch_size, ksize, angle, direction, params_as_tensor, device, dtype):+ mode = "nearest"if params_as_tensor is True:+ if not supports_nearest_3d_grid_sample(device, dtype):+ if not supports_bilinear_3d_grid_sample(device, dtype):+ pytest.skip("This device does not support a viable interpolation mode for 3D grid_sample")+ # This test checks only the normalized kernel sum, which is independent of interpolation mode.+ mode = "bilinear"angle = torch.tensor([angle], device=device, dtype=dtype).repeat(batch_size, 1)direction = torch.tensor([direction], device=device, dtype=dtype).repeat(batch_size)else:@@ -165,7 +179,7 @@ class TestMotionBlur3D(BaseTester):device = Nonedtype = None- actual = get_motion_kernel3d(ksize, angle, direction)+ actual = get_motion_kernel3d(ksize, angle, direction, mode=mode)expected = torch.ones(1, device=device, dtype=dtype) * batch_sizeassert actual.shape == (batch_size, ksize, ksize, ksize)self.assert_close(actual.sum(), expected.sum())diff --git a/tests/geometry/solvers/test_homogeneous.py b/tests/geometry/solvers/test_homogeneous.pyindex 5eb94b3f2..c206d6259 100644--- a/tests/geometry/solvers/test_homogeneous.py+++ b/tests/geometry/solvers/test_homogeneous.py@@ -37,11 +37,11 @@ def _make_rank3_matrix(null_vec: torch.Tensor, device, dtype) -> torch.Tensor:"""# Build the 4x4 matrix whose columns span the orthogonal complement of null_vec.# We use a Gram-Schmidt orthonormalisation relative to null_vec.- n = null_vec.to(device=device, dtype=torch.float64)+ n = null_vec.to(device="cpu", dtype=torch.float64)n = n / n.norm()# Start from the standard basis and remove the component along n.- basis = torch.eye(4, device=device, dtype=torch.float64)+ basis = torch.eye(4, dtype=torch.float64)vecs = []for i in range(4):v = basis[i] - (basis[i] @ n) * n@@ -54,7 +54,7 @@ def _make_rank3_matrix(null_vec: torch.Tensor, device, dtype) -> torch.Tensor:if len(vecs) == 3:break- A = torch.stack(vecs, dim=0).to(dtype) # (3, 4)+ A = torch.stack(vecs, dim=0).to(device=device, dtype=dtype) # (3, 4)return A.unsqueeze(0) # (1, 3, 4)diff --git a/tests/geometry/test_conversions.py b/tests/geometry/test_conversions.pyindex dab05d69f..bc570f3d7 100644--- a/tests/geometry/test_conversions.py+++ b/tests/geometry/test_conversions.py@@ -704,6 +704,8 @@ class TestAngleAxisToQuaternion(BaseTester):# torch.float32 buffer would silently upcast them, which is exactly the half-precision# surface kornia treats as its own. The tolerance is set for float16, the widest of the# four; the float32/float64 values are pinned exactly by the numerical tests above.+ if device.type == "mps" and input_dtype == torch.float64:+ pytest.skip("MPS does not support float64")axis_angle = torch.tensor((1.0, 0.0, 0.0), device=device, dtype=input_dtype)quaternion = kornia.geometry.conversions.axis_angle_to_quaternion(axis_angle)assert quaternion.dtype == input_dtype@@ -1597,6 +1599,7 @@ class TestQuaternionToRotationMatrix(BaseTester):"float16 cannot represent either 1e-13 or the default eps=1e-12 -- both round to 0, so both ""cells collapse to NaN (same underflow class as kornia#3966)")+ _skip_if_mps_clamp_caching(device)normalize_quaternion = kornia.geometry.conversions.normalize_quaternion@@ -3057,11 +3060,12 @@ class TestConvertPointsFromHomogeneous(BaseTester):# [1., 1., nan]; the double-`where` makes it [1., 1., 0.].# w is the exact pole rather than merely a small value: a nearby w only makes the reciprocal# large, which no assertion on finiteness would catch. eps is passed explicitly so the input- # tracks the guard rather than the default. float64 only -- at float16 the default eps- # underflows to 0 (pinned in test_wart_float16_underflowed_default_eps_flips_branches), so- # w == -eps is not the pole there.+ # tracks the guard rather than the default. float32 and float64 both represent -eps and eps+ # identically enough for their sum to hit exactly zero; float32 keeps the pin active on MPS,+ # which cannot represent float64.eps = 1e-8- points = torch.tensor([[2.0, 4.0, -eps]], device=device, dtype=torch.float64, requires_grad=True)+ regression_dtype = torch.float32 if device.type == "mps" else torch.float64+ points = torch.tensor([[2.0, 4.0, -eps]], device=device, dtype=regression_dtype, requires_grad=True)kornia.geometry.conversions.convert_points_from_homogeneous(points, eps=eps).sum().backward()diff --git a/tests/geometry/test_linalg.py b/tests/geometry/test_linalg.pyindex 4cb8c2cf9..f767bccc5 100644--- a/tests/geometry/test_linalg.py+++ b/tests/geometry/test_linalg.py@@ -85,6 +85,8 @@ 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 device.type == "mps" and torch.float64 in (trans_dtype, points_dtype):+ pytest.skip("MPS does not support float64")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.