π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
fix(feature): SOLD2.match returns int64 for empty segment sets; XFeat dense multiscale keeps top_k (#5926)
Dmytro Mishkin4024ecaa8bbb
diff --git a/changelog.d/5926.breaking.md b/changelog.d/5926.breaking.mdnew file mode 100644index 000000000..4b3a62f39--- /dev/null+++ b/changelog.d/5926.breaking.md@@ -0,0 +1 @@+`XFeat()` now starts in evaluation mode, like `XFeat.from_pretrained()` and the reference implementation. It used to start in training mode, so `detectAndCompute`, `detectAndComputeDense` and the `match_*` methods normalised with batch statistics (each keypoint depended on the rest of the batch), updated the BatchNorm running statistics on every call, and a single match raised "Expected more than 1 value per channel when training". Call `.train()` to train.diff --git a/changelog.d/5926.fixed.md b/changelog.d/5926.fixed.mdnew file mode 100644index 000000000..819a9de1b--- /dev/null+++ b/changelog.d/5926.fixed.md@@ -0,0 +1 @@+`SOLD2.match` now returns an int64 tensor when either set of segments is empty (it returned int32), and `XFeat.detectAndComputeDense` with `multiscale=True` no longer returns every cell of a scale whose share of a small positive `top_k` rounds down to 0: the budget is split `int(0.2 * top_k)` / the rest, so for a positive `top_k` the result never exceeds it (zero and negative values still keep every cell) (a default `top_k=4096` now yields 4096 keypoints instead of 4095 on images with enough cells).diff --git a/kornia/feature/sold2/sold2.py b/kornia/feature/sold2/sold2.pyindex 3e543c36b..d3b775ce2 100644--- a/kornia/feature/sold2/sold2.py+++ b/kornia/feature/sold2/sold2.py@@ -49,12 +49,11 @@ class SOLD2(nn.Module):``dense_desc``, :math:`(B, 128, H / 4, W / 4)`, which is not normalized.- ``match`` takes segments as :meth:`forward` returns them and the descriptor map of one image each. Itreturns an int64 tensor :math:`(N_1,)`: for each segment of ``line_seg1``, the index of its match in- ``line_seg2``, or ``-1``.- - Known defects: ``match`` returns int32 when either set of segments is empty- (`#5915 <https://github.com/kornia/kornia/issues/5915>`_). On CPU, it passes float16 and bfloat16- descriptor maps to torch's ``grid_sample`` without an upcast: the half-precision kernel can return wrong- values, NaN or overflow, and where torch has none the call raises- (`#5810 <https://github.com/kornia/kornia/issues/5810>`_).+ ``line_seg2``, or ``-1``. It is int64 also when either set of segments is empty: an empty tensor when+ ``line_seg1`` is, ``-1`` for every segment of ``line_seg1`` when ``line_seg2`` is.+ - Known defects: on CPU, ``match`` passes float16 and bfloat16 descriptor maps to torch's ``grid_sample``+ without an upcast: the half-precision kernel can return wrong values, NaN or overflow, and where torch has+ none the call raises (`#5810 <https://github.com/kornia/kornia/issues/5810>`_).Args:config: :class:`~kornia.feature.sold2.structures.DetectorCfg`, or a dict of its fields, specifying@@ -211,9 +210,9 @@ class WunschLineMatcher(nn.Module):# Default case when an image has no linesif len(line_seg1) == 0:- return torch.empty(0, dtype=torch.int, device=device)+ return torch.empty(0, dtype=torch.long, device=device)if len(line_seg2) == 0:- return -torch.ones(len(line_seg1), dtype=torch.int, device=device)+ return -torch.ones(len(line_seg1), dtype=torch.long, device=device)# Sample points regularly along each lineline_points1, valid_points1 = self.sample_line_points(line_seg1)diff --git a/kornia/feature/xfeat.py b/kornia/feature/xfeat.pyindex 0de316ebb..f635ad9a0 100644--- a/kornia/feature/xfeat.py+++ b/kornia/feature/xfeat.py@@ -301,6 +301,11 @@ class XFeat(nn.Module):Convention:- XFeat defines no ``forward``: call :meth:`detectAndCompute` or :meth:`detectAndComputeDense`.+ - ``XFeat()`` starts in evaluation mode, like :meth:`from_pretrained` and the reference implementation. The+ inference methods are run under ``torch.inference_mode``; in training mode BatchNorm would normalise with+ the statistics of the batch, so a keypoint or match would depend on the rest of the batch, update its+ running statistics on every call, and raise on a single match. Call ``.train()`` to opt in explicitly; the+ methods then behave as torch's training-mode BatchNorm does.- The image is :math:`(B, C, H, W)` with any channel count. Each extraction resizes the image it getsbilinearly to :math:`(H', W')`: ``H`` and ``W`` rounded down to multiples of 32, with a minimum of 32.:class:`XFeatModel` then averages the channels and instance-normalises the result, so an affine change of the@@ -320,13 +325,13 @@ class XFeat(nn.Module):at ``8 * (j, i)``, times the same ratio: the top-left pixel of the cell, not its centre. It keeps the``top_k`` cells of highest reliability, or every cell when there are fewer or ``top_k`` is below 1. Withthe default ``multiscale=True``, it rescales the image bilinearly by 0.6 and by 1.3, runs that extraction- on each with ``top_k`` set to ``int(0.2 * top_k)`` and ``int(0.8 * top_k)``, and divides each keypoint by- its factor; ``scales`` is ``1 / 0.6`` or ``1 / 1.3`` for each keypoint. A scale with fewer cells than its- share returns all of them, and the truncation can lose one, so there can be fewer than ``top_k`` keypoints.- Its descriptors are not normalised.- - Known defects: with ``multiscale=True``, a share that rounds down to 0 keeps every cell of its scale, so a- ``top_k`` from 1 to 4 returns all the cells of the 0.6 extraction, and ``top_k=1`` those of both- (`#5924 <https://github.com/kornia/kornia/issues/5924>`_).+ on each with ``int(0.2 * top_k)`` and the remaining ``top_k - int(0.2 * top_k)`` cells, and divides each+ keypoint by its factor; ``scales`` is ``1 / 0.6`` or ``1 / 1.3`` for each keypoint. A share of 0 yields no+ cell from its scale, and a scale with fewer cells than its share returns all of them, so there are never+ more than ``top_k`` keypoints, and exactly ``top_k`` when both scales have enough cells. A ``top_k`` below+ 1 keeps every cell of both scales. Its descriptors are not normalised. The reference implementation gives+ the 1.3 scale ``int(0.8 * top_k)`` and reads a share of 0 as "every cell"; kornia does not, because that+ returns more keypoints than ``top_k`` asks for.Args:top_k: maximum number of keypoints to keep per image. Default: ``4096``.@@ -361,6 +366,8 @@ class XFeat(nn.Module):self.interpolator = InterpolateSparse2d("bicubic")self._nearest = InterpolateSparse2d("nearest")self._bilinear = InterpolateSparse2d("bilinear")+ # like :meth:`from_pretrained` and the reference: the inference methods must not run BatchNorm in training mode+ self.eval()@classmethoddef from_pretrained(cls, top_k: int = 4096, detection_threshold: float = 0.05) -> XFeat:@@ -480,16 +487,21 @@ class XFeat(nn.Module):batched_matches.append((idx0_b, idx1_b))return batched_matches- def _extract_dense(self, x: torch.Tensor, top_k: int = 8000) -> Tuple[torch.Tensor, torch.Tensor]:- """Extract coarse descriptors from an FPN feature map, top-k by reliability."""- if top_k < 1:- top_k = 100_000_000+ def _extract_dense(self, x: torch.Tensor, top_k: Optional[int] = 8000) -> Tuple[torch.Tensor, torch.Tensor]:+ """Extract coarse descriptors from an FPN feature map, top-k by reliability.++ ``top_k=None`` keeps every cell; ``top_k=0`` keeps none.+ """x, rh1, rw1 = self._preprocess_tensor(x)M1, _K1, H1 = self.net(x)B, C, _H1, _W1 = M1.shape+ if top_k is None:+ top_k = _H1 * _W1xy1 = (self._create_xy(_H1, _W1, M1.device) * 8).expand(B, -1, -1)M1 = M1.permute(0, 2, 3, 1).reshape(B, -1, C)H1 = H1.permute(0, 2, 3, 1).reshape(B, -1)+ if top_k < 1:+ return torch.zeros(B, 0, 2, device=M1.device), M1.new_zeros(B, 0, C)_, top_k_idx = torch.topk(H1, k=min(H1.shape[1], top_k), dim=-1)feats = torch.gather(M1, 1, top_k_idx[..., None].expand(-1, -1, C))mkpts = torch.gather(xy1, 1, top_k_idx[..., None].expand(-1, -1, 2))@@ -497,13 +509,28 @@ class XFeat(nn.Module):return mkpts, featsdef _extract_dualscale(- self, x: torch.Tensor, top_k: int, s1: float = 0.6, s2: float = 1.3+ self, x: torch.Tensor, top_k: Optional[int], s1: float = 0.6, s2: float = 1.3) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor]:- """Extract dense features at two scales and merge."""- x1 = F.interpolate(x, scale_factor=s1, align_corners=False, mode="bilinear")+ """Extract dense features at two scales and merge.++ ``top_k`` is split into ``int(0.2 * top_k)`` for the first scale and the rest for the second;+ ``None`` keeps every cell of both. A zero share yields no cell from its scale.+ """+ if top_k is None:+ k1 = k2 = None+ else:+ k1 = int(top_k * 0.20)+ k2 = int(top_k) - k1x2 = F.interpolate(x, scale_factor=s2, align_corners=False, mode="bilinear")- mkpts_1, feats_1 = self._extract_dense(x1, int(top_k * 0.20))- mkpts_2, feats_2 = self._extract_dense(x2, int(top_k * 0.80))+ mkpts_2, feats_2 = self._extract_dense(x2, k2)+ if k1 == 0:+ # no cell is asked of the first scale: skip its resize and backbone pass; the empty outputs take the+ # dtype and device of the computed scale, so the concatenation does not change the output dtype+ mkpts_1 = mkpts_2.new_empty((mkpts_2.shape[0], 0, 2))+ feats_1 = feats_2.new_empty((feats_2.shape[0], 0, feats_2.shape[-1]))+ else:+ x1 = F.interpolate(x, scale_factor=s1, align_corners=False, mode="bilinear")+ mkpts_1, feats_1 = self._extract_dense(x1, k1)mkpts = torch.cat([mkpts_1 / s1, mkpts_2 / s2], dim=1)sc1 = torch.ones(mkpts_1.shape[:2], device=mkpts_1.device) * (1 / s1)sc2 = torch.ones(mkpts_2.shape[:2], device=mkpts_2.device) * (1 / s2)@@ -604,7 +631,11 @@ class XFeat(nn.Module):Args:x: image tensor of shape :math:`(B, C, H, W)`.- top_k: number of features to keep (overrides ``self.top_k``).+ top_k: number of features to keep (overrides ``self.top_k``). A value below 1 keeps every cell. With+ ``multiscale=True`` the budget is split between the scales, ``int(0.2 * top_k)`` for the 0.6x+ extraction and the rest for the 1.3x one, so the result never exceeds a positive ``top_k``; a scale+ with a budget of 0 contributes nothing. This departs from the reference implementation, which+ gives the 1.3x scale ``int(0.8 * top_k)`` and reads a budget that rounds down to 0 as "every cell".multiscale: use dual-scale (0.6x and 1.3x) extraction. Default: ``True``.Returns:@@ -616,10 +647,12 @@ class XFeat(nn.Module):"""if top_k is None:top_k = self.top_k+ # a top_k below 1 means every cell; resolve it once, before the budget is split between the scales+ budget = top_k if top_k >= 1 else Noneif multiscale:- mkpts, sc, feats = self._extract_dualscale(x, top_k)+ mkpts, sc, feats = self._extract_dualscale(x, budget)else:- mkpts, feats = self._extract_dense(x, top_k)+ mkpts, feats = self._extract_dense(x, budget)sc = torch.ones(mkpts.shape[:2], device=mkpts.device)return {"keypoints": mkpts, "descriptors": feats, "scales": sc}diff --git a/tests/feature/test_sold2.py b/tests/feature/test_sold2.pyindex 3f092e4f9..4db4d5838 100644--- a/tests/feature/test_sold2.py+++ b/tests/feature/test_sold2.py@@ -425,9 +425,9 @@ class TestConventionsSOLD2(BaseTester):assert matches.shape == (2,)assert ((matches >= -1) & (matches < 3)).all()- def test_wart_sold2_match_returns_int32_when_a_set_of_segments_is_empty_5915(self, device, dtype):- # SOLD2.match returns an int64 index per segment of line_seg1, but int32 when either set of segments is empty- # (#5915): an empty tensor when image 1 has no segments, -1 per segment when image 2 has none.+ def test_convention_sold2_match_returns_int64_when_a_set_of_segments_is_empty(self, device, dtype):+ # SOLD2.match returns an int64 index per segment of line_seg1, also when either set of segments is empty:+ # an empty tensor when image 1 has no segments, -1 per segment when image 2 has none (#5915).model = SOLD2(pretrained=False)segments = torch.tensor([[[10.0, 10.0], [50.0, 90.0]], [[20.0, 70.0], [55.0, 20.0]]], device=device)maps = torch.rand(2, 1, 128, 16, 24, device=device, dtype=dtype)@@ -437,9 +437,9 @@ class TestConventionsSOLD2(BaseTester):(segments[:0], segments[:0], []),):matches = model.match(line_seg1, line_seg2, maps[0], maps[1])- assert matches.dtype == torch.int32+ assert matches.dtype == torch.int64assert matches.device == maps.deviceassert matches.tolist() == expected- # two non-empty sets give int64 (float32 maps: torch 2.5.1 has no CPU half grid_sample)+ # two non-empty sets give int64 as well (float32 maps: torch 2.5.1 has no CPU half grid_sample)matches = model.match(segments, segments, maps[0].float(), maps[1].float())assert matches.dtype == torch.int64diff --git a/tests/feature/test_xfeat.py b/tests/feature/test_xfeat.pyindex 9cd1f3331..d4cd83ea7 100644--- a/tests/feature/test_xfeat.py+++ b/tests/feature/test_xfeat.py@@ -551,7 +551,7 @@ class TestConventionsXFeat(BaseTester):self, device, dtype):# multiscale=True (the default) is the multiscale=False extraction of the image rescaled by 0.6 and by 1.3, with- # int(0.2 * top_k) and int(0.8 * top_k) cells, each keypoint divided by its factor; scales is 1 / factor.+ # int(0.2 * top_k) and the remaining cells, each keypoint divided by its factor; scales is 1 / factor.torch.manual_seed(0)xfeat = XFeat().to(device).eval()image = torch.rand(1, 3, 160, 224, device=device, dtype=dtype)@@ -570,24 +570,148 @@ class TestConventionsXFeat(BaseTester):def test_convention_xfeat_dense_keeps_the_top_k_cells_capped_by_the_cells_of_each_scale(self, device, dtype):# each extraction keeps its top_k cells, or every cell when there are fewer or top_k < 1; multiscale=True gives- # the 0.6 and 1.3 extractions int(0.2 * top_k) and int(0.8 * top_k). A 64 x 64 image has 16 cells at 0.6- # (resized to 32 x 32) and 64 at 1.3 (64 x 64), so a share above them is capped, and 9 gives 1 + 7 = 8.+ # the 0.6 and 1.3 extractions int(0.2 * top_k) and the rest. A 64 x 64 image has 16 cells at 0.6+ # (resized to 32 x 32) and 64 at 1.3 (64 x 64), so a share above them is capped, and 9 gives 1 + 8 = 9.torch.manual_seed(0)xfeat = XFeat().to(device).eval()image = torch.rand(1, 3, 64, 64, device=device, dtype=dtype)counts = {k: xfeat.detectAndComputeDense(image, k)["keypoints"].shape[1] for k in (0, 5, 9, 10, 20, 100, 4096)}- assert counts == {0: 80, 5: 5, 9: 8, 10: 10, 20: 20, 100: 80, 4096: 80}+ assert counts == {0: 80, 5: 5, 9: 9, 10: 10, 20: 20, 100: 80, 4096: 80}single = {k: xfeat.detectAndComputeDense(image, k, False)["keypoints"].shape[1] for k in (-1, 0, 1, 7, 100)}assert single == {-1: 64, 0: 64, 1: 1, 7: 7, 100: 64}- def test_wart_xfeat_dense_multiscale_keeps_every_cell_of_a_zero_share_5924(self, device, dtype):- # a share int(0.2 * top_k) or int(0.8 * top_k) that rounds down to 0 reaches the "top_k < 1 keeps every cell"- # rule, so a top_k from 1 to 4 returns all 16 cells of the 0.6 extraction, and 1 those of both scales+ def test_convention_xfeat_dense_multiscale_never_exceeds_a_small_positive_top_k(self, device, dtype):+ # the budget is split int(0.2 * top_k) for the 0.6 extraction and the rest for the 1.3 one, and a share of 0+ # yields no cell (#5924). A 64 x 64 image has 16 cells at 0.6 and 64 at 1.3, so every top_k below 80 is met.torch.manual_seed(0)xfeat = XFeat().to(device).eval()image = torch.rand(1, 3, 64, 64, device=device, dtype=dtype)- counts = {k: xfeat.detectAndComputeDense(image, k)["keypoints"].shape[1] for k in (1, 2, 4)}- assert counts == {1: 16 + 64, 2: 16 + 1, 4: 16 + 3}+ for k in (1, 2, 4, 5, 9, 10):+ out = xfeat.detectAndComputeDense(image, k)+ assert out["keypoints"].shape == (1, k, 2)+ assert out["descriptors"].shape == (1, k, 64)+ assert out["scales"].shape == (1, k)+ k1 = int(0.2 * k)+ assert (out["scales"][0, :k1] == 1 / 0.6).all()+ assert (out["scales"][0, k1:] == 1 / 1.3).all()+ # top_k <= 0 keeps every cell of both scales+ for k in (0, -3):+ assert xfeat.detectAndComputeDense(image, k)["keypoints"].shape == (1, 80, 2)++ def test_convention_xfeat_dense_multiscale_budgets_sum_to_top_k_and_zero_means_every_cell(self, device, dtype):+ # the default top_k of 4096 splits into 819 + 3277; main gave 819 + 3276 and dropped one keypoint+ xfeat = XFeat().to(device).eval()+ image = torch.rand(1, 3, 64, 64, device=device, dtype=dtype)+ seen = []+ real = xfeat._extract_dense+ xfeat._extract_dense = lambda x, top_k=8000: (seen.append(top_k), real(x, top_k))[1]+ for k in (None, 4096, 9, 0):+ seen.clear()+ xfeat.detectAndComputeDense(image, k)+ # the 1.3 scale is extracted first, then the 0.6 one+ assert seen == {None: [3277, 819], 4096: [3277, 819], 9: [8, 1], 0: [None, None]}[k]+ # multiscale=False resolves top_k < 1 the same way+ seen.clear()+ xfeat.detectAndComputeDense(image, -1, False)+ assert seen == [None]++ def test_smoke_xfeat_star_matching_runs_with_a_scale_of_zero_budget(self, device, dtype):+ torch.manual_seed(0)+ xfeat = XFeat().to(device).eval()+ image = torch.rand(1, 3, 64, 64, device=device, dtype=dtype)+ for k in (1, 4):+ mkpts0, mkpts1 = xfeat.match_xfeat_star(image, image, top_k=k)+ assert mkpts0.shape == mkpts1.shape+ assert mkpts0.shape[0] <= k++ def test_convention_xfeat_refines_matches_over_a_scale_of_zero_budget(self, device, dtype):+ # fine_conf=-1 keeps every match, so the refinement of real matches over an empty 0.6 scale is exercised+ torch.manual_seed(0)+ xfeat = XFeat().to(device).eval()+ image = torch.rand(2, 3, 64, 64, device=device, dtype=dtype)+ out = xfeat.detectAndComputeDense(image, 4)+ assert out["keypoints"].shape == (2, 4, 2)+ idxs = xfeat._batch_match(out["descriptors"], out["descriptors"])+ for b in range(2):+ refined = xfeat._refine_matches(out, out, idxs, b, fine_conf=-1.0)+ assert refined.shape[0] >= 1+ assert refined.shape[1] == 4+ assert torch.isfinite(refined).all()++ def test_convention_xfeat_dense_multiscale_accepts_a_float_top_k_and_keeps_float_keypoints(self, device, dtype):+ torch.manual_seed(0)+ xfeat = XFeat().to(device).eval()+ image = torch.rand(2, 3, 64, 64, device=device, dtype=dtype)+ out = xfeat.detectAndComputeDense(image, 10.0)+ assert out["keypoints"].shape == (2, 10, 2)+ empty = xfeat._extract_dense(image, 0)+ full = xfeat._extract_dense(image, 3)+ assert empty[0].dtype == full[0].dtype+ assert empty[1].dtype == full[1].dtype+ assert empty[0].device == full[0].device++ def test_convention_xfeat_dense_multiscale_skips_the_backbone_pass_of_a_scale_with_no_budget(self, device, dtype):+ torch.manual_seed(0)+ xfeat = XFeat().to(device).eval()+ image = torch.rand(1, 3, 64, 64, device=device, dtype=dtype)+ sizes = []+ xfeat.net.register_forward_hook(lambda module, inputs, output: sizes.append(tuple(inputs[0].shape[-2:])))+ xfeat.detectAndComputeDense(image, 4)+ assert sizes == [(64, 64)] # only the 1.3 scale (resized to 64 x 64 here) is run+ sizes.clear()+ xfeat.detectAndComputeDense(image, 5)+ assert len(sizes) == 2++ def test_convention_xfeat_default_constructor_is_in_eval_mode_and_inference_does_not_touch_batchnorm_stats(+ self, device, dtype+ ):+ # XFeat() starts in eval mode like XFeat.from_pretrained and the reference: BatchNorm would otherwise use batch+ # statistics (each keypoint depends on the rest of the batch), update its running statistics on every+ # inference call, and raise on a single match.+ torch.manual_seed(0)+ xfeat = XFeat()+ assert not xfeat.training+ xfeat = xfeat.to(device)+ image = torch.rand(2, 3, 64, 64, device=device)+ before = {k: v.clone() for k, v in xfeat.state_dict().items()}+ xfeat.detectAndCompute(image)+ xfeat.detectAndComputeDense(image, 10)+ xfeat.match_xfeat_star(image, image, top_k=1)+ for k, v in xfeat.state_dict().items():+ assert torch.equal(v, before[k]), k+ assert xfeat.train().training # .train() stays the explicit opt-in++ def test_smoke_xfeat_star_default_constructor_top_k_1_batched(self, device, dtype):+ torch.manual_seed(0)+ xfeat = XFeat().to(device)+ image = torch.rand(2, 3, 64, 64, device=device)+ matches = xfeat.match_xfeat_star(image, image, top_k=1)+ assert len(matches) == 2+ for m in matches:+ assert m.shape[0] <= 1++ def test_convention_xfeat_dense_multiscale_descriptor_dtype_is_the_same_on_both_sides_of_a_zero_share(self, device):+ # under autocast the backbone's output dtype is not the parameters' dtype; the empty scale must not change it+ if torch.device(device).type != "cpu":+ pytest.skip("CPU autocast")+ torch.manual_seed(0)+ xfeat = XFeat().to(device)+ image = torch.rand(2, 3, 64, 64, device=device)+ with torch.autocast("cpu", dtype=torch.bfloat16):+ small = xfeat.detectAndComputeDense(image, 4)+ large = xfeat.detectAndComputeDense(image, 5)+ assert small["descriptors"].dtype == large["descriptors"].dtype+ assert small["keypoints"].dtype == large["keypoints"].dtype++ def test_convention_xfeat_dense_multiscale_with_an_empty_scale_matches_the_other_scale_alone(self, device, dtype):+ torch.manual_seed(0)+ xfeat = XFeat().to(device).eval()+ image = torch.rand(1, 3, 64, 64, device=device, dtype=dtype)+ out = xfeat.detectAndComputeDense(image, 3)+ scaled = torch.nn.functional.interpolate(image, scale_factor=1.3, mode="bilinear", align_corners=False)+ single = xfeat.detectAndComputeDense(scaled, 3, False)+ self.assert_close(out["keypoints"], single["keypoints"] / 1.3)+ self.assert_close(out["descriptors"], single["descriptors"])def test_convention_xfeat_model_reads_the_channel_mean_through_an_instance_norm(self, device, dtype):# XFeatModel averages the channels and instance-normalises the result (model.py of verlab/accelerated_features