π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
fix(geometry): extend the conv_soft_argmax window-centre grid into the padding (#5086)
Mohammad Hijjawi74913ac5448f
diff --git a/changelog.d/5086.breaking.md b/changelog.d/5086.breaking.mdnew file mode 100644index 000000000..7a4dd6bba--- /dev/null+++ b/changelog.d/5086.breaking.md@@ -0,0 +1,7 @@+`conv_soft_argmax2d`, `conv_soft_argmax3d`, `ConvSoftArgmax2d` and `ConvSoftArgmax3d` now continue the window-centre+coordinate grid into the padding, so a window whose centre straddles the border reports the softmax expectation of its+in-image pixels. Previously the grid was zero-padded: with an even `kernel_size` and `padding = k / 2` (for example+`k = 2` with the default `padding = 1`), the first and last window on an axis averaged the coordinate 0 of a padded+pixel into its centre on every channel and reported a point far inside the image (x = 3.5, y = 1.25 for a peak at+x = 8, y = 2 on a 5 x 9 map). Odd windows, and even windows with `padding < k / 2`, give the same output as before.+(#5066)diff --git a/kornia/geometry/subpix/spatial_soft_argmax.py b/kornia/geometry/subpix/spatial_soft_argmax.pyindex bf62f7a06..8f334db3c 100644--- a/kornia/geometry/subpix/spatial_soft_argmax.py+++ b/kornia/geometry/subpix/spatial_soft_argmax.py@@ -334,14 +334,12 @@ def conv_soft_argmax2d(- Coordinates follow :ref:`Coordinates and sizes <coordinate-conventions>`. This function defaults tonormalized, corner-aligned coordinates.:func:`conv_soft_argmax3d` defaults to pixel coordinates and ``output_value=True`` instead.- - ``padding`` adds positions of zero weight, as if the input were padded with ``-inf``: with an odd- ``kernel_size``, a window that overhangs the border averages over its in-image pixels only.- - Known defects: the exponent is shifted by the maximum of the whole map and ``eps`` is added to each+ - ``padding`` adds positions of zero weight, as if the input were padded with ``-inf``: a window that+ overhangs the border averages over its in-image pixels only.+ - Known defect: the exponent is shifted by the maximum of the whole map and ``eps`` is added to eachwindow's denominator, so a window whose values sit far below that maximum, in units of ``temperature``, ispulled toward its centre with a value near ``0``, or is ``NaN`` in float16- (`#5020 <https://github.com/kornia/kornia/issues/5020>`_); with an even ``kernel_size`` and- ``padding = k // 2`` the border windows average a zero-padded coordinate into their centre and report a- point far inside the image (`#5066 <https://github.com/kornia/kornia/issues/5066>`_).+ (`#5020 <https://github.com/kornia/kornia/issues/5020>`_).Args:input: the given heatmap with shape :math:`(N, C, H_{in}, W_{in})`.@@ -411,10 +409,16 @@ def conv_soft_argmax2d(x_softmaxpool = x_softmaxpool.view(b, c, x_softmaxpool.size(2), x_softmaxpool.size(3))# We need to output also coordinates- # Pooled window center coordinates- grid_global: torch.Tensor = create_meshgrid(h, w, False, device).to(dtype).permute(0, 3, 1, 2)+ # Pooled window center coordinates. The grid covers the padded input and carries the coordinates on into the+ # padding: with an even kernel_size and padding = k / 2, a border window's centre straddles a padded pixel,+ # and a zero-padded grid would average 0 into it instead of -1 or W. The offset is applied before the cast, so a+ # float16 or bfloat16 coordinate is rounded once, as on an unpadded grid.+ py, px = (padding, padding) if isinstance(padding, int) else padding+ grid_global: torch.Tensor = create_meshgrid(h + 2 * py, w + 2 * px, False, device)+ grid_global = grid_global - torch.tensor([px, py], device=device, dtype=grid_global.dtype)+ grid_global = grid_global.to(dtype).permute(0, 3, 1, 2)- grid_global_pooled = F.conv2d(grid_global, center_kernel, stride=stride, padding=padding)+ grid_global_pooled = F.conv2d(grid_global, center_kernel, stride=stride)# Coordinates of maxima residual to window center# prepare kernel@@ -460,9 +464,8 @@ def conv_soft_argmax3d(:math:`v_p` the heatmap value there and :math:`T` the temperature.Convention:- - See the convention block of :func:`conv_soft_argmax2d`, including its known defects- (`#5020 <https://github.com/kornia/kornia/issues/5020>`_,- `#5066 <https://github.com/kornia/kornia/issues/5066>`_). Coordinates follow+ - See the convention block of :func:`conv_soft_argmax2d`, including its known defect+ (`#5020 <https://github.com/kornia/kornia/issues/5020>`_). Coordinates follow:ref:`Coordinates and sizes <coordinate-conventions>`; this function defaults to pixel coordinates.Args:@@ -537,10 +540,14 @@ def conv_soft_argmax3d(den = pool_coef * F.avg_pool3d(x_exp.view_as(input), kernel_size, stride=stride, padding=padding) + eps# We need to output also coordinates- # Pooled window center coordinates- grid_global: torch.Tensor = create_meshgrid3d(d, h, w, False, device=device).to(dtype).permute(0, 4, 1, 2, 3)-- grid_global_pooled = F.conv3d(grid_global, center_kernel, stride=stride, padding=padding)+ # Pooled window center coordinates, over the padded input as in conv_soft_argmax2d+ pz, py, px = (padding, padding, padding) if isinstance(padding, int) else padding+ grid_global: torch.Tensor = create_meshgrid3d(d + 2 * pz, h + 2 * py, w + 2 * px, False, device=device)+ # channels are (depth, x, y)+ grid_global = grid_global - torch.tensor([pz, px, py], device=device, dtype=grid_global.dtype)+ grid_global = grid_global.to(dtype).permute(0, 4, 1, 2, 3)++ grid_global_pooled = F.conv3d(grid_global, center_kernel, stride=stride)# Coordinates of maxima residual to window center# prepare kerneldiff --git a/tests/geometry/subpix/test_spatial_softargmax.py b/tests/geometry/subpix/test_spatial_softargmax.pyindex 7657fed50..271434ae5 100644--- a/tests/geometry/subpix/test_spatial_softargmax.py+++ b/tests/geometry/subpix/test_spatial_softargmax.py@@ -368,6 +368,52 @@ class TestConvSoftArgmax2d(BaseTester):expected = torch.tensor([8.0, 7.0], device=device, dtype=dtype)[:, None].expand(2, kx * ky)self.assert_close(coords[0, 0][:, holds_peak], expected, atol=1e-4, rtol=1e-4)+ @pytest.mark.parametrize(+ "kernel_size, padding", [((2, 2), (1, 1)), ((4, 4), (2, 2)), ((4, 6), (2, 3)), ((3, 3), (1, 1))]+ )+ @pytest.mark.parametrize("peak", [(0, 0), (6, 8)])+ def test_border_window_centre_with_padding_5066(self, device, dtype, kernel_size, padding, peak):+ # Every window that holds the one hot pixel reports it, including the border windows of an even kernel_size+ # at padding = k / 2, whose centre falls between a border pixel and a padded one. The coordinate grid used to+ # be zero-padded, so those windows averaged 0 into their centre: x = 3.5 instead of 8 at the right border.+ (ky, kx), (py, px), (row, col) = kernel_size, padding, peak+ data = torch.zeros(1, 1, 7, 9, device=device, dtype=dtype)+ data[..., row, col] = 50.0+ coords = kornia.geometry.subpix.conv_soft_argmax2d(+ data, kernel_size, (1, 1), padding, normalized_coordinates=False+ )+ rows = torch.arange(coords.shape[-2], device=device)+ cols = torch.arange(coords.shape[-1], device=device)+ holds_peak = ((rows - py <= row) & (rows - py > row - ky))[:, None] & (+ (cols - px <= col) & (cols - px > col - kx)+ )[None, :]+ n = int(holds_peak.sum())+ assert n > 0+ expected = torch.tensor([float(col), float(row)], device=device, dtype=dtype)[:, None]+ self.assert_close(coords[0, 0][:, holds_peak], expected.expand(2, n), atol=1e-4, rtol=1e-4)++ def test_window_centre_rounds_once_on_wide_maps(self, device, dtype):+ # On a flat map every full window reports its own centre. The padded centre grid is offset before its cast,+ # so a bfloat16 column is rounded once, as on an unpadded grid: offsetting after the cast rounded twice and+ # moved columns above 256 by one bfloat16 step (column 256 read 255).+ data = torch.zeros(1, 1, 3, 600, device=device, dtype=dtype)+ coords = kornia.geometry.subpix.conv_soft_argmax2d(data, (3, 3), (1, 1), (1, 1), normalized_coordinates=False)+ expected = torch.arange(1, 599, device=device, dtype=torch.float32).to(dtype)+ self.assert_close(coords[0, 0, 0, 1, 1:-1], expected, rtol=0, atol=0)++ def test_int_padding_matches_tuple(self, device, dtype):+ data = torch.zeros(1, 1, 5, 9, device=device, dtype=dtype)+ data[0, 0, 2, 8] = 5.0+ data[0, 0, 0, 0] = 3.0+ for kernel_size, padding in (((4, 4), 2), ((3, 3), 1)):+ expected = kornia.geometry.subpix.conv_soft_argmax2d(+ data, kernel_size, (1, 1), (padding, padding), normalized_coordinates=False+ )+ actual = kornia.geometry.subpix.conv_soft_argmax2d(+ data, kernel_size, (1, 1), padding, normalized_coordinates=False+ )+ self.assert_close(actual, expected, rtol=0, atol=0)+@pytest.mark.parametrize("temperature", [0.0, float("nan"), "tensor"])@pytest.mark.parametrize("op, shape", [("conv_soft_argmax2d", (1, 1, 3, 3)), ("conv_soft_argmax3d", (1, 1, 3, 3, 3))]@@ -556,6 +602,47 @@ class TestConvSoftArgmax3d(BaseTester):expected = torch.tensor([5.0, 6.0, 4.0], device=device, dtype=dtype)[:, None].expand(3, kx * ky * kz)self.assert_close(coords[0, 0][:, holds_peak], expected, atol=1e-4, rtol=1e-4)+ @pytest.mark.parametrize(+ "kernel_size, padding", [((3, 3, 4), (1, 1, 2)), ((2, 2, 2), (1, 1, 1)), ((4, 2, 3), (2, 1, 1))]+ )+ @pytest.mark.parametrize("peak", [(0, 0, 0), (4, 5, 6)])+ def test_border_window_centre_with_padding_5066(self, device, dtype, kernel_size, padding, peak):+ # 3-D counterpart of TestConvSoftArgmax2d::test_border_window_centre_with_padding_5066: a zero-padded+ # coordinate grid pulled every channel of an even border window toward 0, not only the straddling axis.+ if not supports_avg_pool3d(device, dtype):+ pytest.skip(f"torch has no avg_pool3d kernel for {device.type} {dtype}")+ (kz, ky, kx), (pz, py, px), (lev, row, col) = kernel_size, padding, peak+ data = torch.zeros(1, 1, 5, 6, 7, device=device, dtype=dtype)+ data[..., lev, row, col] = 50.0+ coords = kornia.geometry.subpix.conv_soft_argmax3d(+ data, kernel_size, (1, 1, 1), padding, normalized_coordinates=False, output_value=False+ )+ levels = torch.arange(coords.shape[-3], device=device)+ rows = torch.arange(coords.shape[-2], device=device)+ cols = torch.arange(coords.shape[-1], device=device)+ holds_peak = (+ ((levels - pz <= lev) & (levels - pz > lev - kz))[:, None, None]+ & ((rows - py <= row) & (rows - py > row - ky))[None, :, None]+ & ((cols - px <= col) & (cols - px > col - kx))[None, None, :]+ )+ n = int(holds_peak.sum())+ assert n > 0+ # channels are (depth, x, y)+ expected = torch.tensor([float(lev), float(col), float(row)], device=device, dtype=dtype)[:, None]+ self.assert_close(coords[0, 0][:, holds_peak], expected.expand(3, n), atol=1e-4, rtol=1e-4)++ def test_int_padding_matches_tuple(self, device, dtype):+ if not supports_avg_pool3d(device, dtype):+ pytest.skip(f"torch has no avg_pool3d kernel for {device.type} {dtype}")+ data = torch.zeros(1, 1, 4, 5, 7, device=device, dtype=dtype)+ data[0, 0, 3, 4, 6] = 5.0+ data[0, 0, 0, 0, 0] = 3.0+ for kernel_size, padding in (((2, 2, 2), 1), ((3, 3, 3), 1)):+ expected = kornia.geometry.subpix.conv_soft_argmax3d(data, kernel_size, (1, 1, 1), (padding,) * 3)+ actual = kornia.geometry.subpix.conv_soft_argmax3d(data, kernel_size, (1, 1, 1), padding)+ for got, want in zip(actual, expected):+ self.assert_close(got, want, rtol=0, atol=0)+class TestConvQuadInterp3dModule(BaseTester):def test_smoke(self, device, dtype):@@ -1178,15 +1265,16 @@ class TestConventionsConvSoftArgmax(BaseTester):assert float(coords[0, 0, 0, 3, 10]) > 10.05assert float(values[0, 0, 3, 10]) > 0.3- def test_wart_conv_soft_argmax2d_even_window_border_centre_5066(self, device, dtype):- # #5066: zero padding moves an even border window's reported centre away from its hot pixel.+ def test_convention_conv_soft_argmax2d_even_window_border_centre_5066(self, device, dtype):+ # #5066: an even border window whose centre straddles the padding reports its hot pixel, as an odd one does.heatmap = torch.zeros(1, 1, 5, 9, device=device, dtype=dtype)heatmap[0, 0, 2, 8] = 50.0+ expected = torch.tensor([8.0, 2.0], device=device, dtype=dtype)odd = kornia.geometry.subpix.conv_soft_argmax2d(heatmap, (3, 3), (1, 1), (1, 1), normalized_coordinates=False)- self.assert_close(odd[0, 0, 0, 2, -1], torch.tensor(8.0, device=device, dtype=dtype))+ self.assert_close(odd[0, 0, :, 2, -1], expected)even = kornia.geometry.subpix.conv_soft_argmax2d(heatmap, (4, 4), (1, 1), (2, 2), normalized_coordinates=False)assert even.shape[-1] == 10- assert float(even[0, 0, 0, 2, -1]) < 5.0+ self.assert_close(even[0, 0, :, 2, -1], expected)class TestConventionsQuadInterp3d(BaseTester):