π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
perf(feature): ALIKED reads a channels_last feature map on CPU (M1 1.36x forward at 640x480) (#6498)
Dmytro Mishkin0c1e9645e3f3
diff --git a/changelog.d/6498.added.md b/changelog.d/6498.added.mdnew file mode 100644index 000000000..f2ce765be--- /dev/null+++ b/changelog.d/6498.added.md@@ -0,0 +1,7 @@+`ALIKED.extract_dense_map` takes a keyword-only `channels_last` flag, `False` by default, which returns the feature map+with the strides of `torch.channels_last`. `ALIKED.forward` and `ALIKED.forward_laf` use it for a float32 or float64+image on CPU, where normalising the map and sampling it for the descriptors are several times faster: the ALIKED-n16+forward is 1.18-1.36x faster on an Apple M1 and 1.30-1.57x on an x86 i7-14700K, from 1024 x 768 to 640 x 480. Keypoints,+scores and LAFs are unchanged, and float32 descriptors change by rounding (a few 1e-6). MPS and CUDA keep the previous+layout, which is faster there, as do float16 and bfloat16 on CPU, where torch's half-precision `grid_sample` is+unreliable in either layout (#5810).diff --git a/kornia/feature/aliked/aliked.py b/kornia/feature/aliked/aliked.pyindex 159f3e6c1..6052d8696 100644--- a/kornia/feature/aliked/aliked.py+++ b/kornia/feature/aliked/aliked.py@@ -147,6 +147,11 @@ def get_patches(tensor: torch.Tensor, required_corners: torch.Tensor, ps: int) -return sampled.permute(2, 3, 0, 1)+def _reads_channels_last(image: torch.Tensor) -> bool:+ """Whether :meth:`ALIKED.forward` asks for the ``channels_last`` feature map; see ``extract_dense_map``."""+ return image.device.type == "cpu" and image.dtype in (torch.float32, torch.float64)++# ---------------------------------------------------------------------------# LAF helpers# ---------------------------------------------------------------------------@@ -935,12 +940,26 @@ class ALIKED(nn.Module):mask=mask,)- def extract_dense_map(self, image: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor]:+ def extract_dense_map(+ self, image: torch.Tensor, *, channels_last: bool = False+ ) -> tuple[torch.Tensor, torch.Tensor]:"""Run the backbone and return ``(feature_map, score_map)``.Args:image: ``(B, 3, H, W)`` float image. Inputs are internally padded toa multiple of 32 and the padding is removed before returning.+ channels_last: if ``True``, ``feature_map`` has the strides of the ``torch.channels_last`` memory+ format (it is a crop of such a tensor when the image was padded): the ``dim`` channels of each pixel+ lie next to each other. Its values equal those of the default+ layout up to the rounding of the normalisation, and ``score_map`` is the same either way. On CPU,+ normalising the map and the sampling of the descriptor head are then several times faster, so+ :meth:`forward` and :meth:`forward_laf` use it for a float32 or float64 CPU image. They keep the+ default elsewhere: on MPS, ``grid_sample`` is about 4x slower with this layout; on CUDA the forward+ is 0.80-0.94x as fast with it (RTX 4090, float32, float16 and bfloat16); and on CPU torch's float16+ and bfloat16 ``grid_sample`` is unreliable in either layout: it returned NaN for this one on an Apple+ M1, and on x86 it crashes the process for a 640 x 480 image in both+ (`#5810 <https://github.com/kornia/kornia/issues/5810>`_). By default each channel is a plane of the+ map, as before.Returns:``feature_map``: ``(B, dim, H, W)`` L2-normalised dense features.@@ -966,6 +985,8 @@ class ALIKED(nn.Module):x1234 = torch.cat([x1, x2_up, x3_up, x4_up], dim=1)score_map = torch.sigmoid(self.score_head(x1234))+ if channels_last:+ x1234 = x1234.contiguous(memory_format=torch.channels_last)feature_map = F.normalize(x1234, p=2, dim=1)feature_map = padder.unpad(feature_map)@@ -993,7 +1014,7 @@ class ALIKED(nn.Module):if images.shape[1] == 1:images = grayscale_to_rgb(images)- feature_map, score_map = self.extract_dense_map(images)+ feature_map, score_map = self.extract_dense_map(images, channels_last=_reads_channels_last(images))keypoints, kptscores, _scoredispersitys = self.dkd(score_map, image_size=image_size)descriptors, _offsets = self.desc_head(feature_map, keypoints)@@ -1053,7 +1074,7 @@ class ALIKED(nn.Module):if img.shape[1] == 1:img = grayscale_to_rgb(img)- feature_map, score_map = self.extract_dense_map(img)+ feature_map, score_map = self.extract_dense_map(img, channels_last=_reads_channels_last(img))if mask is not None:# Resize mask to score map resolution and apply.diff --git a/tests/feature/test_aliked.py b/tests/feature/test_aliked.pyindex e9492c054..b4465396f 100644--- a/tests/feature/test_aliked.py+++ b/tests/feature/test_aliked.py@@ -574,7 +574,8 @@ class TestALIKED(BaseTester):assert len(output) == 1assert output[0].n > 0- def test_gradcheck(self, device):+ @pytest.mark.parametrize("channels_last", [False, True])+ def test_gradcheck(self, device, channels_last):"""gradcheck on the fully-differentiable extract_dense_map sub-graph.The full pipeline includes discrete NMS/argmax steps that are not@@ -585,8 +586,8 @@ class TestALIKED(BaseTester):aliked = ALIKED(model_name="aliked-t16").to(device, torch.float64).eval()inp = torch.rand(1, 3, 32, 32, device=device, dtype=torch.float64, requires_grad=True)- def fn(x: torch.Tensor) -> torch.Tensor:- fm, sm = aliked.extract_dense_map(x)+ def fn(x: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor]:+ fm, sm = aliked.extract_dense_map(x, channels_last=channels_last)return fm, smassert torch.autograd.gradcheck(fn, [inp], eps=1e-4, atol=1e-3, rtol=1e-3, fast_mode=True, nondet_tol=1e-3)@@ -1324,6 +1325,50 @@ class TestALIKEDModes(BaseTester):assert feat.shape[0] == 1assert score.shape == (1, 1, 16, 16)+ def test_extract_dense_map_channels_last_changes_only_the_layout(self, device, dtype):+ # 50 x 70 is padded to 64 x 96 and cropped back, so the crop of a channels_last map is covered too+ aliked = self._model(device, dtype)+ img = torch.rand(2, 3, 50, 70, device=device, dtype=dtype)+ with torch.no_grad():+ feat, score = aliked.extract_dense_map(img)+ feat_cl, score_cl = aliked.extract_dense_map(img, channels_last=True)+ # Strides, not is_contiguous: a crop of either layout is contiguous in neither.+ assert feat.stride(-1) == 1 # default layout: neighbouring pixels of a channel are next to each other+ assert feat_cl.stride(1) == 1 # channels_last: the channels of a pixel are next to each other+ assert feat_cl.shape == feat.shape == (2, 64, 50, 70)+ self.assert_close(feat_cl, feat)+ self.assert_close(score_cl, score, rtol=0, atol=0)++ @pytest.mark.parametrize("method", ["forward", "forward_laf"])+ def test_forward_asks_for_channels_last_on_cpu_float(self, device, dtype, method, monkeypatch):+ # The layout measured faster per device: channels_last for float32/float64 on CPU; the default on MPS and CUDA+ # (slower there) and for CPU float16/bfloat16, whose grid_sample is unreliable in either layout (#5810).+ aliked = self._model(device, dtype)+ original = aliked.extract_dense_map+ requested = []++ def spy(image, *, channels_last=False):+ requested.append(channels_last)+ return original(image, channels_last=channels_last)++ monkeypatch.setattr(aliked, "extract_dense_map", spy)+ with torch.no_grad():+ getattr(aliked, method)(torch.rand(1, 3, 64, 96, device=device, dtype=dtype))+ assert requested == [device.type == "cpu" and dtype in (torch.float32, torch.float64)]++ def test_forward_matches_the_default_layout(self, device, dtype):+ # forward reads the channels_last map on CPU; the keypoints and scores cannot depend on that choice+ aliked = self._model(device, dtype)+ img = torch.rand(1, 3, 64, 96, device=device, dtype=dtype)+ with torch.no_grad():+ out = aliked(img)[0]+ feat, score = aliked.extract_dense_map(img)+ keypoints, scores, _ = aliked.dkd(score)+ descriptors, _ = aliked.desc_head(feat, keypoints)+ assert out.n > 0+ self.assert_close(out.keypoint_scores, scores[0], rtol=0, atol=0)+ self.assert_close(out.descriptors, descriptors[0])+class TestALIKEDStateDict(BaseTester):"""``dkd.hw_grid`` is rebuilt from ``nms_radius`` and not saved, so the pretrained checkpoints load strictly."""