π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
fix(feature): LightGlue matches batches with point pruning and float16 models with mp=True on CPU (#5928)
Dmytro Mishkin8dfcd4de6b9f
diff --git a/changelog.d/5928.fixed.md b/changelog.d/5928.fixed.mdnew file mode 100644index 000000000..ea692101e--- /dev/null+++ b/changelog.d/5928.fixed.md@@ -0,0 +1,7 @@+`LightGlue` matches a batch of image pairs with point pruning, which is on by default, instead of raising an+`IndexError`: each pair gives the matches and scores it gives on its own, and a batch that can prune runs its pairs one+at a time. A batch with too few keypoints for pruning to start (on CUDA, 1536 by default) no longer raises either, and+early stopping ends such a batch once every pair meets its own criterion, rather than counting the unconfident points+of all pairs together. A float16 model with `mp=True` on CPU now autocasts to float16 and returns float16 scores,+instead of raising a `RuntimeError` in its first layer, or with `"keynet_affnet_hardnet"` already when it reads the+LAFs.diff --git a/kornia/feature/lightglue.py b/kornia/feature/lightglue.pyindex c37de3ac0..174dd0261 100644--- a/kornia/feature/lightglue.py+++ b/kornia/feature/lightglue.py@@ -460,6 +460,14 @@ def _check_keypoints_normalized(kpts: torch.Tensor) -> None:KORNIA_CHECK(torch.all(kpts >= -1).item() and torch.all(kpts <= 1).item(), _KEYPOINT_RANGE_MSG) # type: ignore+def _select_pair(image: Dict[str, Any], k: int, b: int) -> Dict[str, Any]:+ """Take pair ``k`` of the ``b`` pairs from the inputs of one image, keeping entries shared by the batch."""+ return {+ key: value[k : k + 1] if torch.is_tensor(value) and value.ndim > 0 and value.shape[0] == b else value+ for key, value in image.items()+ }++class LightGlue(nn.Module):"""Implement the LightGlue matcher for sparse local features.@@ -477,15 +485,26 @@ class LightGlue(nn.Module):reads ``lafs``. :class:`~kornia.feature.LightGlueMatcher` builds them from LAFs.- The matching scores, ``matching_scores0``, ``matching_scores1`` and ``scores``, are in the dtype of thedescriptors with ``mp=False``. With ``mp=True``, autocast sets it, for every configuration and also when- point pruning removes every point: on CPU, float32 descriptors give bfloat16 scores, and float64 and- bfloat16 ones keep their dtype; on MPS, float32, float16 and bfloat16 descriptors give float32 scores; on- CUDA, float32 descriptors give float32 scores. An image without descriptors runs no layer, and its zero- scores keep the descriptor dtype, also with ``mp=True``.- - Known defects: with ``mp=True`` on CPU, a float16 model raises a ``RuntimeError`` in its first layer, and- with the ``"keynet_affnet_hardnet"`` configuration already when it reads the ``lafs``, also for an image- without descriptors (`#5897 <https://github.com/kornia/kornia/issues/5897>`_). A batch of more than one- pair raises an ``IndexError`` when point pruning runs and keeps a point- (`#5898 <https://github.com/kornia/kornia/issues/5898>`_).+ point pruning removes every point. On CPU, autocast runs in float16 for a float16 model and in bfloat16,+ CPU autocast's default, for any other: a float16 model gives float16 scores for float16 and float32+ descriptors, a float32 or bfloat16 model gives bfloat16 scores for float32 and bfloat16 descriptors, and a+ float64 model gives float64 scores for float64 descriptors. Float16 descriptors with any other model, and+ bfloat16 descriptors with a float16 model, are not supported there+ (`#5929 <https://github.com/kornia/kornia/issues/5929>`_). On MPS, float32, float16 and bfloat16+ descriptors give float32 scores; on CUDA, float32 descriptors give float32 scores. An image without+ descriptors runs no layer, and its zero scores keep the descriptor dtype, also with ``mp=True``.+ - Each pair of a batch gives the matches and scores it gives on its own when point pruning can run, that is+ with ``width_confidence > 0``, no padding to the static lengths of :meth:`compile`, and an image with more+ keypoints than :meth:`pruning_min_kpts` of the device. Pruning keeps a different number of points in each+ pair, so then the pairs run one at a time: ``matches0``, ``matches1``, ``matching_scores0``,+ ``matching_scores1``, ``prune0`` and ``prune1`` stack the rows of the pairs, ``matches`` and ``scores`` list+ them, ``stop`` is the largest number of layers that a pair ran, and there is no ``log_assignment``.+ Otherwise a batch runs as one, and early stopping (``depth_confidence``) ends it at a layer only when every+ pair meets its own criterion. A pair can therefore run more layers in a batch than on its own, and its+ matches can differ.+ - Known defects: on the static-length path of :meth:`compile`, early stopping also counts the unconfident+ padded positions, against the number of real keypoints, so a padded pair can stop later than without+ padding (`#5930 <https://github.com/kornia/kornia/issues/5930>`_).Args:features: The type of local features to match (e.g., 'superpoint', 'disk'), whose configuration and@@ -718,7 +737,7 @@ class LightGlue(nn.Module):scales, oris: [B x N], with add_scale_orilafs: [B x N x 2 x 3], with add_lafOutput (dict):- log_assignment: [B x M+1 x N+1]+ log_assignment: [B x M+1 x N+1], not for a batch that prunes points (see the Convention block)matches0: [B x M]matching_scores0: [B x M]matches1: [B x N]@@ -726,18 +745,27 @@ class LightGlue(nn.Module):matches: List[[Si x 2]], scores: List[[Si]]stop, prune0, prune1: diagnostics of early stopping and point pruning"""+ for key in self.required_data_keys:+ KORNIA_CHECK(key in data, f"Missing key {key} in data")device_type = data["image0"]["keypoints"].device.type- with torch.autocast(enabled=self.conf.mp, device_type=device_type):+ # CPU autocast defaults to bfloat16, whose outputs cannot meet the float16 tensors of a float16 model, so such a+ # model autocasts to float16 there.+ dtype = torch.float16 if device_type == "cpu" and self.posenc.Wr.weight.dtype == torch.float16 else None+ with torch.autocast(enabled=self.conf.mp, device_type=device_type, dtype=dtype):return self._forward(data)def _forward(self, data: dict) -> dict: # type: ignore- for key in self.required_data_keys:- KORNIA_CHECK(key in data, f"Missing key {key} in data")data0, data1 = data["image0"], data["image1"]kpts0, kpts1 = data0["keypoints"], data1["keypoints"]b, m, _ = kpts0.shapeb, n, _ = kpts1.shapedevice = kpts0.device+ c = max(m, n)+ do_compile = self.static_lengths and c <= max(self.static_lengths)+ do_point_pruning = self.conf.width_confidence > 0 and not do_compile+ if b > 1 and min(m, n) > 0 and do_point_pruning and c > self.pruning_min_kpts(device):+ # Point pruning keeps a different number of points in each pair, so the pairs run one at a time.+ return self._forward_pairs(data0, data1, b)size0, size1 = data0.get("image_size"), data1.get("image_size")size0 = size0 if size0 is not None else data0["image"].shape[-2:][::-1]size1 = size1 if size1 is not None else data1["image"].shape[-2:][::-1]@@ -809,8 +837,6 @@ class LightGlue(nn.Module):desc1 = desc1.half()mask0, mask1 = None, None- c = max(m, n)- do_compile = self.static_lengths and c <= max(self.static_lengths)if do_compile:kn = min([k for k in self.static_lengths if k >= c])desc0, mask0 = pad_to_length(desc0, kn)@@ -825,11 +851,10 @@ class LightGlue(nn.Module):# GNN + final_proj + assignmentdo_early_stop = self.conf.depth_confidence > 0- do_point_pruning = self.conf.width_confidence > 0 and not do_compilepruning_th = self.pruning_min_kpts(device)if do_point_pruning:- ind0 = torch.arange(0, m, device=device)[None]- ind1 = torch.arange(0, n, device=device)[None]+ ind0 = torch.arange(0, m, device=device)[None].expand(b, -1)+ ind1 = torch.arange(0, n, device=device)[None].expand(b, -1)# We store the index of the layer at which pruning is detected.prune0 = torch.ones_like(ind0)prune1 = torch.ones_like(ind1)@@ -841,8 +866,9 @@ class LightGlue(nn.Module):if do_early_stop:token0, token1 = self.token_confidence[i](desc0, desc1)- if self.check_if_stop(token0[..., :m, :], token1[..., :n, :], i, m + n):+ if self.check_if_stop(token0, token1, i, m + n):break+ # Pruning runs here for a single pair only: a batch that would prune runs its pairs one at a time.if do_point_pruning and desc0.shape[-2] > pruning_th:scores0 = self.log_assignment[i].get_matchability(desc0)prunemask0 = self.get_pruning_mask(token0, scores0, i) # type: ignore@@ -907,12 +933,12 @@ class LightGlue(nn.Module):if do_point_pruning:m0_ = torch.full((b, m), -1, device=m0.device, dtype=m0.dtype)m1_ = torch.full((b, n), -1, device=m1.device, dtype=m1.dtype)- m0_[:, ind0] = torch.where(m0 == -1, -1, ind1.gather(1, m0.clamp(min=0)))- m1_[:, ind1] = torch.where(m1 == -1, -1, ind0.gather(1, m1.clamp(min=0)))+ m0_.scatter_(1, ind0, torch.where(m0 == -1, -1, ind1.gather(1, m0.clamp(min=0))))+ m1_.scatter_(1, ind1, torch.where(m1 == -1, -1, ind0.gather(1, m1.clamp(min=0))))mscores0_ = torch.zeros((b, m), device=mscores0.device, dtype=mscores0.dtype)mscores1_ = torch.zeros((b, n), device=mscores1.device, dtype=mscores1.dtype)- mscores0_[:, ind0] = mscores0- mscores1_[:, ind1] = mscores1+ mscores0_.scatter_(1, ind0, mscores0)+ mscores1_.scatter_(1, ind1, mscores1)m0, m1, mscores0, mscores1 = m0_, m1_, mscores0_, mscores1_else:prune0 = torch.ones_like(mscores0) * self.conf.n_layers@@ -931,6 +957,22 @@ class LightGlue(nn.Module):"prune1": prune1,}+ def _forward_pairs(self, data0: dict, data1: dict, b: int) -> dict: # type: ignore+ """Match the ``b`` pairs of a batch one at a time and stack their outputs.++ The pairs have no common ``log_assignment``, since each covers the points its pair kept, and ``stop`` is the+ largest number of layers a pair ran.+ """+ outs = [+ self._forward({"image0": _select_pair(data0, k, b), "image1": _select_pair(data1, k, b)}) for k in range(b)+ ]+ stacked = ("matches0", "matches1", "matching_scores0", "matching_scores1", "prune0", "prune1")+ out: Dict[str, Any] = {key: torch.cat([o[key] for o in outs]) for key in stacked}+ out["matches"] = [o["matches"][0] for o in outs]+ out["scores"] = [o["scores"][0] for o in outs]+ out["stop"] = max(o["stop"] for o in outs)+ return out+def confidence_threshold(self, layer_index: int) -> float:"""Scaled confidence threshold."""threshold = 0.8 + 0.1 * math.exp(-4.0 * layer_index / self.conf.n_layers)@@ -950,11 +992,22 @@ class LightGlue(nn.Module):layer_index: int,num_points: int,) -> torch.Tensor:- """Evaluate stopping condition."""+ """Evaluate the early-stopping condition of every pair in a batch.++ Args:+ confidences0: Token confidences of image 0, shape :math:`(B, M)`.+ confidences1: Token confidences of image 1, shape :math:`(B, N)`.+ layer_index: Index of the layer that computed the confidences.+ num_points: Number of keypoints of one pair that the unconfident points are counted against.++ Returns:+ Whether every pair has a ratio of confident points above ``depth_confidence``: each pair counts its own+ points below the confidence threshold of the layer.+ """confidences = torch.cat([confidences0, confidences1], -1)threshold = self.confidence_thresholds[layer_index]- ratio_confident = 1.0 - (confidences < threshold).float().sum() / num_points- return ratio_confident > self.conf.depth_confidence+ ratio_confident = 1.0 - (confidences < threshold).float().sum(-1) / num_points+ return (ratio_confident > self.conf.depth_confidence).all()def pruning_min_kpts(self, device: torch.device) -> int:"""Return the minimum keypoint count needed before pruning is enabled.diff --git a/tests/feature/test_lightglue.py b/tests/feature/test_lightglue.pyindex 9e9b5b6d2..ced926706 100644--- a/tests/feature/test_lightglue.py+++ b/tests/feature/test_lightglue.py@@ -734,7 +734,8 @@ class TestConventionsLightGlue(BaseTester):return torch.cat(columns, 1)[None].to(device, dtype)def test_convention_lightglue_image_size_is_width_height(self, device, dtype):- lg = LightGlue(None, input_dim=8, descriptor_dim=8, n_layers=1, num_heads=1, flash=False)+ # Without point pruning, the batch of two pairs runs as one, and the hook sees both items of each image.+ lg = LightGlue(None, input_dim=8, descriptor_dim=8, n_layers=1, num_heads=1, flash=False, width_confidence=-1)lg = lg.to(device, dtype).eval()seen = self._record_positional_encoding_inputs(lg)kpts = torch.tensor([[[300.0, 30.0], [20.0, 210.0], [160.0, 120.0]]], device=device, dtype=dtype)@@ -891,8 +892,6 @@ class TestLightGlueAllPrunedScoreDtype(BaseTester):@pytest.mark.parametrize("input_dim", [16, 8], ids=["input_dim_eq_descriptor_dim", "input_dim_ne_descriptor_dim"])@pytest.mark.parametrize("mp", [False, True], ids=["mp_off", "mp_on"])def test_all_points_pruned_gives_the_score_dtype_of_kept_points_5877(self, device, dtype, input_dim, mp):- if mp and device.type == "cpu" and dtype == torch.float16:- pytest.skip("a float16 model with mp=True on CPU raises (#5897)")TestLightGluePruningDtype._skip_without_empty_attention(device, dtype)model = self._model(device, dtype, input_dim, mp)kept = self._forward(model, True, device, dtype)@@ -928,43 +927,337 @@ class TestLightGlueAllPrunedScoreDtype(BaseTester):out = TestLightGluePruningDtype._forward(model, {"image0": empty, "image1": dict(empty)})assert TestLightGluePruningDtype._floating_dtypes(out) == {dtype}- def test_wart_lightglue_mixed_precision_cpu_float16_model_raises_5897(self, device, dtype):- if device.type != "cpu" or dtype != torch.float16:- pytest.skip("CPU autocast to bfloat16 meets a float16 model only on CPU")- # #5897: in the first layer, autocast's bfloat16 outputs meet float16 tensors: in the torch.cat that feeds the- # self-attention FFN when input_proj is an identity, and in that FFN's LayerNorm when it is a linear layer.- for input_dim, message in ((self._DIM, "prioritize"), (8, "mixed dtype")):- model = self._model(device, dtype, input_dim, mp=True)- with pytest.raises(RuntimeError, match=message):- self._forward(model, True, device, dtype)- # "keynet_affnet_hardnet" raises before the layers, in scale_laf, also for an image without descriptors.- with unittest.mock.patch("kornia.feature.lightglue.load_state_dict_from_url", return_value={}):- keynet = LightGlue("keynet_affnet_hardnet", n_layers=1, mp=True).to(device, dtype).eval()+ @staticmethod+ def _record_autocast(model, device_type):+ # The autocast state the first layer runs under.+ seen = []++ def hook(module, args):+ seen.append((torch.is_autocast_enabled(device_type), torch.get_autocast_dtype(device_type)))++ model.transformers[0].register_forward_pre_hook(hook)+ return seen++ @pytest.mark.parametrize("input_dim", [16, 8], ids=["input_dim_eq_descriptor_dim", "input_dim_ne_descriptor_dim"])+ def test_convention_lightglue_mixed_precision_cpu_float16_model_autocasts_to_float16_5897(self, device, input_dim):+ if device.type != "cpu":+ pytest.skip("the rule is CPU's: MPS and CUDA autocast to float16 for every model")+ # With mp=True on CPU, a float16 model autocasts to float16, and any other model to bfloat16, CPU autocast's+ # default. Autocast's bfloat16 outputs meeting the float16 tensors of a float16 model raised in the first layer.+ model = self._model(device, torch.float16, input_dim, mp=True)+ seen = self._record_autocast(model, device.type)+ out = self._forward(model, True, device, torch.float16)+ assert seen == [(True, torch.float16)]+ ref = self._forward(self._model(device, torch.float16, input_dim, mp=False), True, device, torch.float16)+ assert TestLightGluePruningDtype._floating_dtypes(out) == {torch.float16}+ assert (ref["matches0"] > -1).any()+ for key in ("matches0", "matches1"):+ self.assert_close(out[key], ref[key])+ # Autocast normalises the keypoints in float32 and promotes concatenations with float32 tensors, so the scores+ # round differently from the plain float16 pass, within two float16 steps at 1.+ for key in ("matching_scores0", "matching_scores1"):+ assert out[key].isfinite().all()+ self.assert_close(out[key], ref[key], rtol=0.0, atol=2e-3)+ float32 = self._model(device, torch.float32, input_dim, mp=True)+ seen = self._record_autocast(float32, device.type)+ self._forward(float32, True, device, torch.float32)+ assert seen == [(True, torch.bfloat16)]++ @pytest.mark.parametrize("input_dim", [16, 8], ids=["input_dim_eq_descriptor_dim", "input_dim_ne_descriptor_dim"])+ def test_convention_lightglue_mixed_precision_cpu_float16_model_takes_float32_descriptors_5897(+ self, device, input_dim+ ):+ if device.type != "cpu":+ pytest.skip("the rule is CPU's: MPS and CUDA autocast to float16 for every model")+ # Float16 autocast takes float32 keypoints and descriptors too, and the scores stay float16. Both runs get the+ # same values, which float16 represents exactly.+ model = self._model(device, torch.float16, input_dim, mp=True)+ g = torch.Generator().manual_seed(1)+ desc = torch.randn(1, 6, input_dim, generator=g)+ desc[..., 0] = 30.0 # layer 0 keeps every point+ image = {"keypoints": torch.rand(1, 6, 2, generator=g) * 100, "descriptors": desc}+ size = torch.tensor([[100, 100]], device=device)+ out, ref = (+ TestLightGluePruningDtype._forward(model, {"image0": data, "image1": dict(data)})+ for data in (+ {"image_size": size, **{key: value.half().to(device, input_dtype) for key, value in image.items()}}+ for input_dtype in (torch.float32, torch.float16)+ )+ )+ assert out["matching_scores0"].dtype == torch.float16+ assert out["scores"][0].dtype == torch.float16+ assert (ref["matches0"] > -1).any()+ for key in ("matches0", "matches1"):+ self.assert_close(out[key], ref[key])+ # Equal on torch 2.5.1, 2.9.1 and 2.14 here; two float16 steps at 1 leave room for kernels that round otherwise.+ for key in ("matching_scores0", "matching_scores1"):+ self.assert_close(out[key], ref[key], rtol=0.0, atol=2e-3)++ def test_wart_lightglue_mixed_precision_cpu_other_half_dtype_descriptors_raise_5929(self, device):+ if device.type != "cpu":+ pytest.skip("MPS and CUDA cast the descriptors to float16 under autocast")+ # #5929: with input_proj an identity, descriptors of the other half dtype than autocast's reach a torch.cat of+ # the first layer, which autocast rejects: float16 ones with a float32 model, bfloat16 ones with a float16 one.+ for model_dtype, input_dtype in ((torch.float32, torch.float16), (torch.float16, torch.bfloat16)):+ model = self._model(device, model_dtype, self._DIM, mp=True)+ with pytest.raises(RuntimeError, match="prioritize"):+ self._forward(model, True, device, input_dtype)++ def test_convention_lightglue_mixed_precision_cpu_float16_model_reads_lafs_5897(self, device):+ if device.type != "cpu":+ pytest.skip("the rule is CPU's: MPS and CUDA autocast to float16 for every model")+ # "keynet_affnet_hardnet" reads the LAFs before the layers, where bfloat16 autocast raised for a float16 model,+ # also for an image without descriptors.++ def keynet(mp):+ torch.manual_seed(0)+ with unittest.mock.patch("kornia.feature.lightglue.load_state_dict_from_url", return_value={}):+ return LightGlue("keynet_affnet_hardnet", n_layers=2, mp=mp).to(device, torch.float16).eval()++ g = torch.Generator().manual_seed(1)+ kpts = torch.rand(1, 6, 2, generator=g) * 80 + 10+ lafs = laf_from_center_scale_ori(+ kpts, torch.rand(1, 6, 1, 1, generator=g) * 5 + 1, torch.rand(1, 6, 1, generator=g) * 360+ )+ image = {+ "keypoints": kpts.to(device, torch.float16),+ "descriptors": torch.randn(1, 6, 128, generator=g).to(device, torch.float16),+ "image_size": torch.tensor([[100, 100]], device=device),+ "lafs": lafs.to(device, torch.float16),+ }+ model = keynet(True)+ seen = self._record_autocast(model, device.type)+ out = TestLightGluePruningDtype._forward(model, {"image0": image, "image1": dict(image)})+ assert seen == [(True, torch.float16)]+ ref = TestLightGluePruningDtype._forward(keynet(False), {"image0": image, "image1": dict(image)})+ assert TestLightGluePruningDtype._floating_dtypes(out) == {torch.float16}+ assert (ref["matches0"] > -1).any()+ for key in ("matches0", "matches1"):+ self.assert_close(out[key], ref[key])+ for key in ("matching_scores0", "matching_scores1"): # tolerance as for the other configurations+ assert out[key].isfinite().all()+ self.assert_close(out[key], ref[key], rtol=0.0, atol=2e-3)empty = {- "keypoints": torch.empty(1, 0, 2, device=device, dtype=dtype),- "descriptors": torch.empty(1, 0, 128, device=device, dtype=dtype),+ "keypoints": torch.empty(1, 0, 2, device=device, dtype=torch.float16),+ "descriptors": torch.empty(1, 0, 128, device=device, dtype=torch.float16),"image_size": torch.tensor([[100, 100]], device=device),- "lafs": torch.empty(1, 0, 2, 3, device=device, dtype=dtype),+ "lafs": torch.empty(1, 0, 2, 3, device=device, dtype=torch.float16),}- with pytest.raises(RuntimeError, match="prioritize"):- TestLightGluePruningDtype._forward(keynet, {"image0": empty, "image1": dict(empty)})-- def test_wart_lightglue_batch_with_point_pruning_raises_5898(self, device, dtype):- if device.type == "cuda":- pytest.skip("on CUDA, point pruning starts only above 1024 keypoints")- # #5898: the pruning bookkeeping keeps one index row for the whole batch, so once pruning has run and kept- # points, the second pair raises. The same model matches each pair on its own.- model = self._model(device, dtype, self._DIM, mp=False)- g = torch.Generator().manual_seed(1)- desc = torch.randn(2, 6, self._DIM, generator=g)- desc[..., 0] = 30.0 # layer 0 keeps every point- batch = {- "keypoints": (torch.rand(2, 6, 2, generator=g) * 100).to(device, dtype),- "descriptors": desc.to(device, dtype),- "image_size": torch.tensor([[100, 100], [100, 100]], device=device),+ out = TestLightGluePruningDtype._forward(keynet(True), {"image0": empty, "image1": dict(empty)})+ assert out["matching_scores0"].shape == (1, 0)+ assert TestLightGluePruningDtype._floating_dtypes(out) == {torch.float16}+++class TestLightGlueBatchedPairs(BaseTester):+ """Each pair of a batch gives the matches it gives on its own (#5898).++ The model is the one of :class:`TestLightGluePruningDtype`: two layers, and layer 0 prunes a point of matchability+ -20 (descriptor dimension 0) unless its token confidence (dimension 1) is -20 too, which also counts against early+ stopping. Image 1 of a pair is image 0 permuted, and a point kept in both images matches its copy. Each pair has its+ own descriptors, keypoints, permutation, and matchable and confident points.+ """++ _M = 16++ def _pair(self, device, dtype, seed, matchable, confident, confident1=None, size=(320, 240)):+ # confident1, in the order of image 0, overrides the confidences that image 1 copies from image 0. The+ # keypoints lie in the (W, H) = (320, 240) top-left corner of an image of the given size.+ g = torch.Generator().manual_seed(seed)+ desc = 3 * torch.randn(1, self._M, 128, generator=g)+ desc[0, :, 0] = 20 * torch.tensor(matchable, dtype=torch.float32)+ desc[0, :, 1] = 20 * torch.tensor(confident, dtype=torch.float32)+ kpts = torch.rand(1, self._M, 2, generator=g) * torch.tensor([320.0, 240.0])+ perm = torch.randperm(self._M, generator=g)+ desc1 = desc.clone()+ if confident1 is not None:+ desc1[0, :, 1] = 20 * torch.tensor(confident1, dtype=torch.float32)+ size = torch.tensor([size], device=device)+ data = {+ "image0": {"keypoints": kpts.to(device, dtype), "descriptors": desc.to(device, dtype), "image_size": size},+ "image1": {+ "keypoints": kpts[:, perm].to(device, dtype),+ "descriptors": desc1[:, perm].to(device, dtype),+ "image_size": size,+ },+ }+ return data, perm++ @staticmethod+ def _stack(pairs):+ return {+ image: {key: torch.cat([p[image][key] for p in pairs]) for key in pairs[0][image]} for image in pairs[0]}++ @staticmethod+ def _forward(model, data, pruning_threshold=-1):+ # -1 prunes at any number of keypoints; a larger threshold, such as CUDA's, turns pruning off below it.+ thresholds = dict.fromkeys(LightGlue.pruning_keypoint_thresholds, pruning_threshold)+ with torch.no_grad(), unittest.mock.patch.dict(LightGlue.pruning_keypoint_thresholds, thresholds):+ return model(data)++ def _assert_pair(self, out, k, single, exact):+ # Pair k of a batch output against the output of that pair on its own.+ tol = {"rtol": 0.0, "atol": 0.0} if exact else {}+ for key in ("matches0", "matches1", "prune0", "prune1"):+ self.assert_close(out[key][k : k + 1], single[key], rtol=0.0, atol=0.0)+ self.assert_close(out["matches"][k], single["matches"][0], rtol=0.0, atol=0.0)+ for key in ("matching_scores0", "matching_scores1"):+ self.assert_close(out[key][k : k + 1], single[key], **tol)+ self.assert_close(out["scores"][k], single["scores"][0], **tol)++ def test_convention_lightglue_batch_with_point_pruning_matches_each_pair_5898(self, device, dtype):+ model = TestLightGluePruningDtype._model(device, dtype)+ matchable = [(1, -1) * 8, (1, 1, 1, -1) * 4, (1, -1) * 8]+ confident = [TestLightGluePruningDtype._CONFIDENT, (1,) * 7 + (-1,) + (1,) * 8, (1,) * 16]+ # Pair 0 prunes 6 points of each image and pair 1 prunes 3; pair 2 has no unconfident point, so early stopping+ # ends it after layer 0, before any pruning. Pair 1 has its own image size.+ sizes = [(320, 240), (400, 300), (320, 240)]+ pairs = [self._pair(device, dtype, k, matchable[k], confident[k], size=sizes[k]) for k in range(3)]+ singles = [self._forward(model, data) for data, _ in pairs]+ assert [single["stop"] for single in singles] == [2, 2, 1]+ # A batch can give one image size for all its pairs.+ shared_size = self._stack([pairs[0][0], pairs[2][0]])+ for image in shared_size.values():+ image["image_size"] = image["image_size"][:1]+ for batch, members in ((shared_size, [0, 2]), (self._stack([data for data, _ in pairs]), [0, 1, 2])):+ out = self._forward(model, batch)+ # The pairs keep different numbers of points, so they have no common log assignment, and stop is the+ # largest number of layers a pair ran.+ assert "log_assignment" not in out+ assert out["stop"] == 2+ for row, k in enumerate(members):+ self._assert_pair(out, row, singles[k], exact=True)+ # The pairs that ran both layers match each point they kept to its copy, as an index into their own input.+ for row, k in enumerate(members):+ if k == 2:+ continue+ perm = pairs[k][1]+ pruned = (torch.tensor(matchable[k]) < 0) & (torch.tensor(confident[k]) > 0)+ self.assert_close(out["prune0"][row], torch.where(pruned, 1, 2).to(device))+ self.assert_close(out["matches0"][row], torch.where(pruned, -1, torch.argsort(perm)).to(device))+ self.assert_close(out["matches1"][row], torch.where(pruned[perm], -1, perm).to(device))+ kept = torch.where(~pruned)[0]+ self.assert_close(out["matches"][row], torch.stack([kept, torch.argsort(perm)[kept]], -1).to(device))++ def test_convention_lightglue_batch_with_a_pair_whose_points_are_all_pruned_5898(self, device, dtype):+ TestLightGluePruningDtype._skip_without_empty_attention(device, dtype)+ # Without early stopping, no low-confidence point is kept, and layer 0 prunes every point of the second pair.+ model = TestLightGluePruningDtype._model(device, dtype, depth_confidence=-1)+ pairs = [+ self._pair(device, dtype, k, matchable, TestLightGluePruningDtype._CONFIDENT)+ for k, matchable in enumerate([(1, -1) * 8, (-1,) * 16])+ ]+ singles = [self._forward(model, data) for data, _ in pairs]+ assert [("log_assignment" in single) for single in singles] == [True, False]+ out = self._forward(model, self._stack([data for data, _ in pairs]))+ assert "log_assignment" not in out+ for k in range(2):+ self._assert_pair(out, k, singles[k], exact=True)+ self.assert_close(out["matches0"][1], torch.full((self._M,), -1, device=device))+ assert out["scores"][1].shape == (0,)++ def test_convention_lightglue_batch_below_the_pruning_threshold_runs_together_5898(self, device, dtype):+ # Point pruning runs only in an image with more keypoints than the device threshold (on CUDA, 1536 by default+ # and 1024 with flash=False): below it, a batch runs as one, with its log assignment, and gives the prune0 and+ # prune1 of each pair on its own.+ model = TestLightGluePruningDtype._model(device, dtype)+ matchable = [(1, -1) * 8, (1, 1, 1, -1) * 4]+ pairs = [self._pair(device, dtype, k, matchable[k], TestLightGluePruningDtype._CONFIDENT) for k in range(2)]+ singles = [self._forward(model, data, pruning_threshold=1000) for data, _ in pairs]+ out = self._forward(model, self._stack([data for data, _ in pairs]), pruning_threshold=1000)+ assert out["log_assignment"].shape == (2, self._M + 1, self._M + 1)+ assert out["stop"] == 2for k in range(2):- pair = {key: value[k : k + 1] for key, value in batch.items()}- TestLightGluePruningDtype._forward(model, {"image0": pair, "image1": dict(pair)})- with pytest.raises(IndexError):- TestLightGluePruningDtype._forward(model, {"image0": batch, "image1": dict(batch)})+ self._assert_pair(out, k, singles[k], exact=False)+ self.assert_close(out["log_assignment"][k : k + 1], singles[k]["log_assignment"])+ self.assert_close(out["prune0"], torch.ones(2, self._M, device=device, dtype=torch.long))++ def test_convention_lightglue_batch_stops_early_when_every_pair_meets_its_criterion_5898(self, device, dtype):+ # Without pruning, a batch runs as one. Early stopping after layer 0 needs more than 95 % of the 32 points of a+ # pair confident: one unconfident point passes, two do not. The batch stops once every pair passes.+ model = TestLightGluePruningDtype._model(device, dtype, width_confidence=-1)+ everywhere = (1,) * self._M+ pairs = [+ self._pair(device, dtype, k, everywhere, unconfident, everywhere)+ for k, unconfident in enumerate(+ [(1,) * 3 + (-1,) + (1,) * 12, (1,) * 5 + (-1,) + (1,) * 10, (-1, -1) + (1,) * 14]+ )+ ]+ singles = [self._forward(model, data) for data, _ in pairs]+ assert [single["stop"] for single in singles] == [1, 1, 2]+ out = self._forward(model, self._stack([pairs[0][0], pairs[1][0]]))+ assert out["stop"] == 1+ for k in range(2):+ self._assert_pair(out, k, singles[k], exact=False)+ # A pair runs as many layers as its batch: pair 0 stops after layer 0 on its own, and after layer 1 next to a+ # pair that does not stop.+ out = self._forward(model, self._stack([pairs[0][0], pairs[2][0]]))+ assert out["stop"] == 2+ self._assert_pair(out, 1, singles[2], exact=False)++ @pytest.mark.parametrize("batch_size", [1, 2])+ def test_convention_lightglue_input_without_keypoints_reads_no_pruning_threshold_5898(+ self, device, dtype, batch_size+ ):+ # The pruning threshold of the device is read only once there are keypoints, so an input without any returns+ # empty matches also on a device type without a threshold.+ empty = {+ "keypoints": torch.empty(batch_size, 0, 2, device=device, dtype=dtype),+ "descriptors": torch.empty(batch_size, 0, 128, device=device, dtype=dtype),+ "image_size": torch.tensor([[320, 240]] * batch_size, device=device),+ }+ model = TestLightGluePruningDtype._model(device, dtype)+ with torch.no_grad(), unittest.mock.patch.dict(LightGlue.pruning_keypoint_thresholds, clear=True):+ out = model({"image0": empty, "image1": dict(empty)})+ assert out["matches0"].shape == (batch_size, 0)+ assert [tuple(m.shape) for m in out["matches"]] == [(0, 2)] * batch_size++ @pytest.mark.parametrize("features", ["sift", "add_laf"])+ def test_convention_lightglue_batch_with_point_pruning_gives_each_pair_its_inputs_5898(+ self, device, dtype, features+ ):+ # Each pair of a batch that prunes gets its own scales and orientations ("sift") or LAFs (add_laf), and its own+ # image, which gives the image size.+ torch.manual_seed(0)+ with unittest.mock.patch("kornia.feature.lightglue.load_state_dict_from_url", return_value={}):+ if features == "sift":+ model = LightGlue("sift", n_layers=2)+ else:+ model = LightGlue(None, input_dim=128, add_laf=True, n_layers=2)+ model = model.to(device, dtype).eval()+ g = torch.Generator().manual_seed(0)+ b, m = 2, 12++ def image():+ kpts = torch.rand(b, m, 2, generator=g) * torch.tensor([320.0, 240.0])+ scale = torch.rand(b, m, 1, 1, generator=g) * 10 + 2+ ori = torch.rand(b, m, 1, generator=g) * 360 - 180+ data = {+ "keypoints": kpts,+ "descriptors": torch.randn(b, m, 128, generator=g),+ "image": torch.zeros(b, 1, 240, 320),+ "scales": scale[..., 0, 0],+ "oris": torch.deg2rad(ori[..., 0]),+ "lafs": laf_from_center_scale_ori(kpts, scale, ori),+ }+ return {key: value.to(device, dtype) for key, value in data.items()}++ batch = {"image0": image(), "image1": image()}+ singles = [+ self._forward(model, {name: {key: v[k : k + 1] for key, v in img.items()} for name, img in batch.items()})+ for k in range(b)+ ]+ out = self._forward(model, batch)+ assert "log_assignment" not in out+ for k in range(b):+ self._assert_pair(out, k, singles[k], exact=True)++ def test_wart_lightglue_static_lengths_early_stop_counts_padding_5930(self, device, dtype):+ # #5930: every point of this pair is confident, so it stops after layer 0. Padded to the static length 64, the+ # padded positions, unconfident here, count against its 32 points, and it runs both layers.+ model = TestLightGluePruningDtype._model(device, dtype, width_confidence=-1)+ everywhere = (1,) * self._M+ data, _ = self._pair(device, dtype, 0, everywhere, everywhere)+ assert self._forward(model, data)["stop"] == 1+ model.static_lengths = (64,) # what compile() sets; the padded layers run here without compiling+ assert self._forward(model, data)["stop"] == 2