Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

fix(geometry): pass contiguous LU blocks to MPS solve_triangular in _null_space_lu (#5667)

peng xianged8cb09e3c87
diff --git a/changelog.d/5667.fixed.md b/changelog.d/5667.fixed.md
new file mode 100644
index 000000000..d7b627f27
--- /dev/null
+++ b/changelog.d/5667.fixed.md
@@ -0,0 +1,5 @@
+On MPS with torch 2.9.1, or torch 2.5.1 with `PYTORCH_ENABLE_MPS_FALLBACK=1`, `find_fundamental` with
+`method="7POINT"`, or with `method="8POINT"` and exactly eight unweighted points, and the minimal homography and
+fundamental matrix solvers inside `RANSAC` returned wrong models (in our tests RANSAC found no inliers). MPS
+`solve_triangular` misread the strided LU blocks that the shared null-space solver passed to it; the solver now makes
+them contiguous on MPS. Results on the CPU and on MPS with torch 2.14 are bit-identical to before.
diff --git a/kornia/geometry/solvers/homogeneous.py b/kornia/geometry/solvers/homogeneous.py
index 84f0ea147..791383605 100644
--- a/kornia/geometry/solvers/homogeneous.py
+++ b/kornia/geometry/solvers/homogeneous.py
@@ -191,7 +191,11 @@ def _null_space_lu(A: torch.Tensor) -> torch.Tensor:
# batch inside while_loop that needs a data-dependent guard. Make that layout check always true,
# including empty batches; a row-major copy still needs a guard for the empty case.
square = square.mT.contiguous().mT
- lower = torch.linalg.solve_triangular(square, lu[:, m:, :m], upper=False, left=False, unitriangular=True)
+ rhs = lu[:, m:, :m]
+ if A.device.type == "mps":
+ # MPS solve_triangular reads strided views wrongly on torch 2.5.1 and 2.9.1.
+ square, rhs = square.contiguous(), rhs.contiguous()
+ lower = torch.linalg.solve_triangular(square, rhs, upper=False, left=False, unitriangular=True)
eye = torch.eye(n - m, dtype=A.dtype, device=A.device).expand(batch, -1, -1)
permutation, _, _ = torch.lu_unpack(lu, pivots, unpack_data=False)
return permutation @ torch.cat([-lower.mT, eye], 1)
diff --git a/tests/geometry/solvers/test_homogeneous.py b/tests/geometry/solvers/test_homogeneous.py
index bf5242595..7229f6e84 100644
--- a/tests/geometry/solvers/test_homogeneous.py
+++ b/tests/geometry/solvers/test_homogeneous.py
@@ -276,6 +276,36 @@ class TestConventionNullVector3x4(BaseTester):
class TestNullSpaceLU(BaseTester):
"""``_null_space_lu``, the batched null space behind the seven-, eight- and four-point minimal solvers."""
+ @pytest.mark.parametrize("rows", [7, 8])
+ @pytest.mark.parametrize("batch_size", [1, 32])
+ def test_mps_matches_cpu(self, device, dtype, rows, batch_size, monkeypatch):
+ if device.type != "mps" or dtype != torch.float32:
+ pytest.skip("MPS float32 regression")
+ generator = torch.Generator().manual_seed(0)
+ A = torch.randn(batch_size, rows, 9, generator=generator, dtype=dtype)
+ expected = _null_space_lu(A)
+ solve_triangular = torch.linalg.solve_triangular
+ calls = []
+
+ def check_layout(square, rhs, **kwargs):
+ assert square.device == rhs.device == device
+ assert square.is_contiguous()
+ assert rhs.is_contiguous()
+ calls.append(True)
+ return solve_triangular(square, rhs, **kwargs)
+
+ # Newer MPS kernels handle strides, so also guard the layout needed by older releases.
+ monkeypatch.setattr(torch.linalg, "solve_triangular", check_layout)
+ actual = _null_space_lu(A.to(device))
+ assert calls == [True]
+ assert actual.device == device
+ assert actual.dtype == dtype
+ actual = actual.cpu()
+ actual = actual / actual.norm(dim=1, keepdim=True)
+ expected = expected / expected.norm(dim=1, keepdim=True)
+ self.assert_close(actual, expected, atol=1e-5, rtol=1e-5)
+ self.assert_close(A @ actual, torch.zeros(batch_size, rows, 9 - rows, dtype=dtype), atol=1e-5, rtol=0)
+
@pytest.mark.parametrize("rows", [7, 8])
def test_matches_svd_subspace(self, device, dtype, rows):
if dtype in (torch.float16, torch.bfloat16):
diff --git a/tests/geometry/test_homography.py b/tests/geometry/test_homography.py
index 3c09c63c9..eb717f368 100644
--- a/tests/geometry/test_homography.py
+++ b/tests/geometry/test_homography.py
@@ -1628,6 +1628,27 @@ class TestConventionHomography(BaseTester):
class TestHomographySharedKernels(BaseTester):
+ @pytest.mark.parametrize("batch_size", [1, 32])
+ def test_four_point_homography_mps_matches_cpu(self, device, dtype, batch_size):
+ if device.type != "mps" or dtype != torch.float32:
+ pytest.skip("MPS float32 regression")
+ generator = torch.Generator().manual_seed(0)
+ corners = torch.tensor([[0.0, 0.0], [1.0, 0.0], [1.0, 1.0], [0.0, 1.0]], dtype=dtype)
+ src = corners + 0.1 * torch.randn(batch_size, 4, 2, generator=generator, dtype=dtype)
+ H = torch.eye(3, dtype=dtype) + 0.1 * torch.randn(batch_size, 3, 3, generator=generator, dtype=dtype)
+ dst = transform_points(H, src)
+ n1, _ = normalize_points(src)
+ n2, _ = normalize_points(dst)
+ expected = _four_point_homography(_hom(n1), n2)
+ actual = _four_point_homography(_hom(n1).to(device), n2.to(device))
+ assert actual.device == device
+ assert actual.dtype == dtype
+ actual = actual.cpu()
+ # Unit-norm homographies are defined up to sign.
+ sign = (actual * expected).sum(dim=(-2, -1)).sign()
+ self.assert_close(actual * sign[:, None, None], expected, atol=1e-5, rtol=1e-5)
+ self.assert_close(transform_points(actual, n1), n2, atol=1e-5, rtol=1e-5)
+
def test_design_rows_vanish_on_exact_matches(self, device, dtype):
_skip_half(dtype, _HALF_DLT)
src, dst, H = _planar(device, dtype)