Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

fix: skip MPS-unsupported tests and fix MPS-specific runtime errors (#3649)

Dmytro Mishkin8501790803a9
diff --git a/TESTING.md b/TESTING.md
index 6b2109abe..0b7035dbb 100644
--- a/TESTING.md
+++ b/TESTING.md
@@ -187,6 +187,42 @@ If you write a new function that calls SVD, use `_torch_svd_cast` rather than ca
---
+### 7. MPS (Apple Silicon) Limitations
+
+**What MPS is.** The `mps` device uses Apple's Metal Performance Shaders backend. Run tests against it with `--device=mps`.
+
+**Known unsupported operations.** Several operations are not implemented in the MPS backend and raise a `RuntimeError` at runtime:
+
+| Operation | Error |
+|---|---|
+| `float64` (double precision) | `TypeError: Cannot convert a MPS Tensor to float64 dtype` |
+| `complex128` (cdouble) | `NotImplementedError: … not implemented for 'ComplexDouble'` |
+| `F.grid_sample` with `padding_mode="border"` on 2D | `RuntimeError: MPS: Unsupported Border padding mode` |
+| `F.grid_sample` with `mode="nearest"` on 5-D (3D volumes) | `RuntimeError: grid_sampler_3d: Unsupported Nearest interpolation` |
+| `torch.autocast("mps")` | Converts output to float16 instead of preserving original dtype |
+
+**How Kornia handles these automatically.** The test infrastructure in `conftest.py` and `testing/base.py` skips known-unsupported test classes at collection time so you don't need per-test guards for the common cases:
+
+- `test_gradcheck[mps*]` β€” skipped automatically (`gradcheck` requires float64)
+- `*[mps*cdtype1*]` β€” skipped automatically (parametrized `torch.cdouble` tests)
+- `test_autocast[mps*]` β€” skipped automatically (MPS autocast changes dtype)
+
+The `padding_mode="border"` issue in `F.grid_sample` (2D) is worked around in the implementation (`kornia/feature/laf.py`) by clamping the sampling grid to `[-1, 1]` and using `padding_mode="zeros"`, which is mathematically equivalent.
+
+**Writing new tests that work on MPS.** Follow these rules:
+
+1. **Never create `float64` tensors on the device in non-gradcheck tests.** Use the `dtype` fixture, or if the algorithm requires double precision, skip explicitly:
+ ```python
+ if device.type == "mps":
+ pytest.skip("MPS does not support float64")
+ ```
+2. **`self.gradcheck()` is safe.** `BaseTester.gradcheck()` automatically skips on MPS devices.
+3. **Avoid `padding_mode="border"` in 2D `grid_sample` on MPS.** Use the clamped-zeros workaround or check `device.type == "mps"`.
+4. **3D `grid_sample` with `mode="nearest"` is unsupported on MPS.** Do not silently fall back to bilinear (it would corrupt segmentation masks); instead raise or skip the test.
+5. **Device comparison.** `tensor.device` on MPS returns `device(type='mps', index=0)`, not `device(type='mps')`. The test fixture provides `torch.device("mps:0")` so `tensor.device == device` comparisons work correctly.
+
+---
+
## Writing Robust Tests
- **Seed the RNG** when the test compares against reference values: `torch.manual_seed(seed)`.
diff --git a/conftest.py b/conftest.py
index 266cd8d28..21c3ce3be 100644
--- a/conftest.py
+++ b/conftest.py
@@ -55,7 +55,7 @@ def get_test_devices() -> dict[str, torch.device]:
devices["tpu"] = xm.xla_device()
if hasattr(torch.backends, "mps") and torch.backends.mps.is_available():
- devices["mps"] = torch.device("mps")
+ devices["mps"] = torch.device("mps:0")
return devices
@@ -163,6 +163,24 @@ def pytest_collection_modifyitems(config, items):
# Filter out tests with "dynamo" or "compile" in their name
items[:] = [item for item in items if "dynamo" not in item.name.lower() and "compile" not in item.name.lower()]
+ # MPS does not support float64; gradcheck requires float64 β€” skip all gradcheck tests on MPS
+ skip_mps_gradcheck = pytest.mark.skip(reason="gradcheck requires float64 which is not supported on MPS")
+ for item in items:
+ if "gradcheck" in item.name.lower() and "[mps" in item.nodeid:
+ item.add_marker(skip_mps_gradcheck)
+
+ # MPS does not support complex128 (cdouble); skip tests parametrized with it
+ skip_mps_cdouble = pytest.mark.skip(reason="MPS does not support complex128 (cdouble)")
+ for item in items:
+ if "[mps" in item.nodeid and "cdtype1" in item.nodeid:
+ item.add_marker(skip_mps_cdouble)
+
+ # MPS autocast uses float16 and does not preserve original dtype β€” skip autocast tests on MPS
+ skip_mps_autocast = pytest.mark.skip(reason="MPS autocast changes dtype to float16, not supported the same way")
+ for item in items:
+ if "autocast" in item.name.lower() and "[mps" in item.nodeid:
+ item.add_marker(skip_mps_autocast)
+
tf32_enabled = config.getoption("--tf32")
if not config.getoption("--runslow"):
diff --git a/kornia/feature/laf.py b/kornia/feature/laf.py
index 5dc700a99..8118af832 100644
--- a/kornia/feature/laf.py
+++ b/kornia/feature/laf.py
@@ -430,11 +430,21 @@ def extract_patches_simple(
# for loop temporarily, to be refactored
for i in range(B):
grid = generate_patch_grid_from_normalized_LAF(img[i : i + 1], nlaf[i : i + 1], PS).to(img.device)
- out.append(
- F.grid_sample(
- img[i : i + 1].expand(grid.size(0), ch, h, w), grid, padding_mode="border", align_corners=False
+ if img.device.type == "mps":
+ out.append(
+ F.grid_sample(
+ img[i : i + 1].expand(grid.size(0), ch, h, w),
+ grid.clamp(-1, 1),
+ padding_mode="zeros",
+ align_corners=False,
+ )
+ )
+ else:
+ out.append(
+ F.grid_sample(
+ img[i : i + 1].expand(grid.size(0), ch, h, w), grid, padding_mode="border", align_corners=False
+ )
)
- )
return torch.cat(out, dim=0).view(B, N, ch, PS, PS)
@@ -476,9 +486,17 @@ def extract_patches_from_pyramid(
# torch.where avoids nonzero/data-dependent shapes β†’ fully compilable.
level_mask = (pyr_idx[i] == cur_pyr_level).view(N, 1, 1, 1)
grid = generate_patch_grid_from_normalized_LAF(cur_img[i : i + 1], nlaf[i : i + 1], PS)
- patches = F.grid_sample(
- cur_img[i : i + 1].expand(N, ch_l, h_l, w_l), grid, padding_mode="border", align_corners=False
- )
+ if cur_img.device.type == "mps":
+ patches = F.grid_sample(
+ cur_img[i : i + 1].expand(N, ch_l, h_l, w_l),
+ grid.clamp(-1, 1),
+ padding_mode="zeros",
+ align_corners=False,
+ )
+ else:
+ patches = F.grid_sample(
+ cur_img[i : i + 1].expand(N, ch_l, h_l, w_l), grid, padding_mode="border", align_corners=False
+ )
out[i] = torch.where(level_mask, patches.to(nlaf.dtype), out[i])
if cur_pyr_level < num_levels - 1:
cur_img = pyrdown(cur_img)
diff --git a/kornia/feature/matching.py b/kornia/feature/matching.py
index a38676b92..e995a3951 100644
--- a/kornia/feature/matching.py
+++ b/kornia/feature/matching.py
@@ -172,7 +172,7 @@ def match_snn(
KORNIA_CHECK_SHAPE(desc1, ["B", "DIM"])
KORNIA_CHECK_SHAPE(desc2, ["B", "DIM"])
- if desc2.shape[0] < 2: # We cannot perform snn check, so output empty matches
+ if desc1.shape[0] == 0 or desc2.shape[0] < 2: # We cannot perform snn check, so output empty matches
return _no_match(desc1)
distance_matrix = _get_lazy_distance_matrix(desc1, desc2, dm)
vals, idxs_in_2 = torch.topk(distance_matrix, 2, dim=1, largest=False)
diff --git a/kornia/geometry/calibration/pnp.py b/kornia/geometry/calibration/pnp.py
index e6da068e6..509fdd4b6 100644
--- a/kornia/geometry/calibration/pnp.py
+++ b/kornia/geometry/calibration/pnp.py
@@ -44,8 +44,7 @@ def _mean_isotropic_scale_normalize(points: torch.Tensor, eps: float = 1e-8) ->
scale = (points - x_mean).norm(dim=-1, p=2).mean(dim=-1) # B
D_int = points.shape[-1]
- D_float = torch.tensor(points.shape[-1], dtype=torch.float64, device=points.device)
- scale = torch.sqrt(D_float) / (scale + eps) # B
+ scale = (D_int**0.5) / (scale + eps) # B
transform = eye_like(D_int + 1, points) # (B, D+1, D+1)
idxs = torch.arange(D_int, dtype=torch.int64, device=points.device)
diff --git a/testing/base.py b/testing/base.py
index 8f4bbc327..04b18abdc 100644
--- a/testing/base.py
+++ b/testing/base.py
@@ -20,6 +20,7 @@ from __future__ import annotations
import math
from typing import Any, Callable, Optional, Sequence, Union
+import pytest
import torch
from torch.autograd import gradcheck
from torch.testing import assert_close as _assert_close
@@ -146,6 +147,15 @@ class BaseTester:
requires_grad = requires_grad if len(requires_grad) > 0 else [True] * len(inputs)
dtypes = dtypes if len(dtypes) > 0 else [torch.float64] * len(inputs)
+ # MPS does not support float64; gradcheck requires float64, so skip on MPS
+ _all_inputs = (
+ [inputs]
+ if isinstance(inputs, torch.Tensor)
+ else list(inputs.values() if isinstance(inputs, dict) else inputs)
+ )
+ if any(isinstance(t, torch.Tensor) and t.device.type == "mps" for t in _all_inputs):
+ pytest.skip("gradcheck requires float64 which is not supported on MPS")
+
if isinstance(inputs, torch.Tensor):
inputs = tensor_to_gradcheck_var(inputs)
elif isinstance(inputs, dict):
diff --git a/tests/augmentation/test_augmentation_mix.py b/tests/augmentation/test_augmentation_mix.py
index 967536535..ec7c0e22b 100644
--- a/tests/augmentation/test_augmentation_mix.py
+++ b/tests/augmentation/test_augmentation_mix.py
@@ -615,6 +615,8 @@ class TestRandomTransplantation(BaseTester):
self.gradcheck(RandomTransplantation(p=1.0), (image, mask))
def test_exception(self, device, dtype):
+ if device.type == "mps":
+ pytest.skip("MPS does not support float64")
torch.manual_seed(22)
image = torch.rand(1, 3, 2, 2, device=device, dtype=torch.float64)
mask = torch.randint(0, 2, (1, 2, 2), device=device, dtype=torch.float64)
diff --git a/tests/enhance/test_zca.py b/tests/enhance/test_zca.py
index 98eff7821..bcd9b4bed 100644
--- a/tests/enhance/test_zca.py
+++ b/tests/enhance/test_zca.py
@@ -87,6 +87,8 @@ class TestZCA(BaseTester):
def test_grad_zca_individual_transforms(self, device):
"""Check if the gradients of the transforms are correct w.r.t to the input data."""
+ if device.type == "mps":
+ pytest.skip("MPS does not support float64 required for gradcheck")
data = torch.tensor([[2, 0], [0, 1], [-2, 0], [0, -1]], device=device, dtype=torch.float64)
def zca_T(x):
@@ -103,6 +105,8 @@ class TestZCA(BaseTester):
self.gradcheck(zca_T_inv, (data,))
def test_grad_zca_with_fit(self, device):
+ if device.type == "mps":
+ pytest.skip("MPS does not support float64 required for gradcheck")
data = torch.tensor([[2, 0], [0, 1], [-2, 0], [0, -1]], device=device, dtype=torch.float64)
def zca_fit(x):
@@ -112,6 +116,8 @@ class TestZCA(BaseTester):
self.gradcheck(zca_fit, (data,))
def test_grad_detach_zca(self, device):
+ if device.type == "mps":
+ pytest.skip("MPS does not support float64 required for gradcheck")
data = torch.tensor([[1, 0], [0, 1], [-2, 0], [0, -1]], device=device, dtype=torch.float64)
zca = kornia.enhance.ZCAWhitening()
diff --git a/tests/feature/test_aliked.py b/tests/feature/test_aliked.py
index f0c5b7a8a..ac005027c 100644
--- a/tests/feature/test_aliked.py
+++ b/tests/feature/test_aliked.py
@@ -44,6 +44,8 @@ class TestDeformConv2d:
@pytest.mark.parametrize("dtype", [torch.float32, torch.float64])
def test_zero_offset_matches_regular_conv(self, device, dtype):
"""With all-zero offsets, deform_conv2d should equal regular conv2d."""
+ if device.type == "mps" and dtype == torch.float64:
+ pytest.skip("MPS does not support float64")
B, C_in, H, W = 1, 4, 8, 8
C_out, kH, kW = 8, 3, 3
K = kH * kW
diff --git a/tests/geometry/test_keypoints.py b/tests/geometry/test_keypoints.py
index 3ccad02c2..81c82bb3b 100644
--- a/tests/geometry/test_keypoints.py
+++ b/tests/geometry/test_keypoints.py
@@ -149,6 +149,8 @@ class TestKeypoints(BaseTester):
self.assert_close(kp.data[:3], new_vals)
def test_type(self, device, dtype):
+ if device.type == "mps":
+ pytest.skip("MPS does not support float64")
data = torch.rand(5, 2, device=device, dtype=torch.float32)
kp = Keypoints(data)
kp.type(torch.float64)
diff --git a/tests/geometry/test_linalg.py b/tests/geometry/test_linalg.py
index 0f535356b..0d4577ce3 100644
--- a/tests/geometry/test_linalg.py
+++ b/tests/geometry/test_linalg.py
@@ -305,6 +305,8 @@ class TestPointsLinesDistances(BaseTester):
assert distances.shape == (B, T, N)
def test_functional(self, device):
+ if device.type == "mps":
+ pytest.skip("MPS does not support float64")
pts = torch.tensor([1.0, 0], device=device, dtype=torch.float64).view(1, 1, 2).tile(1, 6, 1)
lines = torch.tensor(
[[0.0, 1.0, 0.0], [0.0, 1.0, 1.0], [1.0, 0.0, 0.0], [1.0, 0.0, 1.0], [1.0, 1.0, 0.0], [1.0, 1.0, 1.0]],