π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
fix(feature): never return a pair of masked LoFTR coarse cells as a match (#5749)
niukanen195fbad7cb394
diff --git a/changelog.d/5749.fixed.md b/changelog.d/5749.fixed.mdnew file mode 100644index 000000000..b04a03f59--- /dev/null+++ b/changelog.d/5749.fixed.md@@ -0,0 +1 @@+`LoFTR`'s coarse matching no longer returns a pair of masked cells as a match. With `mask0` / `mask1`, a pair whose two cells are both masked got the confidence `1 / (L * S)` from the two softmaxes (a fully masked row or column is uniform there, and all its other entries are exactly 0, so the pair was also a mutual nearest neighbour), and whenever `match_coarse.thr` was below `1 / (L * S)` it was returned with keypoints in the padding of both images. The confidence of a pair that involves a masked cell is now 0 after the softmaxes, and a zero confidence is never a match (a negative `thr` now behaves like `thr=0`), so a masked pair is not returned for any `thr` and `border_rm`.diff --git a/kornia/feature/loftr/utils/coarse_matching.py b/kornia/feature/loftr/utils/coarse_matching.pyindex f629a69bb..acbffa2e4 100644--- a/kornia/feature/loftr/utils/coarse_matching.py+++ b/kornia/feature/loftr/utils/coarse_matching.py@@ -160,10 +160,17 @@ class CoarseMatching(nn.Module):if self.match_type == "dual_softmax":sim_matrix = torch.einsum("nlc,nsc->nls", feat_c0, feat_c1) / self.temperatureif mask_c0 is not None and mask_c1 is not None:- sim_matrix.masked_fill_(- ~(mask_c0[..., None] * mask_c1[:, None]).bool(), _masked_similarity(sim_matrix.dtype)- )- conf_matrix = F.softmax(sim_matrix, 1) * F.softmax(sim_matrix, 2)+ invalid = ~(mask_c0[..., None] * mask_c1[:, None]).bool()+ sim_matrix.masked_fill_(invalid, _masked_similarity(sim_matrix.dtype))+ conf_matrix = F.softmax(sim_matrix, 1) * F.softmax(sim_matrix, 2)+ # A pair of masked cells gets the confidence 1 / (L * S) from the two softmaxes:+ # a row or column that is masked entirely is uniform there, and all its other+ # entries are exactly 0, so the pair is also a mutual nearest neighbour. Whenever+ # `thr` is below 1 / (L * S), `get_coarse_match` would return it as a match, with+ # keypoints in the padding of both images (#5740). A masked pair is never a match.+ conf_matrix.masked_fill_(invalid, 0.0)+ else:+ conf_matrix = F.softmax(sim_matrix, 1) * F.softmax(sim_matrix, 2)elif self.match_type == "sinkhorn":# sinkhorn, dustbin included@@ -221,8 +228,9 @@ class CoarseMatching(nn.Module):"w1c": data["hw1_c"][1],}_device = conf_matrix.device- # 1. confidence thresholding- mask = conf_matrix > self.thr+ # 1. confidence thresholding. A zero confidence is never a match, even for a negative `thr`: `mconf == 0` marks+ # the training ground-truth pads below and is dropped from the keypoints, but not from `b_ids`.+ mask = conf_matrix > max(self.thr, 0.0)N = conf_matrix.shape[0]mask = mask.reshape(N, axes_lengths["h0c"], axes_lengths["w0c"], axes_lengths["h1c"], axes_lengths["w1c"])# mask = rearrange(mask, 'b (h0c w0c) (h1c w1c) -> b h0c w0c h1c w1c',diff --git a/tests/feature/test_loftr.py b/tests/feature/test_loftr.pyindex bf59d7d00..56610a79e 100644--- a/tests/feature/test_loftr.py+++ b/tests/feature/test_loftr.py@@ -111,6 +111,29 @@ class TestLoFTR(BaseTester):out = loftr(sample)assert out is not None+ def test_masked_cells_do_not_match_5740(self, device):+ """The whole-module view of #5740: with the same coarse cells masked on both sides,+ no returned keypoint may sit in the masked region, for any ``thr``."""+ cfg = copy.deepcopy(default_cfg)+ cfg["match_coarse"]["thr"] = 0.0+ cfg["match_coarse"]["border_rm"] = 0+ gen = torch.Generator(device=device).manual_seed(3)+ patches = torch.rand(1, 1, 64, 64, device=device, generator=gen)+ loftr = LoFTR(pretrained=None, config=cfg).to(device)+ mask = torch.ones(1, 64, 64, device=device)+ mask[..., :16] = 0 # the left quarter of both images is padding+ with torch.no_grad():+ out = loftr({"image0": patches, "image1": patches, "mask0": mask, "mask1": mask})+ kp0, kp1 = out["keypoints0"], out["keypoints1"]+ assert len(kp0) > 0+ # The masked cells are the coarse columns 0 and 1 (pixel x < 16, centers 0 and 8). Before+ # the fix, masked-cell pairs put keypoints at those centers, and the fine level refined+ # them to x in [0, 4] or below 0. A fine refinement of a valid coarse cell (column 2,+ # center 16) can legitimately move a few pixels into the masked band, so the assertion+ # covers the masked cell centres with the fine half-window to spare.+ assert (kp0[:, 0] < 12).sum().item() == 0+ assert (kp1[:, 0] < 12).sum().item() == 0+@pytest.mark.slow@pytest.mark.skipif(sys.platform == "win32", reason="this test takes so much memory in the CI with Windows")@pytest.mark.parametrize("data", ["loftr_homo"], indirect=True)@@ -315,6 +338,58 @@ class TestCoarseMatching(BaseTester):assert out["mconf"].dtype == dtypeassert out["mkpts0_c"].shape == (self.N_PRED, 2)+ @pytest.mark.parametrize("thr", [0.0, -1.0])+ @pytest.mark.parametrize("mask0_on", [False, True])+ @pytest.mark.parametrize("mask1_on", [False, True])+ def test_masked_cell_pair_is_never_a_match_5740(self, device, mask0_on, mask1_on, thr):+ """A pair of masked coarse cells has the confidence 1 / (L * S): the row and the+ column of a fully masked cell are uniform under the two softmaxes, and all other+ entries are exactly 0, so the pair is also a mutual nearest neighbour. With ``thr``+ below 1 / (L * S) it was returned as a match, with keypoints in the padding of both+ images. One-sided masking is covered too: the confidence of any pair that involves a+ masked cell is 0. A negative ``thr`` must not admit those zero confidences either:+ ``get_coarse_match`` drops ``mconf == 0`` from the keypoints but not from ``b_ids``."""+ cfg = {+ "thr": thr,+ "border_rm": 0,+ "train_coarse_percent": 0.5,+ "train_pad_num_gt_min": 2,+ "match_type": "dual_softmax",+ "dsmax_temperature": 0.1,+ }+ gen = torch.Generator(device=device).manual_seed(0)+ feat0 = torch.randn(1, 12, 8, device=device, generator=gen)+ feat1 = torch.randn(1, 9, 8, device=device, generator=gen)+ mask0, mask1 = torch.ones(1, 12, device=device), torch.ones(1, 9, device=device)+ if mask0_on:+ mask0[0, 3] = 0+ if mask1_on:+ mask1[0, 4] = 0+ data = {+ "hw0_c": (3, 4),+ "hw1_c": (3, 3),+ "hw0_i": (24, 32),+ "hw1_i": (24, 24),+ "stride_c": 8,+ }+ cm = CoarseMatching(cfg).to(device)+ cm.eval()+ cm(feat0, feat1, data, mask_c0=mask0, mask_c1=mask1)+ pairs = set(zip(data["i_ids"].tolist(), data["j_ids"].tolist()))+ assert len(data["b_ids"]) == len(data["mconf"]) == len(data["mkpts0_c"])+ if mask0_on or mask1_on:+ # any pair that involves a masked cell has the confidence 0: one-sided masking+ # already achieved that through the -1e9 similarity fill (the softmax over the+ # masked row or column gives it no weight), both-sided masking is what needed the+ # explicit zero fill after the softmaxes+ assert (3, 4) not in pairs+ assert data["conf_matrix"][0, 3, 4].item() == 0.0+ else:+ # control: without any mask the pair keeps its normal confidence, the fix must not+ # suppress it (whether it is a mutual nearest neighbour depends on the RNG, so only+ # the confidence is asserted)+ assert data["conf_matrix"][0, 3, 4].item() > 0.0+def test_eval_path_unaffected(self, device):"""Eval mode skips the gt-padding branch entirely -- assert thatdirectly (gt_mask all False, count == predictions only), not just