Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

fix(geometry): correct batched line homography scores on MPS (#5462)

mika46cb41662376
diff --git a/changelog.d/5462.fixed.md b/changelog.d/5462.fixed.md
new file mode 100644
index 000000000..395a5d19c
--- /dev/null
+++ b/changelog.d/5462.fixed.md
@@ -0,0 +1 @@
+Fixed `convert_points_to_homogeneous`, and through it `transform_points` and `RANSAC("homography_from_linesegments")`, returning wrong values on MPS once the third-from-last dimension of the points (for `transform_points`, the flattened batch) reaches 65536; RANSAC on line segments picked a wrong homography.
diff --git a/kornia/geometry/conversions.py b/kornia/geometry/conversions.py
index a144f6cfa..b87e5c97c 100644
--- a/kornia/geometry/conversions.py
+++ b/kornia/geometry/conversions.py
@@ -296,7 +296,9 @@ def convert_points_to_homogeneous(points: torch.Tensor) -> torch.Tensor:
if len(points.shape) < 2:
raise ValueError(f"Input must be at least a 2D tensor. Got {points.shape}")
- return F.pad(points, [0, 1], "constant", 1.0)
+ # Concatenate rather than ``F.pad(points, [0, 1], value=1.0)``: on MPS (seen on torch 2.5.1 and 2.14) a constant
+ # pad with a non-zero value returns garbage once the third-from-last dimension reaches 2**16.
+ return torch.cat([points, torch.ones_like(points[..., :1])], dim=-1)
def _convert_affinematrix_to_homography_impl(A: torch.Tensor) -> torch.Tensor:
diff --git a/kornia/geometry/homography.py b/kornia/geometry/homography.py
index a163b4c1d..a5cfee9d2 100644
--- a/kornia/geometry/homography.py
+++ b/kornia/geometry/homography.py
@@ -297,8 +297,10 @@ def line_segment_transfer_error_one_way(
# fix its error reads as zero, and the callers that need infinity guard on the segment length themselves.
scale = ln2[..., :, :2].norm(dim=-1, keepdim=True)
ln2 = ln2 / torch.where(scale > 0, scale, torch.ones_like(scale))
- ps1_in2 = convert_points_to_homogeneous(transform_points(H, ps1))
- pe1_in2 = convert_points_to_homogeneous(transform_points(H, pe1))
+ # Pass (B, N, 2) points so transform_points applies each H once; (B, N, 1, 2) points are flattened to
+ # (B*N, 1, 2) and every H is repeated N times.
+ ps1_in2 = convert_points_to_homogeneous(transform_points(H, ps1.squeeze(-2))).unsqueeze(-2)
+ pe1_in2 = convert_points_to_homogeneous(transform_points(H, pe1.squeeze(-2))).unsqueeze(-2)
er_st1 = (ln2 @ ps1_in2.transpose(-2, -1)).view(B, N).abs()
er_end1 = (ln2 @ pe1_in2.transpose(-2, -1)).view(B, N).abs()
error = 0.5 * (er_st1 + er_end1)
diff --git a/tests/geometry/test_conversions.py b/tests/geometry/test_conversions.py
index 732b6dbae..90a496a2f 100644
--- a/tests/geometry/test_conversions.py
+++ b/tests/geometry/test_conversions.py
@@ -2744,6 +2744,15 @@ class TestConvertPointsToHomogeneous(BaseTester):
self.assert_close(actual, expected)
+ def test_third_from_last_dim_of_2_pow_16(self, device, dtype):
+ # On MPS (torch 2.5.1 and 2.14) a constant F.pad with a non-zero value returns garbage once dim -3 reaches
+ # 2**16: RANSAC scored (B, N, 1, 2) segment endpoints with B * N >= 2**16 through it (#5443).
+ points = (torch.arange(2**17, device=device) % 7).reshape(2**16, 1, 2).to(dtype)
+ out = kornia.geometry.conversions.convert_points_to_homogeneous(points)
+ assert out.shape == (2**16, 1, 3)
+ assert torch.equal(out[..., :2], points)
+ assert bool((out[..., 2] == 1).all())
+
class TestConvertAtoH(BaseTester):
def test_convert_points(self, device, dtype):
diff --git a/tests/geometry/test_homography.py b/tests/geometry/test_homography.py
index 5e2715aac..8dec29e6f 100644
--- a/tests/geometry/test_homography.py
+++ b/tests/geometry/test_homography.py
@@ -149,6 +149,21 @@ class TestLineSegmentOneWayError(BaseTester):
error.sum().backward()
assert torch.isfinite(ls2.grad).all()
+ @pytest.mark.parametrize("batch_size, num_segments", [(256, 256), (1, 2**16)])
+ def test_2_pow_16_segments(self, batch_size, num_segments, device, dtype):
+ # RANSAC scores a (B, N) batch of segments; with B * N or N reaching 2**16, MPS (torch 2.5.1 and 2.14) made
+ # the endpoints homogeneous through a constant F.pad that returns garbage there and picked a wrong model
+ # (#5443). Image-1 segment (0, a)-(1, a) maps by the x-shift to (1, a)-(2, a), d px from the image-2 line
+ # y = a + d.
+ idx = torch.arange(batch_size * num_segments, device=device).reshape(batch_size, num_segments)
+ a, d = (idx % 7).to(dtype), (idx % 3).to(dtype)
+ zero, one = torch.zeros_like(a), torch.ones_like(a)
+ ls1 = torch.stack([torch.stack([zero, a], -1), torch.stack([one, a], -1)], dim=2)
+ ls2 = torch.stack([torch.stack([zero, a + d], -1), torch.stack([2 * one, a + d], -1)], dim=2)
+ H = torch.tensor([[1.0, 0.0, 1.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0]], device=device, dtype=dtype)
+ H = H.expand(batch_size, 3, 3)
+ self.assert_close(line_segment_transfer_error_one_way(ls1, ls2, H), d, atol=0.0, rtol=0.0)
+
class TestSymmetricTransferError(BaseTester):
def test_smoke(self, device, dtype):
diff --git a/tests/geometry/test_linalg.py b/tests/geometry/test_linalg.py
index e4ac5bdbc..bf68b2af8 100644
--- a/tests/geometry/test_linalg.py
+++ b/tests/geometry/test_linalg.py
@@ -109,6 +109,15 @@ class TestTransformPoints(BaseTester):
assert out.dtype == dtype
assert out.shape == kgl.transform_points(single_trans, points).shape
+ @pytest.mark.parametrize("points_shape", [(2**16, 1, 2), (1, 2**16, 1, 2)])
+ def test_flattened_batch_of_2_pow_16(self, points_shape, device, dtype):
+ # The points are flattened to (2**16, 1, 2) and made homogeneous; on MPS (torch 2.5.1 and 2.14) a constant
+ # F.pad with a non-zero value returns garbage once dim -3 reaches 2**16 (#5443).
+ points = (torch.arange(2**17, device=device) % 7).reshape(points_shape).to(dtype)
+ trans = torch.tensor([[2.0, 0.0, 1.0], [0.0, 3.0, 2.0], [0.0, 0.0, 1.0]], device=device, dtype=dtype)[None]
+ expected = torch.stack([2 * points[..., 0] + 1, 3 * points[..., 1] + 2], dim=-1)
+ self.assert_close(kgl.transform_points(trans, points), expected, atol=0.0, rtol=0.0)
+
def test_gradcheck(self, device):
# generate input data
batch_size, num_points, num_dims = 2, 3, 2