Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

fix(feature): keep SMNN mutual matches in integer space (#5687)

NIKHIL73b9baebdd92
diff --git a/changelog.d/5687.fixed.md b/changelog.d/5687.fixed.md
new file mode 100644
index 000000000..3113382df
--- /dev/null
+++ b/changelog.d/5687.fixed.md
@@ -0,0 +1 @@
+Fix half-precision mutual descriptor matches on MPS in `match_smnn` and replace its quadratic match-intersection allocation with an integer lookup.
diff --git a/kornia/feature/matching.py b/kornia/feature/matching.py
index 0a99d6147..f2d9b2115 100644
--- a/kornia/feature/matching.py
+++ b/kornia/feature/matching.py
@@ -239,25 +239,15 @@ def match_smnn(
dists2, idx2 = match_snn(desc2, desc1, th, distance_matrix.t())
if len(dists2) > 0 and len(dists1) > 0:
- idx2 = idx2.flip(1)
- if not is_mps_tensor_safe(idx1):
- idxs_dm = torch.cdist(idx1.float(), idx2.float(), p=1.0)
- else:
- idxs1_rep = idx1.to(desc1).repeat_interleave(idx2.size(0), dim=0)
- idxs_dm = (idx2.to(desc2).repeat(idx1.size(0), 1) - idxs1_rep).abs().sum(dim=1)
- idxs_dm = idxs_dm.reshape(idx1.size(0), idx2.size(0))
- mutual_idxs1 = idxs_dm.min(dim=1)[0] < 1e-8
- mutual_idxs2 = idxs_dm.min(dim=0)[0] < 1e-8
- good_idxs1 = idx1[mutual_idxs1.view(-1)]
- good_idxs2 = idx2[mutual_idxs2.view(-1)]
- dists1_good = dists1[mutual_idxs1.view(-1)]
- dists2_good = dists2[mutual_idxs2.view(-1)]
- _, idx_upl1 = torch.sort(good_idxs1[:, 0])
- _, idx_upl2 = torch.sort(good_idxs2[:, 0])
- good_idxs1 = good_idxs1[idx_upl1]
- match_dists = torch.max(dists1_good[idx_upl1], dists2_good[idx_upl2])
- matches_idxs = good_idxs1
- match_dists, matches_idxs = match_dists.view(-1, 1), matches_idxs.view(-1, 2)
+ # Each target occurs at most once in idx2. Join on its integer index instead of
+ # comparing every pair of matches in floating point (quadratic memory and inexact in half).
+ reverse_lookup = torch.full((desc2.size(0),), -1, dtype=torch.long, device=idx2.device)
+ reverse_lookup[idx2[:, 0]] = torch.arange(idx2.size(0), device=idx2.device)
+ reverse_positions = reverse_lookup[idx1[:, 1]]
+ mutual = (reverse_positions >= 0) & (idx2[reverse_positions, 1] == idx1[:, 0])
+ # match_snn already returns source indices in ascending order.
+ matches_idxs = idx1[mutual]
+ match_dists = torch.maximum(dists1[mutual], dists2[reverse_positions[mutual]])
else:
match_dists, matches_idxs = _no_match(distance_matrix)
return match_dists, matches_idxs
diff --git a/tests/feature/test_matching.py b/tests/feature/test_matching.py
index d4eb5a4e0..234972a54 100644
--- a/tests/feature/test_matching.py
+++ b/tests/feature/test_matching.py
@@ -157,6 +157,61 @@ class TestMatchSNN(BaseTester):
class TestMatchSMNN(BaseTester):
+ @pytest.mark.parametrize("mps_fallback", [False, True])
+ def test_mutual_matches_keep_integer_indices(self, device, dtype, monkeypatch, mps_fallback):
+ # Half precision cannot distinguish all descriptor indices: float16 rounds 2049 to
+ # 2048, and bfloat16 rounds 257 to 256. Only the last pair below is mutual.
+ count = 2050 if dtype == torch.float16 else 258 if dtype == torch.bfloat16 else 16
+ desc = torch.zeros(count, 1, device=device, dtype=dtype)
+ dm = torch.full((count, count), 10.0, device=device, dtype=dtype)
+ dm[-2, -2] = 1.0
+ dm[-1, -2] = 0.5
+ dm[-1, -1] = 0.1
+ if mps_fallback:
+ monkeypatch.setattr(matching, "is_mps_tensor_safe", lambda _: True)
+
+ ratios, indices = match_smnn(desc, desc, 0.95, dm)
+
+ expected_indices = torch.tensor([[count - 1, count - 1]], device=device, dtype=torch.long)
+ self.assert_close(indices, expected_indices)
+ self.assert_close(ratios, torch.tensor([[0.2]], device=device, dtype=dtype))
+
+ def test_reverse_ratios_follow_the_matches(self, device, dtype):
+ # Reverse matches arrive in target-index order; forward matches arrive in source-index order.
+ # Reject source 1 in the reverse direction and source 3 in the forward direction.
+ dm = torch.tensor(
+ [[4.0, 10.0, 1.0], [10.0, 1.5, 10.0], [1.0, 10.0, 10.0], [2.0, 2.0, 10.0]],
+ device=device,
+ dtype=dtype,
+ requires_grad=True,
+ )
+ ratios, indices = match_smnn(dm[:, :1], dm[0, :, None], 0.7, dm)
+ self.assert_close(indices, torch.tensor([[0, 2], [2, 0]], device=device, dtype=torch.long))
+ self.assert_close(ratios, torch.tensor([[0.25], [0.5]], device=device, dtype=dtype))
+ ratios.sum().backward()
+ expected_grad = torch.tensor(
+ [[-0.0625, 0.0, 0.25], [0.0, 0.0, 0.0], [0.5, 0.0, 0.0], [-0.25, 0.0, 0.0]],
+ device=device,
+ dtype=dtype,
+ )
+ self.assert_close(dm.grad, expected_grad)
+
+ def test_nonempty_directional_matches_have_empty_intersection(self, device, dtype):
+ dm = torch.tensor([[1.0, 2.0], [0.5, 0.75]], device=device, dtype=dtype)
+ # The forward ratio test keeps 0 -> 0; the reverse test keeps 0 -> 1 and 1 -> 1.
+ ratios, indices = match_smnn(dm[:, :1], dm[0, :, None], 0.6, dm)
+ assert ratios.shape == (0, 1)
+ assert indices.shape == (0, 2)
+ assert indices.dtype == torch.long
+
+ def test_target_without_reverse_match_is_not_mutual(self, device, dtype):
+ # Sources 0 and 1 both match target 0, which ties between them and has no reverse match. The last reverse
+ # match (target 2 -> source 0) names source 0, and the first (target 1 -> source 1) names source 1.
+ dm = torch.tensor([[1.0, 10.0, 2.0], [1.0, 3.0, 10.0], [10.0, 10.0, 10.0]], device=device, dtype=dtype)
+ ratios, indices = match_smnn(dm[:, :1], dm[0, :, None], 0.7, dm)
+ assert ratios.shape == (0, 1)
+ assert indices.shape == (0, 2)
+
@pytest.mark.parametrize("num_desc1, num_desc2, dim", [(2, 4, 4), (2, 5, 128), (6, 2, 32)])
def test_shape(self, num_desc1, num_desc2, dim, device):
desc1 = torch.rand(num_desc1, dim, device=device)