π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
fix(geometry): accept an unbatched (3, 3) Fm in the epipolar distances (#6110)
Saksham Sharma43fb5bfd66b9
diff --git a/changelog.d/6110.fixed.md b/changelog.d/6110.fixed.mdnew file mode 100644index 000000000..32532693a--- /dev/null+++ b/changelog.d/6110.fixed.md@@ -0,0 +1 @@+`sampson_epipolar_distance`, `symmetrical_epipolar_distance`, `left_to_right_epipolar_distance` and `right_to_left_epipolar_distance` accept a single `(3, 3)` fundamental matrix, as their `(*, 3, 3)` shapes document, and return the distances of the batched call without its batch axis. They raised `ValueError: Fm must be a (*, 3, 3) tensor. Got torch.Size([3, 3])`, except the first two on CUDA with fewer than 10,000 points, which accepted it. An `Fm` whose last two dimensions are not `(3, 3)` now raises that `ValueError` on every path. On CUDA the first two raised a `RuntimeError` or `IndexError` from the matrix product instead, and returned values for a `(4, 4)` `Fm` with 4-component points; with one point set and several matrices on the CPU, `sampson_epipolar_distance` raised a `RuntimeError`, or reshaped an `Fm` such as `(2, 9, 1)` into `3 x 3` matrices.diff --git a/kornia/geometry/epipolar/_metrics.py b/kornia/geometry/epipolar/_metrics.pyindex 39cb8e915..f38cb64a2 100644--- a/kornia/geometry/epipolar/_metrics.py+++ b/kornia/geometry/epipolar/_metrics.py@@ -46,7 +46,7 @@ def _sampson_epipolar_distance_manual_impl_(pts1: Tensor, pts2: Tensor, Fm: Tensif not isinstance(Fm, Tensor):raise TypeError(f"Fm type is not a torch.Tensor. Got {type(Fm)}")- if (len(Fm.shape) < 3) or not Fm.shape[-2:] == (3, 3):+ if Fm.shape[-2:] != (3, 3):raise ValueError(f"Fm must be a (*, 3, 3) tensor. Got {Fm.shape}")# Extract coords; support 2D (w=1) and 3D homogeneous@@ -255,7 +255,10 @@ def sampson_epipolar_distance(the computed Sampson distance with shape :math:`(*, N)`."""- # Shapes are validated by the implementations, as before; a single (3, 3) Fm never counts as several models.+ # Checked here because the CUDA matmul and shared-point implementations do not check Fm. A single (3, 3) Fm+ # never counts as several models.+ if Fm.shape[-2:] != (3, 3):+ raise ValueError(f"Fm must be a (*, 3, 3) tensor. Got {Fm.shape}")num_points = pts1.shape[-2]matmul = Fm.device.type == "cuda" and num_points < use_matmul_at_less_than_pointsnum_models = math.prod(Fm.shape[:-2])@@ -275,7 +278,7 @@ def _symmetrical_epipolar_distance_manual_impl_(pts1: Tensor, pts2: Tensor, Fm:if not isinstance(Fm, Tensor):raise TypeError(f"Fm type is not a torch.Tensor. Got {type(Fm)}")- if (len(Fm.shape) < 3) or Fm.shape[-2:] != (3, 3):+ if Fm.shape[-2:] != (3, 3):raise ValueError(f"Fm must be a (*, 3, 3) tensor. Got {Fm.shape}")# Extract coords; support 2D (w=1) and 3D homogeneous@@ -361,6 +364,9 @@ def symmetrical_epipolar_distance(the computed Symmetrical distance with shape :math:`(*, N)`."""+ # Checked here because the CUDA matmul implementation does not check Fm.+ if Fm.shape[-2:] != (3, 3):+ raise ValueError(f"Fm must be a (*, 3, 3) tensor. Got {Fm.shape}")if Fm.device.type == "cuda":num_points = pts1.shape[-2]if num_points < 10000:@@ -391,7 +397,7 @@ def left_to_right_epipolar_distance(pts1: Tensor, pts2: Tensor, Fm: Tensor) -> TKORNIA_CHECK_IS_TENSOR(pts2)KORNIA_CHECK_IS_TENSOR(Fm)- if (len(Fm.shape) < 3) or not Fm.shape[-2:] == (3, 3):+ if Fm.shape[-2:] != (3, 3):raise ValueError(f"Fm must be a (*, 3, 3) tensor. Got {Fm.shape}")if pts1.shape[-1] == 2:@@ -426,7 +432,7 @@ def right_to_left_epipolar_distance(pts1: Tensor, pts2: Tensor, Fm: Tensor) -> TKORNIA_CHECK_IS_TENSOR(pts2)KORNIA_CHECK_IS_TENSOR(Fm)- if (len(Fm.shape) < 3) or not Fm.shape[-2:] == (3, 3):+ if Fm.shape[-2:] != (3, 3):raise ValueError(f"Fm must be a (*, 3, 3) tensor. Got {Fm.shape}")if pts2.shape[-1] == 2:diff --git a/tests/geometry/epipolar/test_epipolar_metrics.py b/tests/geometry/epipolar/test_epipolar_metrics.pyindex b73817fc7..805a0b90a 100644--- a/tests/geometry/epipolar/test_epipolar_metrics.py+++ b/tests/geometry/epipolar/test_epipolar_metrics.py@@ -465,10 +465,8 @@ class TestSampsonSharedPoints(BaseTester):self.assert_close(out, expected, rtol=1e-3, atol=1e-3 * float(expected.abs().median()))def test_single_matrix_without_batch_dimension(self, device, dtype):- if device.type != "cuda":- pytest.skip("the manual implementation, used on CPU, has always required a batch dimension on Fm")- # The CUDA matmul implementation broadcasts a single (3, 3) matrix; the shared-point dispatch must not reject- # it.+ # Every implementation broadcasts a single (3, 3) matrix, and the shared-point dispatch must not reject it.+ # The CPU manual implementation used to require a batch dimension on Fm (#6108).pts1 = torch.rand(1, 9, 2, device=device, dtype=dtype)pts2 = torch.rand(1, 9, 2, device=device, dtype=dtype)Fm = create_random_fundamental_matrix(1, dtype=dtype, device=device)@@ -604,3 +602,64 @@ class TestSampsonSharedPoints(BaseTester):pts2 = torch.rand(1, 5, 2, device=device, dtype=torch.float64)Fm = create_random_fundamental_matrix(3, dtype=torch.float64, device=device)self.gradcheck(lambda a, b, F: _sampson_epipolar_distance_shared_impl_(a, b, F, True), (pts1, pts2, Fm))+++class TestUnbatchedFundamentalMatrix(BaseTester):+ """A single (3, 3) ``Fm`` with unbatched points, as documented by the ``(*, 3, 3)`` shapes (#6108)."""++ METRICS = (+ epi.sampson_epipolar_distance,+ epi.symmetrical_epipolar_distance,+ epi.left_to_right_epipolar_distance,+ epi.right_to_left_epipolar_distance,+ )++ @pytest.mark.parametrize("metric", METRICS, ids=lambda fn: fn.__name__)+ @pytest.mark.parametrize("homogeneous", [False, True])+ def test_unbatched_fm_matches_the_batched_call_6108(self, metric, homogeneous, device, dtype):+ # A (3, 3) Fm raised "Fm must be a (*, 3, 3) tensor" on the CPU, although (3, 3) is such a shape.+ generator = torch.Generator().manual_seed(6108)+ pts1 = torch.rand(7, 2, generator=generator).to(device, dtype)+ pts2 = torch.rand(7, 2, generator=generator).to(device, dtype)+ if homogeneous:+ pts1 = torch.cat([pts1, torch.ones_like(pts1[:, :1])], dim=-1)+ pts2 = torch.cat([pts2, torch.ones_like(pts2[:, :1])], dim=-1)+ Fm = create_random_fundamental_matrix(1, dtype=dtype, device=device)++ out = metric(pts1, pts2, Fm[0])++ assert out.shape == (7,)+ # The unbatched matmul may round differently from the batched one, so compare to rounding, not bitwise.+ self.assert_close(out, metric(pts1[None], pts2[None], Fm)[0])++ @pytest.mark.parametrize("metric", METRICS, ids=lambda fn: fn.__name__)+ def test_unbatched_fm_with_batched_points_6108(self, metric, device, dtype):+ # One matrix shared by several point sets broadcasts like any other (*, 3, 3) Fm.+ generator = torch.Generator().manual_seed(6108)+ pts1 = torch.rand(3, 7, 2, generator=generator).to(device, dtype)+ pts2 = torch.rand(3, 7, 2, generator=generator).to(device, dtype)+ Fm = create_random_fundamental_matrix(1, dtype=dtype, device=device)++ out = metric(pts1, pts2, Fm[0])++ assert out.shape == (3, 7)+ # A (3, 3) Fm folds the product into one matrix multiplication, and the expanded Fm runs a batched one. The+ # two kernels can round differently (float64 on an AVX-512 CPU and on CUDA), so compare to rounding.+ self.assert_close(out, metric(pts1, pts2, Fm.expand(3, 3, 3)))++ @pytest.mark.parametrize("metric", METRICS, ids=lambda fn: fn.__name__)+ @pytest.mark.parametrize("shape", [(3,), (4, 4), (2, 3), (2, 4, 4)])+ def test_fm_without_a_3x3_matrix_still_raises_6108(self, metric, shape, device, dtype):+ # The CUDA matmul paths of the first two metrics, and the shared-point Sampson path that (2, 4, 4) reaches on+ # the CPU, did not check Fm and raised a RuntimeError or an IndexError instead.+ pts = torch.rand(7, 2, device=device, dtype=dtype)+ with pytest.raises(ValueError, match=r"Fm must be a \(\*, 3, 3\) tensor"):+ metric(pts, pts, torch.rand(*shape, device=device, dtype=dtype))++ @pytest.mark.parametrize("metric", METRICS, ids=lambda fn: fn.__name__)+ def test_unbatched_fm_gradcheck_6108(self, metric, device):+ generator = torch.Generator().manual_seed(6108)+ pts1 = torch.rand(5, 2, generator=generator, dtype=torch.float64).to(device)+ pts2 = torch.rand(5, 2, generator=generator, dtype=torch.float64).to(device)+ Fm = create_random_fundamental_matrix(1, dtype=torch.float64, device=device)[0]+ self.gradcheck(metric, (pts1, pts2, Fm))