π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
fix(filters): build a Python-number motion blur parameter like its tensor partner (#5436)
εΊζ’ηf1ad5763360b
diff --git a/changelog.d/5436.fixed.md b/changelog.d/5436.fixed.mdnew file mode 100644index 000000000..17eb2bb67--- /dev/null+++ b/changelog.d/5436.fixed.md@@ -0,0 +1,5 @@+`motion_blur` and `motion_blur3d` (and `MotionBlur`, `MotionBlur3D`) now accept a tensor `angle` or `direction` with a+Python number for the other again, whatever the tensor's dtype and device, and blur as the two-tensor call does (#5429).+Previously, since #5270, such a call raised a `TypeCheckError` unless the tensor was in the input's dtype promoted to at+least float32, and a `DeviceError` for a tensor on an accelerator, because the number was built on the CPU in that+promoted dtype instead of like its tensor partner.diff --git a/kornia/filters/motion.py b/kornia/filters/motion.pyindex eab9500ba..05ec9de3a 100644--- a/kornia/filters/motion.py+++ b/kornia/filters/motion.py@@ -33,10 +33,16 @@ _VALID_BORDER = {"constant", "reflect", "replicate", "circular"}def _scalar_params_as_tensors(input: torch.Tensor, angle: float | tuple[float, float, float] | torch.Tensor, direction: float | torch.Tensor) -> tuple[torch.Tensor, torch.Tensor]:- # Python-number parameters build the kernel in the input's floating dtype, but never below float32: a float64+ # A Python-number parameter next to a tensor one is built like that tensor, on its device and in its dtype, so+ # the kernel is built from one device and one dtype, as it is from two tensors.+ if isinstance(angle, torch.Tensor) and not isinstance(direction, torch.Tensor):+ direction = torch.as_tensor(direction, device=angle.device, dtype=angle.dtype)+ elif isinstance(direction, torch.Tensor) and not isinstance(angle, torch.Tensor):+ angle = torch.as_tensor(angle, device=direction.device, dtype=direction.dtype)+ # Two Python-number parameters build the kernel in the input's floating dtype, but never below float32: a float64# input keeps float64 precision, while a half-precision kernel would quantise the rotation and move the- # nearest-neighbour samples. The kernel is built on the CPU, as before: MPS builds a different one at some- # angles (#5181). Tensor parameters keep their own device and dtype.+ # nearest-neighbour samples. That kernel is built on the CPU: MPS builds a different one at some angles (#5181).+ # Tensor parameters keep their own device and dtype.dtype = torch.promote_types(input.dtype, torch.float32) if input.is_floating_point() else torch.get_default_dtype()if not isinstance(angle, torch.Tensor):angle = torch.as_tensor(angle, dtype=dtype)diff --git a/testing/base.py b/testing/base.pyindex 9e7cb07c4..084efc264 100644--- a/testing/base.py+++ b/testing/base.py@@ -208,6 +208,36 @@ def supports_bilinear_2d_grid_sample_backward(device: torch.device, dtype: torchreturn _supports_kernel_probe(_bilinear_2d_grid_sample_backward_op, device.type, dtype)+def _nearest_2d_grid_sample_op(device_type: str, dtype: torch.dtype) -> None:+ inp = _probe_zeros(device_type, dtype, 1, 1, 2, 2)+ grid = _probe_zeros(device_type, dtype, 1, 1, 1, 2)+ F.grid_sample(inp, grid, mode="nearest", align_corners=True)+++def supports_nearest_2d_grid_sample(device: torch.device, dtype: torch.dtype) -> bool:+ """Whether this device supports nearest interpolation in 2D ``grid_sample`` for ``dtype``.++ Probed at runtime and cached per (device type, dtype), so tests guarded by this helper+ auto-enable once PyTorch adds the missing interpolation kernel.+ """+ return _supports_kernel_probe(_nearest_2d_grid_sample_op, device.type, dtype)+++def _arange_op(device_type: str, dtype: torch.dtype) -> None:+ _probe_zeros(device_type, dtype, 1)+ torch.arange(2, device=device_type, dtype=dtype)+++def supports_arange(device: torch.device, dtype: torch.dtype) -> bool:+ """Whether this device has a ``torch.arange`` kernel for ``dtype``.++ :func:`kornia.filters.get_motion_kernel2d` builds its taps with ``arange`` in the dtype of ``direction``;+ torch 2.5.1 has no bfloat16 ``arange`` on MPS. Probed at runtime and cached per (device type, dtype), so it+ auto-enables once PyTorch fills the kernel in.+ """+ return _supports_kernel_probe(_arange_op, device.type, dtype)++def _bicubic_2d_grid_sample_op(device_type: str, dtype: torch.dtype) -> None:inp = _probe_zeros(device_type, dtype, 1, 1, 2, 2)grid = _probe_zeros(device_type, dtype, 1, 1, 1, 2)diff --git a/tests/filters/test_motion.py b/tests/filters/test_motion.pyindex ecd1dd38e..0f63bd066 100644--- a/tests/filters/test_motion.py+++ b/tests/filters/test_motion.py@@ -36,7 +36,9 @@ from kornia.filters import (from testing.base import (BaseTester,+ supports_arange,supports_bilinear_3d_grid_sample,+ supports_nearest_2d_grid_sample,supports_nearest_3d_grid_sample,supports_reflect_padding,supports_replicate_padding_3d,@@ -223,6 +225,38 @@ class TestMotionBlur(BaseTester):self.assert_close(motion_blur(img, 7, angle, 0.3, "reflect"), expected, rtol=0, atol=0)self.assert_close(MotionBlur(7, angle, 0.3, "reflect")(img), expected, rtol=0, atol=0)+ @pytest.mark.parametrize("tensor_dtype", [torch.float16, torch.bfloat16, torch.float32, torch.float64])+ @pytest.mark.parametrize("tensor_parameter", ["angle", "angle_0d", "direction"])+ def test_tensor_parameter_with_a_python_number_is_built_like_the_tensor(+ self, tensor_parameter, tensor_dtype, device, dtype+ ):+ # A tensor angle or direction with a Python number for the other builds the number on the tensor's device and+ # in its dtype, whatever the input's dtype, so the blur is the one of the two tensors.+ if device.type == "mps" and torch.float64 in (dtype, tensor_dtype):+ pytest.skip("MPS has no float64")+ if not supports_reflect_padding(device, dtype):+ pytest.skip("reflection_pad2d is unavailable for this device/dtype")+ if not supports_nearest_2d_grid_sample(device, tensor_dtype):+ pytest.skip(f"the kernel is rotated with grid_sample, which this device lacks for {tensor_dtype}")+ if not supports_arange(device, tensor_dtype):+ pytest.skip(f"the kernel taps are built with arange, which this device lacks for {tensor_dtype}")+ torch.manual_seed(0)+ image = torch.rand(1, 2, 9, 11, device=device, dtype=dtype)+ angle = torch.tensor([30.0], device=device, dtype=tensor_dtype)+ direction = torch.tensor([0.5], device=device, dtype=tensor_dtype)+ expected = motion_blur(image, 5, angle, direction)+ if tensor_parameter == "angle":+ params = (angle, 0.5)+ elif tensor_parameter == "angle_0d":+ params = (angle[0], 0.5)+ else:+ params = (30.0, direction)+ actual = motion_blur(image, 5, *params)+ assert actual.dtype == dtype+ assert actual.device == image.device+ self.assert_close(actual, expected, rtol=0, atol=0)+ self.assert_close(MotionBlur(5, *params)(image), expected, rtol=0, atol=0)+# A blur of a constant image is that constant. ``(1, 1, 3, 9)`` and ``(1, 1, 9, 3)`` are shorter than the# 5-tap kernel along one axis.@pytest.mark.parametrize("shape", [(1, 1, 5, 7), (2, 3, 8, 6), (1, 1, 3, 9), (1, 1, 9, 3)])@@ -473,6 +507,31 @@ class TestMotionBlur3D(BaseTester):self.assert_close(motion_blur3d(volume, 5, angle, 0.3, "replicate"), expected, rtol=0, atol=0)self.assert_close(MotionBlur3D(5, angle, 0.3, "replicate")(volume), expected, rtol=0, atol=0)+ @pytest.mark.parametrize("tensor_dtype", [torch.float16, torch.bfloat16, torch.float32, torch.float64])+ @pytest.mark.parametrize("tensor_parameter", ["angle", "direction"])+ def test_tensor_parameter_with_a_python_number_is_built_like_the_tensor(+ self, tensor_parameter, tensor_dtype, device, dtype+ ):+ # A tensor angle or direction with a Python number, or a tuple, for the other builds that one on the tensor's+ # device and in its dtype, whatever the input's dtype, so the blur is the one of the two tensors.+ if device.type == "mps" and torch.float64 in (dtype, tensor_dtype):+ pytest.skip("MPS has no float64")+ if not supports_replicate_padding_3d(device, dtype):+ pytest.skip("replication_pad3d is unavailable for this device/dtype")+ if not supports_nearest_3d_grid_sample(device, tensor_dtype):+ pytest.skip(f"the kernel is rotated with grid_sample, which this device lacks for {tensor_dtype}")+ torch.manual_seed(0)+ volume = torch.rand(1, 2, 6, 7, 8, device=device, dtype=dtype)+ angle = torch.tensor([[10.0, 20.0, 30.0]], device=device, dtype=tensor_dtype)+ direction = torch.tensor([0.5], device=device, dtype=tensor_dtype)+ expected = motion_blur3d(volume, 3, angle, direction)+ params = (angle, 0.5) if tensor_parameter == "angle" else ((10.0, 20.0, 30.0), direction)+ actual = motion_blur3d(volume, 3, *params)+ assert actual.dtype == dtype+ assert actual.device == volume.device+ self.assert_close(actual, expected, rtol=0, atol=0)+ self.assert_close(MotionBlur3D(3, *params)(volume), expected, rtol=0, atol=0)+@pytest.mark.skip(reason="After the op be optimized the results are not the same")@pytest.mark.parametrize("batch_size", [1, 2])def test_dynamo(self, batch_size, device, dtype, torch_optimizer):