Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

fix(feature): ALIKED keeps the default map layout under torch.compile (compiled x86 CPU 1.28x) (#6510)

Dmytro Mishkin26067c9e4a33
diff --git a/changelog.d/6510.fixed.md b/changelog.d/6510.fixed.md
new file mode 100644
index 000000000..5be75c175
--- /dev/null
+++ b/changelog.d/6510.fixed.md
@@ -0,0 +1,7 @@
+Under `torch.compile`, `ALIKED.forward` and `forward_laf` on the CPU ask for the default feature-map layout again.
+Eager keeps the channels_last map of #6498. Inductor (torch 2.14, x86) lowers the descriptor head's `grid_sample` to
+a channel-by-channel gather that the channels_last map slows down, and it transposed the normalised map into its
+channels_last store. On an i7-14700K, the compiled forward of a 416 x 640 image took 260 ms with the map. It now takes
+203 ms with static shapes, and 172 ms instead of 201 ms with `dynamic=True`. With `channels_last=True`,
+`extract_dense_map` now normalises in an explicit (B, H, W, C) tensor. Eager gets the same bits, and inductor gets a
+pixel-major store. Eager, CUDA and MPS are unchanged.
diff --git a/kornia/feature/aliked/aliked.py b/kornia/feature/aliked/aliked.py
index 6052d8696..883cfcb6f 100644
--- a/kornia/feature/aliked/aliked.py
+++ b/kornia/feature/aliked/aliked.py
@@ -65,6 +65,7 @@ from torch.nn.modules.utils import _pair
from kornia.color import grayscale_to_rgb
from kornia.core.download import load_state_dict_from_url
+from kornia.core.utils import is_compiling
from kornia.geometry.subpix import nms2d
from .deform_conv2d import deform_conv2d
@@ -148,8 +149,13 @@ def get_patches(tensor: torch.Tensor, required_corners: torch.Tensor, ps: int) -
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)
+ """Whether :meth:`ALIKED.forward` asks for the ``channels_last`` feature map; see ``extract_dense_map``.
+
+ It does for a float32 or float64 CPU image in eager only. Under ``torch.compile`` or ``torch.export`` capture the
+ default layout is faster: inductor lowers the descriptor head's ``grid_sample`` to a loop that gathers one channel
+ at a time across the sample points, and on the channels_last map each of those reads lands on another cache line.
+ """
+ return image.device.type == "cpu" and image.dtype in (torch.float32, torch.float64) and not is_compiling()
# ---------------------------------------------------------------------------
@@ -953,13 +959,16 @@ class ALIKED(nn.Module):
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
+ :meth:`forward` and :meth:`forward_laf` use it for a float32 or float64 CPU image in eager. 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.
+ map, as before. Under ``torch.compile`` they keep the default too. On an x86 CPU (torch 2.14),
+ inductor lowers the descriptor head's ``grid_sample`` to a loop that gathers one channel at a time
+ across the sample points, and on this layout each of those reads lands on another cache line. The
+ compiled forward of a 416 x 640 image took 254 ms with this map and 199 ms without (4 threads).
Returns:
``feature_map``: ``(B, dim, H, W)`` L2-normalised dense features.
@@ -986,8 +995,15 @@ class ALIKED(nn.Module):
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)
+ # Each pixel's channels are normalised in an explicit (B, H, W, C) tensor, whose permutation back has the
+ # strides of a channels_last map. Eager computes the same bits as normalising
+ # ``x1234.contiguous(memory_format=torch.channels_last)`` over dim 1. Inductor (torch 2.14, x86) differs:
+ # for that form it kept the channel-major loop of the map's producer and transposed every 8 x 8 tile into
+ # the channels_last store. For this form it writes pixel by pixel, which made the compiled forward of a
+ # 416 x 640 image 1.11x faster while it still asked for this map.
+ feature_map = F.normalize(x1234.permute(0, 2, 3, 1).contiguous(), p=2, dim=-1).permute(0, 3, 1, 2)
+ else:
+ feature_map = F.normalize(x1234, p=2, dim=1)
feature_map = padder.unpad(feature_map)
score_map = padder.unpad(score_map)
diff --git a/tests/feature/test_aliked.py b/tests/feature/test_aliked.py
index b4465396f..f32dc9f9e 100644
--- a/tests/feature/test_aliked.py
+++ b/tests/feature/test_aliked.py
@@ -24,6 +24,7 @@ import torch.nn.functional as F
import kornia
from kornia.feature import laf_is_filled
from kornia.feature.aliked import ALIKED, ALIKEDFeatures
+from kornia.feature.aliked import aliked as aliked_module
from kornia.feature.aliked.aliked import SDDH, InputPadder, _affine_from_cov, get_patches
from kornia.feature.aliked.deform_conv2d import _bilinear_sample, _grid_sample_bilinear, deform_conv2d
@@ -449,12 +450,13 @@ class TestALIKED(BaseTester):
assert bottom - top in (0, 1)
assert right - left in (0, 1)
- def test_dynamo_dense_map_with_changing_sizes(self, dtype, device, torch_optimizer):
+ @pytest.mark.parametrize("channels_last", [False, True])
+ def test_dynamo_dense_map_with_changing_sizes(self, dtype, device, torch_optimizer, channels_last):
"""extract_dense_map compiles in one graph and matches eager, also once the image size changes.
A second size makes Dynamo trace the sizes symbolically. The padding used to be a modulo of the image size,
which reached the float offset bound of DeformableConv2d, and inductor (torch 2.14) failed to lower it:
- ``TensorReferenceAnalysis has no attribute 'python_mod'``.
+ ``TensorReferenceAnalysis has no attribute 'python_mod'``. The channels_last map keeps its layout compiled.
"""
if device.type == "mps" and dtype == torch.float64:
pytest.skip("MPS does not support float64")
@@ -464,9 +466,11 @@ class TestALIKED(BaseTester):
for hw in ((64, 96), (96, 72), (80, 112)):
inp = torch.rand(1, 3, *hw, device=device, dtype=dtype)
with torch.no_grad():
- expected, actual = aliked.extract_dense_map(inp), op(inp)
+ expected = aliked.extract_dense_map(inp, channels_last=channels_last)
+ actual = op(inp, channels_last=channels_last)
for e, a in zip(expected, actual):
self.assert_close(a, e)
+ assert (actual[0].stride(1) == 1) == channels_last
def test_dynamo_model_with_changing_sizes(self, dtype, device, torch_optimizer):
"""The compiled model, with the graph breaks of its keypoint selection, runs on changing image sizes."""
@@ -1356,6 +1360,23 @@ class TestALIKEDModes(BaseTester):
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)]
+ @pytest.mark.parametrize("method", ["forward", "forward_laf"])
+ def test_forward_keeps_the_default_layout_in_graph_capture(self, device, dtype, method, monkeypatch):
+ # inductor's grid_sample gathers channel by channel, which the channels_last map makes slower (x86, torch 2.14)
+ 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)
+ monkeypatch.setattr(aliked_module, "is_compiling", lambda: True)
+ with torch.no_grad():
+ getattr(aliked, method)(torch.rand(1, 3, 64, 96, device=device, dtype=dtype))
+ assert requested == [False]
+
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)