π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
fix(filters): break nearest sampling ties in get_motion_kernel2d the same way everywhere (#5497)
Animesh Kumarffa046cfd770
diff --git a/changelog.d/5497.breaking.md b/changelog.d/5497.breaking.mdnew file mode 100644index 000000000..d8460e318--- /dev/null+++ b/changelog.d/5497.breaking.md@@ -0,0 +1 @@+`get_motion_kernel2d` with `mode="nearest"`, and with it `motion_blur`, `MotionBlur` and `RandomMotionBlur`, used to let roundoff pick the tap where the rotated line falls exactly between two taps (some multiples of 30 degrees), so the kernel changed with the dtype, the device, the torch version, `torch.compile` and a full turn added to the angle. The tie now goes to the even coordinate, as `grid_sample` breaks it with exact arithmetic, so at those angles the CPU float32 kernel can differ from the one it used to be: `get_motion_kernel2d(5, 330.0, 0.3)` gives other taps than before. A nearest kernel still has a zero gradient in the angle.diff --git a/kornia/filters/kernels_geometry.py b/kornia/filters/kernels_geometry.pyindex 1bb9d20a4..b21457e6f 100644--- a/kornia/filters/kernels_geometry.py+++ b/kornia/filters/kernels_geometry.py@@ -48,10 +48,10 @@ def get_motion_kernel2d(- A floating tensor ``angle`` of shape :math:`(B,)` gives :math:`(B, k, k)` in its dtype. A tensor``direction`` must match it in length, dtype and device; a float ``direction`` is not broadcast, so itraises for ``B > 1``.- - Known defect: with ``'nearest'``, at angles where the rotated line falls on sampling ties, such as 30 or- 60 degrees, roundoff breaks the ties, so the kernel can change with the dtype, the device or a full turn- added to the angle; on MPS a tensor angle and the same float angle can blur differently- (`#5181 <https://github.com/kornia/kornia/issues/5181>`_).+ - With ``'nearest'``, each pixel copies the tap nearest to its source under the inverse rotation, picked+ with exact arithmetic: where the source falls exactly between two taps, such as at 30 or 120 degrees, the+ tie goes to the even coordinate, as ``torch.nn.functional.grid_sample`` breaks it. The kernel is the+ same on every device and dtype, for every full turn added to the angle, and with ``torch.compile``.Args:kernel_size: motion kernel width and height, an odd integer of at least 3.@@ -121,11 +121,42 @@ def get_motion_kernel2d(kernel = kernel[:, None, ...]# rotate (counterclockwise) kernel by given angle- kernel = rotate(kernel, angle, mode=mode, align_corners=True)- kernel = kernel[:, 0]+ if mode == "nearest":+ kernel = _rotate_nearest(kernel[:, 0], angle)+ else:+ kernel = rotate(kernel, angle, mode=mode, align_corners=True)+ kernel = kernel[:, 0]return kernel / kernel.sum(dim=(1, 2), keepdim=True)+def _rotate_nearest(kernel: torch.Tensor, angle: torch.Tensor) -> torch.Tensor:+ """Rotate square kernels :math:`(B, k, k)` counter-clockwise by ``angle`` degrees with nearest sampling.++ Each pixel copies the tap at its source under the inverse rotation, as ``rotate`` with ``mode='nearest'`` and+ ``align_corners=True`` does with exact arithmetic. The source is computed in float64 on the CPU and snapped to a+ :math:`2^{-20}` grid, so a source that falls between two taps is an exact tie whatever the roundoff of ``cos``+ and ``sin``, and ``torch.round`` breaks it half to even as ``grid_sample`` does. The weights are then gathered in+ the kernel's own dtype and device, so gradients still reach them.+ """+ batch_size, kernel_size = kernel.shape[0], kernel.shape[-1]+ center = (kernel_size - 1) / 2+ # move first, then cast: on MPS a single .to(device="cpu", dtype=torch.float64) returns zeros (torch 2.14)+ radians = torch.deg2rad(angle.detach().cpu().to(torch.float64) % 360.0)+ cos, sin = radians.cos()[:, None, None], radians.sin()[:, None, None]+ offsets = torch.arange(kernel_size, dtype=torch.float64) - center+ v, u = torch.meshgrid(offsets, offsets, indexing="ij")+ snap = 2.0**20+ col = (((cos * u - sin * v) * snap).round() / snap + center).round()+ row = (((sin * u + cos * v) * snap).round() / snap + center).round()+ inside = (col >= 0) & (col < kernel_size) & (row >= 0) & (row < kernel_size)+ # flat index plus one; 0 picks the zero weight padded in front, for a source outside the kernel+ source = torch.where(inside, row * kernel_size + col + 1, 0.0).long().flatten(1).to(kernel.device)+ weights = F.pad(kernel.flatten(1), [1, 0])+ kernel = weights.gather(1, source).view(batch_size, kernel_size, kernel_size)+ # nearest sampling has a zero gradient in the angle, as grid_sample gives; keep the angle in the graph with it+ return kernel * (1 + 0 * angle[:, None, None])++def get_motion_kernel3d(kernel_size: int,angle: torch.Tensor | tuple[float, float, float],diff --git a/kornia/filters/motion.py b/kornia/filters/motion.pyindex 57a33becd..21f8a0d3a 100644--- a/kornia/filters/motion.py+++ b/kornia/filters/motion.py@@ -41,7 +41,7 @@ def _scalar_params_as_tensors(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. That kernel is built on the CPU: MPS builds a different one at some angles (#5181).+ # nearest-neighbour samples. That kernel is built on the CPU.# 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):diff --git a/tests/filters/test_filters.py b/tests/filters/test_filters.pyindex ea1f52eb1..c9016808a 100644--- a/tests/filters/test_filters.py+++ b/tests/filters/test_filters.py@@ -2463,32 +2463,90 @@ class TestConventionsKernels(BaseTester):# the first-order taps are +-0.5assert bool((get_spatial_gradient_kernel3d("diff", 1, device=device, dtype=torch.int32) == 0).all())- def test_wart_motion_kernel2d_nearest_ties_change_with_a_full_turn_5181(self):- """At a sampling-tie angle roundoff picks the tap: 30 and -330 degrees build other kernels (#5181)."""+ @pytest.mark.parametrize("kernel_size", [5, 7])+ def test_convention_motion_kernel2d_nearest_ties_ignore_a_full_turn_5181(self, kernel_size):+ """At a sampling-tie angle the tap is picked from the angle modulo 360: 30 and -330 degrees agree (#5181)."""# a float angle builds the kernel on the CPU in float32, whatever the test device- difference = get_motion_kernel2d(5, 30.0, 1.0) - get_motion_kernel2d(5, -330.0, 1.0)- assert float(difference.abs().max()) > 0.1-- def test_wart_motion_kernel2d_on_mps_differs_from_cpu_for_some_angles_5181(self, device, dtype):- """A tensor angle builds get_motion_kernel2d on its own device, and MPS gives other kernels (#5181)."""- if device.type != "mps":- pytest.skip("#5181 compares the kernel built on MPS with the one built on the CPU")- _kernel_guard("get_motion_kernel2d", torch.device("cpu"), dtype)- # every whole degree, including 120 and 210- angles = torch.arange(0.0, 360.0, 1.0, dtype=dtype)+ self.assert_close(get_motion_kernel2d(5, 30.0, 1.0), get_motion_kernel2d(5, -330.0, 1.0), rtol=0, atol=0)+ # every whole degree, which includes the ties at 60, 120, 210, 240 and 300 degrees+ angles = torch.arange(0.0, 360.0, 1.0)directions = torch.full_like(angles, 0.3)- on_cpu = get_motion_kernel2d(7, angles, directions)- on_mps = get_motion_kernel2d(7, angles.to(device), directions.to(device)).cpu()- # a sampling tie rounded the other way moves a tap weight (about 0.18), far beyond half-precision roundoff- differing = (on_mps.float() - on_cpu.float()).abs().flatten(1).amax(1) > 0.05- if not bool(differing.any()):- pytest.skip("this MPS backend rounds the sampling ties like the CPU (#5181)")- # a Python-float angle builds the kernel on the CPU in float32, equal to the CPU tensor-angle kernel- on_cpu_f32 = get_motion_kernel2d(7, angles.float(), directions.float())- for index in differing.nonzero().flatten().tolist():- from_float = get_motion_kernel2d(7, float(angles[index]), float(directions[index]))- assert from_float.device.type == "cpu"- self.assert_close(from_float[0], on_cpu_f32[index])+ for turns in (-2, -1, 1):+ self.assert_close(+ get_motion_kernel2d(kernel_size, angles + 360.0 * turns, directions),+ get_motion_kernel2d(kernel_size, angles, directions),+ rtol=0,+ atol=0,+ )++ @pytest.mark.parametrize("kernel_size", [3, 5, 7])+ def test_convention_motion_kernel2d_tie_goes_half_to_even_5181(self, kernel_size, device, dtype):+ """A source between two taps is an exact tie, broken half to even as grid_sample does (#5181)."""+ _kernel_guard("get_motion_kernel2d", device, dtype)+ # cos and sin of the multiples of 30 degrees as a + b * sqrt(3), with exact fractions+ half, root = Fraction(1, 2), (Fraction(0), Fraction(1, 2))+ cos_sin = {+ 30: (root, (half, 0)),+ 60: ((half, 0), root),+ 120: ((-half, 0), root),+ 150: ((0, -root[1]), (half, 0)),+ }+ cos_sin.update({a + 180: ((-c[0], -c[1]), (-s[0], -s[1])) for a, (c, s) in list(cos_sin.items())})+ center, line = kernel_size // 2, [0.85 - 0.7 * col / (kernel_size - 1) for col in range(kernel_size)]++ def nearest(a, b):+ # the absolute source coordinate center + a + b * sqrt(3): exact ties only when b == 0+ return round(center + a) if b == 0 else round(center + float(a) + float(b) * 3**0.5)++ for angle, ((ca, cb), (sa, sb)) in sorted(cos_sin.items()):+ expected = torch.zeros(kernel_size, kernel_size, dtype=torch.float64)+ for y in range(kernel_size):+ for x in range(kernel_size):+ u, v = x - center, y - center+ col = nearest(ca * u - sa * v, cb * u - sb * v)+ row = nearest(sa * u + ca * v, sb * u + cb * v)+ if row == center and 0 <= col < kernel_size:+ expected[y, x] = line[col]+ kernel = get_motion_kernel2d(kernel_size, torch.tensor([float(angle)], device=device, dtype=dtype), 0.7)+ self.assert_close(kernel[0].cpu().double(), expected / expected.sum(), rtol=0, atol=1e-2)++ def test_motion_kernel2d_nearest_angle_gradient_is_zero(self, device, dtype):+ """Nearest sampling keeps the angle in the graph with a zero gradient, as grid_sample gives."""+ _kernel_guard("get_motion_kernel2d", device, dtype)+ angle = torch.tensor([30.0, 37.0], device=device, dtype=dtype, requires_grad=True)+ get_motion_kernel2d(5, angle, torch.tensor([0.3, -0.3], device=device, dtype=dtype)).sum().backward()+ self.assert_close(angle.grad, torch.zeros_like(angle))++ @pytest.mark.parametrize("kernel_size", [3, 5, 7])+ def test_convention_motion_kernel2d_nearest_next_to_a_tie_is_rotate_5181(self, kernel_size, device, dtype):+ """1e-4 degrees from a tie, the taps are rotate()'s: only an exact tie is snapped (#5181)."""+ from kornia.geometry.transform import rotate++ if dtype in (torch.float16, torch.bfloat16):+ pytest.skip("an angle 1e-4 degrees from a tie is not representable in half precision")+ ties = torch.tensor([30.0, 60.0, 120.0, 150.0, 210.0, 240.0, 300.0, 330.0], dtype=torch.float64)+ angle = torch.cat([ties - 1e-4, ties + 1e-4]).to(device=device, dtype=dtype)+ # 1e-4 degrees moves a source more than 1e-6 px off the half: rotate() in float64 resolves it, and so must+ # the snap, which only merges sources closer than 2**-21 (4.8e-7) px to a tie+ line = torch.zeros(angle.shape[0], 1, kernel_size, kernel_size, dtype=torch.float64)+ line[:, 0, kernel_size // 2] = torch.linspace(0.65, 0.35, kernel_size, dtype=torch.float64)+ expected = rotate(line, angle.cpu().double(), mode="nearest", align_corners=True)[:, 0]+ kernel = get_motion_kernel2d(kernel_size, angle, torch.full_like(angle, 0.3))+ self.assert_close(kernel.cpu().double(), expected / expected.sum((1, 2), keepdim=True), rtol=0, atol=1e-5)++ def test_convention_motion_kernel2d_same_taps_for_every_device_and_dtype_5181(self, device, dtype):+ """A tensor angle on any device and in any dtype picks the taps of the float64 CPU kernel (#5181)."""+ _kernel_guard("get_motion_kernel2d", device, dtype)+ # every whole degree, which includes the ties at 120, 150, 210 and 300 degrees; the reference takes the+ # angles as this dtype holds them (bfloat16 rounds the degrees above 256)+ angles = torch.arange(0.0, 360.0, 1.0, device=device, dtype=dtype)+ directions = torch.full_like(angles, 0.3)+ reference = get_motion_kernel2d(7, angles.cpu().double(), directions.cpu().double())+ kernel = get_motion_kernel2d(7, angles, directions)+ assert kernel.device == device+ assert kernel.dtype == dtype+ # a tie broken the other way moves a tap weight by about 0.18, far beyond half-precision roundoff+ self.assert_close(kernel.cpu().double(), reference, rtol=0, atol=1e-2)@pytest.mark.parametrize("ndim", [1, 2])def test_convention_box_kernel_is_a_contiguous_tensor_5160(self, ndim, device, dtype):diff --git a/tests/filters/test_motion.py b/tests/filters/test_motion.pyindex d780089cb..f4a6e68c4 100644--- a/tests/filters/test_motion.py+++ b/tests/filters/test_motion.py@@ -215,8 +215,7 @@ class TestMotionBlur(BaseTester):@pytest.mark.parametrize("angle", [60.0, 120.0, 150.0])def test_python_float_parameters_match_cpu_tensor_kernel(self, angle, device, dtype):- # Python-number parameters build the kernel on the CPU in the input dtype, never below float32: a half- # kernel moves the nearest samples at these angles, and an MPS kernel differs at 120 degrees (#5181).+ # Python-number parameters build the kernel on the CPU in the input dtype, never below float32.kernel_dtype = torch.promote_types(dtype, torch.float32)img = torch.rand(1, 2, 9, 9, device=device, dtype=dtype)kernel = get_motion_kernel2d(