π 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_kernel3d the same way everywhere (#5516)
εΊζ’η9d5effe25d07
diff --git a/changelog.d/5516.breaking.md b/changelog.d/5516.breaking.mdnew file mode 100644index 000000000..06b9a4ab1--- /dev/null+++ b/changelog.d/5516.breaking.md@@ -0,0 +1,7 @@+`get_motion_kernel3d` with `mode="nearest"`, and with it `motion_blur3d`, `MotionBlur3D` and `RandomMotionBlur3D`, used+to let roundoff pick the tap where the rotated line falls exactly between two taps (a pitch or roll that is a multiple+of 30 degrees), so the kernel changed with the dtype: float32 and float64 built different kernels at 6 of the 1000+angles of a 10-value grid, by up to 0.16 (#5510). The tie now goes to the even coordinate, as `grid_sample` breaks it+with exact arithmetic, so at those angles the float32 kernel can differ from the one it used to be:+`get_motion_kernel3d(5, (0.0, 330.0, 0.0), 0.3)` keeps 7 taps where it used to keep 5. 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 e49ea986d..1bb9d20a4 100644--- a/kornia/filters/kernels_geometry.py+++ b/kornia/filters/kernels_geometry.py@@ -22,6 +22,7 @@ import torch.nn.functional as Ffrom kornia.core.check import KORNIA_CHECK, KORNIA_CHECK_SHAPEfrom kornia.core.utils import _extract_device_dtype+from kornia.geometry.conversions import axis_angle_to_rotation_matrixfrom kornia.geometry.transform import rotate, rotate3dfrom .kernels import _check_kernel_size, _unpack_2d_ks, _unpack_3d_ks@@ -143,6 +144,10 @@ def get_motion_kernel3d(off the line); a positive pitch alone turns the line's -x end, the heavy end for a positive ``direction``,towards +z, and a positive roll alone turns the line clockwise as displayed, the opposite of the 2d``angle``.+ With ``'nearest'``, each voxel 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 a pitch or roll of 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 and with ``torch.compile``.Args:kernel_size: motion kernel width, height and depth, an odd integer of at least 3.@@ -232,6 +237,38 @@ def get_motion_kernel3d(kernel = kernel[:, None, ...]# rotate (counterclockwise) kernel by given angle- kernel = rotate3d(kernel, angle[:, 0], angle[:, 1], angle[:, 2], mode=mode, align_corners=True)- kernel = kernel[:, 0]+ if mode == "nearest":+ kernel = _rotate3d_nearest(kernel[:, 0], angle)+ else:+ kernel = rotate3d(kernel, angle[:, 0], angle[:, 1], angle[:, 2], mode=mode, align_corners=True)+ kernel = kernel[:, 0]return kernel / kernel.sum(dim=(1, 2, 3), keepdim=True)+++def _rotate3d_nearest(kernel: torch.Tensor, angle: torch.Tensor) -> torch.Tensor:+ """Rotate cubic kernels :math:`(B, k, k, k)` by the axis-angle vector ``angle`` in degrees with nearest sampling.++ Each voxel copies the tap at its source under the inverse rotation, as ``rotate3d`` 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 the+ rotation matrix, 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)+ rotation = axis_angle_to_rotation_matrix(torch.deg2rad(angle.detach().cpu().to(torch.float64)))+ offsets = torch.arange(kernel_size, dtype=torch.float64) - center+ z, y, x = torch.meshgrid(offsets, offsets, offsets, indexing="ij")+ # the source of voxel p is R^T (p - c) + c, written as a row vector times R+ source = torch.stack((x, y, z), -1).reshape(1, -1, 3) @ rotation+ snap = 2.0**20+ source = ((source * snap).round() / snap + center).round()+ inside = ((source >= 0) & (source < kernel_size)).all(-1)+ col, row, slab = source.unbind(-1)+ # flat index plus one; 0 picks the zero weight padded in front, for a source outside the kernel+ flat = torch.where(inside, (slab * kernel_size + row) * kernel_size + col + 1, 0.0).long().to(kernel.device)+ weights = F.pad(kernel.flatten(1), [1, 0])+ kernel = weights.gather(1, flat).view(batch_size, kernel_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.sum(-1)[:, None, None, None])diff --git a/tests/filters/test_filters.py b/tests/filters/test_filters.pyindex 79795b2b5..ea1f52eb1 100644--- a/tests/filters/test_filters.py+++ b/tests/filters/test_filters.py@@ -16,6 +16,8 @@#+from fractions import Fraction+import pytestimport torchimport torch.nn.functional as F@@ -2273,6 +2275,88 @@ class TestConventionsKernels(BaseTester):expected[3, 1, 2] = 1 / 2self.assert_close(kernel((90.0, 90.0, 0.0)), expected)+ @pytest.mark.parametrize("kernel_size", [3, 5, 7])+ def test_convention_motion_kernel3d_tie_goes_half_to_even_5510(self, kernel_size, device, dtype):+ """A source between two taps is an exact tie, broken half to even as grid_sample does (#5510)."""+ # 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 axis in (1, 2):+ for angle, ((ca, cb), (sa, sb)) in sorted(cos_sin.items()):+ expected = torch.zeros(kernel_size, kernel_size, kernel_size, dtype=torch.float64)+ for z in range(kernel_size):+ for y in range(kernel_size):+ for x in range(kernel_size):+ u, v, w = x - center, y - center, z - center+ # the source of a voxel is R^T (p - c) + c: a pitch turns the x-z plane, a roll the x-y+ if axis == 1:+ col, row, slab = (+ nearest(ca * u - sa * w, cb * u - sb * w),+ y,+ nearest(sa * u + ca * w, sb * u + cb * w),+ )+ else:+ col, row, slab = (+ nearest(ca * u + sa * v, cb * u + sb * v),+ nearest(-sa * u + ca * v, -sb * u + cb * v),+ z,+ )+ if row == center and slab == center and 0 <= col < kernel_size:+ expected[z, y, x] = line[col]+ vector = [0.0, 0.0, 0.0]+ vector[axis] = float(angle)+ kernel = get_motion_kernel3d(kernel_size, torch.tensor([vector], device=device, dtype=dtype), 0.7)+ self.assert_close(kernel[0].cpu().double(), expected / expected.sum(), rtol=0, atol=1e-2)++ def test_convention_motion_kernel3d_same_taps_for_every_dtype_5510(self, device, dtype):+ """Every dtype and device picks the taps of the float64 CPU kernel, at the tie angles too (#5510)."""+ values = torch.tensor([0.0, 30.0, 45.0, 60.0, 90.0, 120.0, 150.0, 210.0, 240.0, 300.0], dtype=torch.float64)+ angles = torch.stack(torch.meshgrid(values, values, values, indexing="ij"), -1).reshape(-1, 3)+ direction = torch.full((angles.shape[0],), 0.3, dtype=torch.float64)+ reference = get_motion_kernel3d(5, angles, direction)+ kernel = get_motion_kernel3d(5, angles.to(device=device, dtype=dtype), direction.to(device=device, dtype=dtype))+ self.assert_close(kernel.cpu().double(), reference, rtol=0, atol=1e-2)++ def test_motion_kernel3d_nearest_angle_gradient_is_zero(self, device, dtype):+ """Nearest sampling keeps the angle in the graph with a zero gradient, as grid_sample gives."""+ angle = torch.tensor([[0.0, 30.0, 0.0], [10.0, 20.0, 37.0]], device=device, dtype=dtype, requires_grad=True)+ get_motion_kernel3d(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_kernel3d_nearest_next_to_a_tie_is_rotate3d_5510(self, kernel_size, device, dtype):+ """1e-4 degrees from a tie, the taps are rotate3d()'s: only an exact tie is snapped (#5510)."""+ from kornia.geometry.transform import rotate3d++ 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)+ near = torch.cat([ties - 1e-4, ties + 1e-4])+ zero = torch.zeros_like(near)+ # a pitch alone and a roll alone, where the ties are+ angle = torch.cat([torch.stack([zero, near, zero], -1), torch.stack([zero, zero, near], -1)])+ angle = angle.to(device=device, dtype=dtype)+ # 1e-4 degrees moves a source more than 1e-6 px off the half: rotate3d() in float64 resolves it, and so must+ # the snap, which only merges sources closer than 2**-21 (4.8e-7) px to a tie+ center = kernel_size // 2+ line = torch.zeros(angle.shape[0], 1, kernel_size, kernel_size, kernel_size, dtype=torch.float64)+ line[:, 0, center, center] = torch.linspace(0.65, 0.35, kernel_size, dtype=torch.float64)+ expected = rotate3d(line, *angle.cpu().double().unbind(-1), mode="nearest", align_corners=True)[:, 0]+ kernel = get_motion_kernel3d(kernel_size, angle, torch.full((angle.shape[0],), 0.3, device=device, dtype=dtype))+ self.assert_close(kernel.cpu().double(), expected / expected.sum((1, 2, 3), keepdim=True), rtol=0, atol=1e-5)+def test_convention_gaussian_discrete_kernel1d_has_kernel_size_taps_5158(self, device, dtype):"""get_gaussian_discrete_kernel1d gives kernel_size taps, [1.0] for size 1, and rejects an even size (#5158)."""self.assert_close(