π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
fix(feature): let the SIFT pyramid backend move to MPS (#5142)
Dmytro Mishkin2d317094907a
diff --git a/kornia/feature/sift/scale_space.py b/kornia/feature/sift/scale_space.pyindex ebe33369a..f9e020441 100644--- a/kornia/feature/sift/scale_space.py+++ b/kornia/feature/sift/scale_space.py@@ -31,7 +31,7 @@ integration; gradients are transformed into LAF coordinates before voting.from __future__ import annotationsimport math-from typing import Any, Optional+from typing import Any, Callable, Optionalimport torchimport torch.nn.functional as F@@ -59,13 +59,44 @@ class _SIFTScalePyramid(nn.Module):step = 2.0 ** (1.0 / 3.0)sigmas = [math.sqrt(1.6**2 - 1.0)]sigmas += [1.6 * step**i * math.sqrt(step**2 - 1.0) for i in range(5)]- for index, sigma in enumerate(sigmas):+ self._sigmas = sigmas+ self._register_kernels(torch.device("cpu"))++ def _register_kernels(self, device: torch.device) -> None:+ # Keep the reference kernels in float64: rounding them here would cap a+ # float64 pyramid at float32 accuracy. MPS has no float64 and its images+ # are at most float32, so it gets float32 kernels. They are built on the+ # CPU whatever the default device is, then moved. The buffers are+ # non-persistent, so loading a state_dict saved on MPS cannot round a+ # CPU module's kernels to float32.+ dtype = torch.float32 if device.type == "mps" else torch.float64+ for index, sigma in enumerate(self._sigmas):size = int(8.0 * sigma + 1.0) | 1- # Keep the reference kernel in float64. Rounding it at construction- # would cap a float64 pyramid at float32 accuracy, unlike- # ``ScalePyramid``, which builds its kernels in the input dtype.- kernel = get_gaussian_kernel1d(size, sigma, dtype=torch.float64).reshape(-1)- self.register_buffer(f"kernel_{index}", kernel)+ kernel = get_gaussian_kernel1d(size, sigma, device=torch.device("cpu"), dtype=torch.float64)+ self.register_buffer(f"kernel_{index}", kernel.reshape(-1).to(dtype).to(device), persistent=False)++ def _apply(self, fn: Callable[[torch.Tensor], torch.Tensor], *args: Any, **kwargs: Any) -> _SIFTScalePyramid:+ # Let the kernels follow the module's device but not its dtype: passing+ # them through ``fn`` would round them on ``.half()`` and raise on+ # ``.to("mps")``. Rebuild them on the target device instead.+ kernels = [getattr(self, f"kernel_{index}") for index in range(len(self._sigmas))]+ device = fn(torch.zeros((), device=kernels[0].device, dtype=torch.float32)).device+ out = super()._apply(+ lambda tensor: tensor if any(tensor is kernel for kernel in kernels) else fn(tensor), *args, **kwargs+ )+ self._register_kernels(device)+ return out++ def __getstate__(self) -> dict[str, Any]:+ state = super().__getstate__()+ # Pickle float32 copies, which ``map_location`` can put on any device,+ # MPS included. ``__setstate__`` rebuilds the reference kernels there.+ state["_buffers"] = {name: buffer.float() for name, buffer in state["_buffers"].items()}+ return state++ def __setstate__(self, state: dict[str, Any]) -> None:+ super().__setstate__(state)+ self._register_kernels(self.kernel_0.device)@staticmethoddef _double(image: torch.Tensor) -> torch.Tensor:@@ -166,8 +197,11 @@ class _SIFTScalePyramid(nn.Module):def forward(self, image: torch.Tensor) -> list[torch.Tensor]:"""Build doubled-image Gaussian octaves for normalized grayscale images."""doubled = self._double(image)- # Cast the float64 reference kernels once instead of on every blur.- kernels = [getattr(self, f"kernel_{index}").to(doubled) for index in range(6)]+ # Cast the reference kernels once instead of on every blur. ``_apply``+ # keeps them on the module's device. For an image on another device, cast+ # the dtype before moving: a compiled graph that moves first builds a+ # float64 tensor on the device, which MPS rejects.+ kernels = [getattr(self, f"kernel_{index}").to(doubled.dtype).to(doubled.device) for index in range(6)]first = self._blur(doubled, kernels[0])pyramid = []while True:diff --git a/tests/feature/test_sift_scale_pyramid_optimized.py b/tests/feature/test_sift_scale_pyramid_optimized.pyindex e3d70e1ca..d27b8039d 100644--- a/tests/feature/test_sift_scale_pyramid_optimized.py+++ b/tests/feature/test_sift_scale_pyramid_optimized.py@@ -65,7 +65,7 @@ class TestSIFTScalePyramidCPUOptimized(BaseTester):self._cpu(device, dtype)pyramid = _SIFTScalePyramid().to(device, dtype)image = torch.rand(1, 1, *shape, device=device, dtype=dtype)- kernel = torch.rand_like(pyramid.kernel_4)+ kernel = torch.rand_like(pyramid.kernel_4.to(image))actual = (pyramid._blur_cpu(image, kernel, kernel.numel() // 2)@@ -108,7 +108,8 @@ class TestSIFTScalePyramidCPUOptimized(BaseTester):pyramid = _SIFTScalePyramid().to(device, dtype)actual_input = torch.rand(1, 1, 17, 19, device=device, dtype=dtype, requires_grad=True)expected_input = actual_input.detach().clone().requires_grad_()- kernel = pyramid.kernel_4+ # ``forward`` casts the float64 reference kernels to the image before blurring.+ kernel = pyramid.kernel_4.to(actual_input)actual = (pyramid._blur_cpu(actual_input, kernel, kernel.numel() // 2)@@ -138,7 +139,7 @@ class TestSIFTScalePyramidCPUOptimized(BaseTester):pytest.skip("the CPU slice implementation uses full precision")pyramid = _SIFTScalePyramid().to(device, dtype)image = torch.rand(1, 1, 17, 19, device=device, dtype=dtype)- kernel = pyramid.kernel_4+ kernel = pyramid.kernel_4.to(image)radius = kernel.numel() // 2expected = pyramid._blur_cpu(image, kernel, radius)torch._dynamo.reset()diff --git a/tests/feature/test_sift_scale_space.py b/tests/feature/test_sift_scale_space.pyindex b85393666..23d3b899b 100644--- a/tests/feature/test_sift_scale_space.py+++ b/tests/feature/test_sift_scale_space.py@@ -429,6 +429,84 @@ class TestSIFTScalePyramid(BaseTester):for octave in pyramid(image):assert (octave - value).abs().max() < 1e-14+ def test_device_argument_and_device_only_move(self, device):+ # Registered as float64 buffers, the reference kernels made `device="mps"` and `.to("mps")` raise, because+ # MPS has no float64. Only a move that also cast the dtype, `.to("mps", torch.float32)`, worked.+ # Built on the default device, they also made construction under `with torch.device("mps")` raise.+ image = torch.rand(1, 1, 48, 52, device=device)+ expected = SIFTFeatureScaleSpace(8, descriptor_backend="pyramid").to(device, torch.float32)(image)+ with device:+ under_default_device = SIFTFeatureScaleSpace(8, descriptor_backend="pyramid")+ for feature in (+ SIFTFeatureScaleSpace(8, descriptor_backend="pyramid", device=device),+ SIFTFeatureScaleSpace(8, descriptor_backend="pyramid").to(device),+ under_default_device,+ ):+ # Not bitwise: on MPS, the orientation histogram's scatter_add_ varies from run to run at float32 rounding.+ for actual, reference in zip(feature(image), expected):+ assert actual.device == image.device+ self.assert_close(actual, reference)++ def test_dynamo_on_device(self, device, torch_optimizer):+ from kornia.feature.sift.scale_space import _SIFTScalePyramid++ # A compiled graph must not build a float64 tensor on MPS, which rejects it: the kernels are float32 there, and+ # forward casts a kernel's dtype before any move.+ pyramid = _SIFTScalePyramid().to(device)+ image = torch.rand(1, 1, 33, 37, device=device)+ expected = pyramid(image)+ for actual_octave, expected_octave in zip(torch_optimizer(pyramid)(image), expected):+ self.assert_close(actual_octave, expected_octave)++ @pytest.mark.parametrize("module_dtype", [torch.float16, torch.bfloat16])+ def test_module_dtype_cast_keeps_reference_kernels(self, device, module_dtype):+ from kornia.feature.sift.scale_space import _SIFTScalePyramid++ # The detector builds its pyramid in float32 for half inputs, so a half-cast module still blurs float32 images.+ # Casting the module must not round the Gaussian kernels to its dtype: rounded kernels miss their unit sum, and+ # a constant image drifts octave by octave, from 8e-5 in the first to 4.9e-4 in the fifth with float16 kernels,+ # and from 1.1e-3 to 3.0e-3 with bfloat16 ones.+ value = 0.37+ image = torch.full((1, 1, 96, 96), value, device=device, dtype=torch.float32)+ for octave in _SIFTScalePyramid().to(device, module_dtype)(image):+ assert (octave - value).abs().max() < 1e-6++ def test_kernels_are_buffers_that_follow_device_moves(self, device):+ from kornia.feature.sift.scale_space import _SIFTScalePyramid++ # The kernels live on the module's device, so forward does not copy them there on every call. A move rebuilds+ # them from float64, in float32 on MPS, which has no float64; a dtype cast of the module leaves them alone. They+ # stay out of state_dict: loading a checkpoint saved on MPS would round a CPU module's kernels to float32.+ reference = [getattr(_SIFTScalePyramid(), f"kernel_{index}") for index in range(6)]+ pyramid = _SIFTScalePyramid().to(device).half()+ kernel_dtype = torch.float32 if device.type == "mps" else torch.float64+ assert not pyramid.state_dict()+ for index, expected in enumerate(reference):+ kernel = getattr(pyramid, f"kernel_{index}")+ assert kernel.device.type == device.type and kernel.dtype == kernel_dtype+ assert torch.equal(kernel.cpu(), expected.to(kernel_dtype))+ pyramid.cpu()+ for index, expected in enumerate(reference):+ kernel = getattr(pyramid, f"kernel_{index}")+ assert kernel.dtype == torch.float64 and torch.equal(kernel, expected)++ def test_whole_module_pickle_rebuilds_kernels_where_they_land(self, device):+ from kornia.feature.sift.scale_space import _SIFTScalePyramid++ # The pickle holds float32 copies of the kernels, which `map_location` can put on MPS, and loading rebuilds+ # them on the device they land on. A float64 CPU copy could not be mapped to MPS, and float32 MPS kernels+ # mapped to the CPU would cap float64 images at float32 accuracy.+ for source, target in ((device, torch.device("cpu")), (torch.device("cpu"), device)):+ checkpoint = io.BytesIO()+ torch.save(_SIFTScalePyramid().to(source), checkpoint)+ checkpoint.seek(0)+ restored = torch.load(checkpoint, map_location=target, weights_only=False)+ expected = _SIFTScalePyramid().to(target)+ for index in range(6):+ kernel, reference = getattr(restored, f"kernel_{index}"), getattr(expected, f"kernel_{index}")+ assert kernel.device.type == target.type and kernel.dtype == reference.dtype+ assert torch.equal(kernel, reference)+def test_pyramid_backend_rejects_unknown_compile_component(self):with pytest.raises(ValueError, match="compile_modules"):SIFTFeatureScaleSpace(descriptor_backend="pyramid", compile_modules=["resp"])