π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
fix(feature): honor independently optional LoFTR masks (#5788)
Karnajeet Gosavic62def94c73f
diff --git a/changelog.d/5788.fixed.md b/changelog.d/5788.fixed.mdnew file mode 100644index 000000000..3de72abd1--- /dev/null+++ b/changelog.d/5788.fixed.md@@ -0,0 +1 @@+LoFTR coarse matching now applies either supplied padding mask independently, treating an omitted mask as all-valid.diff --git a/kornia/feature/loftr/utils/coarse_matching.py b/kornia/feature/loftr/utils/coarse_matching.pyindex acbffa2e4..90cd90460 100644--- a/kornia/feature/loftr/utils/coarse_matching.py+++ b/kornia/feature/loftr/utils/coarse_matching.py@@ -157,28 +157,28 @@ class CoarseMatching(nn.Module):# F.normalizefeat_c0, feat_c1 = (feat / feat.shape[-1] ** 0.5 for feat in [feat_c0, feat_c1])+ # Each coarse mask is independently optional; an absent mask means all cells are valid.+ invalid = None+ if mask_c0 is not None:+ invalid = ~mask_c0.bool()[..., None]+ if mask_c1 is not None:+ invalid_c1 = ~mask_c1.bool()[:, None]+ invalid = invalid_c1 if invalid is None else invalid | invalid_c1+if self.match_type == "dual_softmax":sim_matrix = torch.einsum("nlc,nsc->nls", feat_c0, feat_c1) / self.temperature- if mask_c0 is not None and mask_c1 is not None:- invalid = ~(mask_c0[..., None] * mask_c1[:, None]).bool()+ if invalid is not None: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 = F.softmax(sim_matrix, 1) * F.softmax(sim_matrix, 2)+ # Fully masked rows/columns can still receive softmax mass; masked cells are never valid matches.+ if invalid is not None: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 includedsim_matrix = torch.einsum("nlc,nsc->nls", feat_c0, feat_c1)- if mask_c0 is not None and mask_c1 is not None:- sim_matrix[:, :L, :S].masked_fill_(- ~(mask_c0[..., None] * mask_c1[:, None]).bool(), _masked_similarity(sim_matrix.dtype)- )+ if invalid is not None:+ sim_matrix[:, :L, :S].masked_fill_(invalid, _masked_similarity(sim_matrix.dtype))# build uniform prior & use sinkhornlog_assign_matrix = self.log_optimal_transport(sim_matrix, self.bin_score, self.skh_iters)@@ -195,6 +195,11 @@ class CoarseMatching(nn.Module):if self.config["sparse_spvs"]:data.update({"conf_matrix_with_bin": assign_matrix.clone()})+ if invalid is not None:+ # A transport solver may assign a tiny probability to an invalid cell despite its finite logit. Out of+ # place: `conf_matrix` is a view of the `exp` output, which autograd saves for the backward pass.+ conf_matrix = conf_matrix.masked_fill(invalid, 0.0)+data.update({"conf_matrix": conf_matrix})# predict coarse matches from conf_matrixdiff --git a/tests/feature/test_loftr.py b/tests/feature/test_loftr.pyindex 56610a79e..9881c194c 100644--- a/tests/feature/test_loftr.py+++ b/tests/feature/test_loftr.py@@ -390,6 +390,151 @@ class TestCoarseMatching(BaseTester):# the confidence is asserted)assert data["conf_matrix"][0, 3, 4].item() > 0.0+ @pytest.mark.parametrize("masked_side", [0, 1])+ def test_independently_optional_coarse_masks_5768(self, device, masked_side):+ cfg = dict(self.CFG)+ cfg["thr"] = 0.0+ generator = torch.Generator(device=device).manual_seed(0)+ feat0 = torch.randn(1, 12, 8, device=device, generator=generator)+ feat1 = torch.randn(1, 9, 8, device=device, generator=generator)+ masked = torch.ones(1, 12 if masked_side == 0 else 9, device=device)+ masked[0, [0, 5, 7, 8, 11] if masked_side == 0 else [0, 3, 5]] = 0+ all_valid = torch.ones(1, 9 if masked_side == 0 else 12, device=device)++ def run(include_other_mask):+ masks = (+ (masked, all_valid if include_other_mask else None)+ if masked_side == 0+ else (all_valid if include_other_mask else None, masked)+ )+ data = {+ "hw0_c": (3, 4),+ "hw1_c": (3, 3),+ "hw0_i": (24, 32),+ "hw1_i": (24, 24),+ "stride_c": 8,+ }+ CoarseMatching(cfg).to(device).eval()(feat0, feat1, data, mask_c0=masks[0], mask_c1=masks[1])+ return data++ one_sided = run(False)+ explicit_valid = run(True)+ assert torch.equal(one_sided["conf_matrix"], explicit_valid["conf_matrix"])+ assert torch.equal(one_sided["i_ids"], explicit_valid["i_ids"])+ assert torch.equal(one_sided["j_ids"], explicit_valid["j_ids"])+ selected = one_sided["i_ids"] if masked_side == 0 else one_sided["j_ids"]+ assert selected.numel() > 0+ assert bool(masked[0, selected].all())++ @pytest.mark.parametrize("masked_side", [0, 1])+ def test_sinkhorn_applies_independently_optional_coarse_masks_5768(self, device, masked_side):+ cfg = dict(self.CFG)+ cfg["thr"] = 0.0+ cfg["sparse_spvs"] = False+ cm = CoarseMatching(cfg).to(device).eval()+ cm.match_type = "sinkhorn"+ cm.skh_prefilter = False+ cm.skh_iters = 1+ cm.bin_score = torch.nn.Parameter(torch.tensor(1.0, device=device))+ transport_inputs = []++ def fake_transport(scores, *_):+ transport_inputs.append(scores.detach().clone())+ return torch.zeros(scores.shape[0], scores.shape[1] + 1, scores.shape[2] + 1, device=device)++ cm.log_optimal_transport = fake_transport+ generator = torch.Generator(device=device).manual_seed(0)+ feat0 = torch.randn(1, 12, 8, device=device, generator=generator)+ feat1 = torch.randn(1, 9, 8, device=device, generator=generator)+ masked = torch.ones(1, 12 if masked_side == 0 else 9, device=device)+ masked[0, [0, 5]] = 0+ masks = (masked, None) if masked_side == 0 else (None, masked)+ data = {+ "hw0_c": (3, 4),+ "hw1_c": (3, 3),+ "hw0_i": (24, 32),+ "hw1_i": (24, 24),+ "stride_c": 8,+ }++ cm(feat0, feat1, data, mask_c0=masks[0], mask_c1=masks[1])+ invalid = ~masked.bool()[..., None] if masked_side == 0 else ~masked.bool()[:, None]+ invalid = invalid.expand_as(transport_inputs[0])+ assert bool((transport_inputs[0][invalid] == -1e9).all())+ assert bool((data["conf_matrix"][invalid] == 0).all())+ selected = data["i_ids"] if masked_side == 0 else data["j_ids"]+ assert selected.numel() > 0+ assert bool(masked[0, selected].all())++ @pytest.mark.parametrize(("mask0_on", "mask1_on"), [(True, False), (False, True), (True, True)])+ def test_masked_sinkhorn_training_backward_5768(self, device, mask0_on, mask1_on):+ """The zero fill after the transport must not write into the ``exp`` output, which autograd saves: an in-place+ fill made ``backward`` raise for every masked Sinkhorn training step."""+ cfg = dict(self.CFG)+ cfg["thr"] = 0.0+ cfg["sparse_spvs"] = False+ cm = CoarseMatching(cfg).to(device).train()+ cm.match_type = "sinkhorn"+ cm.skh_prefilter = False+ cm.skh_iters = 1+ cm.bin_score = torch.nn.Parameter(torch.tensor(1.0, device=device))+ # A differentiable stand-in for SuperGlue's log_optimal_transport (not shipped), with a dustbin row and column.+ cm.log_optimal_transport = lambda scores, *_: F.log_softmax(F.pad(scores, (0, 1, 0, 1)), dim=-1)+ generator = torch.Generator(device=device).manual_seed(0)+ feat0 = torch.randn(1, 12, 8, device=device, generator=generator, requires_grad=True)+ feat1 = torch.randn(1, 9, 8, device=device, generator=generator, requires_grad=True)+ mask0 = torch.ones(1, 12, device=device)+ mask0[0, [0, 5]] = 0+ mask1 = torch.ones(1, 9, device=device)+ mask1[0, 3] = 0+ data = {+ "hw0_c": (3, 4),+ "hw1_c": (3, 3),+ "hw0_i": (24, 32),+ "hw1_i": (24, 24),+ "stride_c": 8,+ "spv_b_ids": torch.zeros(2, dtype=torch.long, device=device),+ "spv_i_ids": torch.tensor([1, 2], device=device),+ "spv_j_ids": torch.tensor([1, 2], device=device),+ }++ cm(feat0, feat1, data, mask_c0=mask0 if mask0_on else None, mask_c1=mask1 if mask1_on else None)+ data["conf_matrix"].sum().backward()+ assert bool(torch.isfinite(feat0.grad).all())+ assert bool(torch.isfinite(feat1.grad).all())++ @pytest.mark.parametrize("masked_side", [0, 1])+ def test_one_sided_mask_is_applied_per_sample_5768(self, device, masked_side):+ """Each sample of a batch keeps its own mask, and the dual softmax runs over that sample's valid cells only:+ the confidences of the valid cells equal the dual softmax of the unmasked submatrix, all others are 0."""+ cfg = dict(self.CFG)+ cfg["thr"] = 0.0+ generator = torch.Generator(device=device).manual_seed(0)+ feat0 = torch.randn(2, 12, 8, device=device, generator=generator)+ feat1 = torch.randn(2, 9, 8, device=device, generator=generator)+ masked = torch.ones(2, 12 if masked_side == 0 else 9, device=device)+ masked[0, [0, 5, 7]] = 0+ masked[1, [1, 2, 8]] = 0+ data = {+ "hw0_c": (3, 4),+ "hw1_c": (3, 3),+ "hw0_i": (24, 32),+ "hw1_i": (24, 24),+ "stride_c": 8,+ }+ masks = (masked, None) if masked_side == 0 else (None, masked)+ CoarseMatching(cfg).to(device).eval()(feat0, feat1, data, mask_c0=masks[0], mask_c1=masks[1])++ sim = torch.einsum("nlc,nsc->nls", feat0 / 8**0.5, feat1 / 8**0.5) / cfg["dsmax_temperature"]+ for b in range(2):+ valid = masked[b].bool()+ expected = torch.zeros_like(sim[b])+ if masked_side == 0:+ expected[valid] = sim[b][valid].softmax(0) * sim[b][valid].softmax(1)+ else:+ expected[:, valid] = sim[b][:, valid].softmax(0) * sim[b][:, valid].softmax(1)+ self.assert_close(data["conf_matrix"][b], expected)+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