Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

fix(geometry): give every conv_soft_argmax window its own softmax (#5134)

区梓灏ea8ad2fe474f
diff --git a/changelog.d/5134.breaking.md b/changelog.d/5134.breaking.md
new file mode 100644
index 000000000..a1139ba71
--- /dev/null
+++ b/changelog.d/5134.breaking.md
@@ -0,0 +1,13 @@
+`conv_soft_argmax2d`, `conv_soft_argmax3d`, `ConvSoftArgmax2d` and `ConvSoftArgmax3d` now take the softmax of every
+window over that window's own values (#5020), so a window's coordinates and value no longer depend on the rest of the
+map. Previously the exponent was shifted by the maximum of the whole map and `eps` was added to each window's
+denominator: a window 15 or more units of `temperature` below that maximum was pulled toward its centre and its value
+toward 0, and from about 30 units it returned its centre with value 0 in float32, float64 and bfloat16; in float16 it
+was wrong from about 15 units and NaN from about 18. With `eps=0` such a window was right until `exp` underflowed and
+NaN beyond (about 95 units in float32 and bfloat16, 745 in float64). Windows near the map maximum move within
+precision: on maps spanning a few units of `temperature`, by up to about 3e-6 in float32 and float64 and by one to
+three ulp in float16 and bfloat16. `eps` is still accepted and has no effect. `conv_soft_argmax3d` now runs in float16
+and bfloat16 on CPU, where it raised `NotImplementedError` (`avg_pool3d`). A `padding` above half of `kernel_size`, or
+a negative one, raises `ValueError` instead of the pooling kernel's `RuntimeError`. The windows are unfolded, which
+takes `k*k` (2D) or `k*k*k` (3D) times the memory of the output map, and a CPU forward pass takes about 1.2 to 2.4
+times as long as before (3x3 to 15x15 windows).
diff --git a/docs/source/get-started/precision.rst b/docs/source/get-started/precision.rst
index e42a27dfc..8167a20b7 100644
--- a/docs/source/get-started/precision.rst
+++ b/docs/source/get-started/precision.rst
@@ -101,9 +101,9 @@ precision, so the table says nothing about those backends.
* - ``kornia.geometry.subpix``
- ⚠️ Partial
- ⚠️ Partial
- - 14 / 12
- - ``ConvSoftArgmax3d`` raises because CPU ``avg_pool3d`` has no half-precision kernel; the remaining
- entries are accuracy.
+ - 6 / 4
+ - Accuracy of ``SpatialSoftArgmax2d`` and of the ``ConvQuadInterp3d`` diagonal refinement; bfloat16 also
+ ``render_gaussian2d``.
* - ``kornia.geometry.conversions``
- ⚠️ Partial
- ⚠️ Partial
diff --git a/kornia/geometry/subpix/spatial_soft_argmax.py b/kornia/geometry/subpix/spatial_soft_argmax.py
index 74efc5038..7c9df4bfd 100644
--- a/kornia/geometry/subpix/spatial_soft_argmax.py
+++ b/kornia/geometry/subpix/spatial_soft_argmax.py
@@ -309,6 +309,20 @@ class ConvSoftArgmax3d(nn.Module):
)
+def _unfold3d(padded: torch.Tensor, kernel_size: tuple[int, int, int], stride: tuple[int, int, int]) -> torch.Tensor:
+ """Unfold an already padded ``(N, 1, D, H, W)`` volume into ``(N, D_out, kz * ky * kx, H_out * W_out)`` windows.
+
+ Each depth slice is unfolded like an image, then the slices are unfolded along depth, so the window values are in
+ (depth, row, column) order.
+ """
+ n, _, d_p, h_p, w_p = padded.shape
+ kz, ky, kx = kernel_size
+ sz, sy, sx = stride
+ columns = F.unfold(padded.reshape(n * d_p, 1, h_p, w_p), (ky, kx), stride=(sy, sx))
+ columns = columns.view(n, d_p, ky * kx, -1).unfold(1, kz, sz) # (N, D_out, ky * kx, L, kz)
+ return columns.permute(0, 1, 4, 2, 3).reshape(n, columns.shape[1], kz * ky * kx, -1)
+
+
def conv_soft_argmax2d(
input: torch.Tensor,
kernel_size: tuple[int, int] = (3, 3),
@@ -336,21 +350,20 @@ def conv_soft_argmax2d(
: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``: 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 each
- window's denominator, so a window whose values sit far below that maximum, in units of ``temperature``, is
- pulled toward its centre with a value near ``0``, or is ``NaN`` in float16
- (`#5020 <https://github.com/kornia/kornia/issues/5020>`_).
+ - Each window is the softmax of its own values: the exponent is shifted by the window's maximum, so a
+ window's coordinates and value do not depend on the rest of the map, in float16 either. ``eps`` is
+ accepted and has no effect (`#5020 <https://github.com/kornia/kornia/issues/5020>`_).
Args:
input: the given heatmap with shape :math:`(N, C, H_{in}, W_{in})`.
kernel_size: the size of the window.
stride: the stride of the window.
- padding: the padding added to each side of the input.
+ padding: the padding added to each side of the input, at most half of ``kernel_size`` on every axis.
temperature: softmax temperature: the input is divided by it; smaller is sharper. Must be positive.
A tensor temperature is not checked under ``torch.compile`` or export.
normalized_coordinates: whether to return the coordinates normalized in the range of :math:`[-1, 1]`.
Otherwise, it will return the coordinates in the range of the input shape.
- eps: small value to avoid zero division.
+ eps: accepted for backward compatibility and ignored; every window's softmax denominator is at least 1.
output_value: if True, val is output, if False, only ij.
Returns:
@@ -383,6 +396,8 @@ def conv_soft_argmax2d(
b, c, h, w = input.shape
ky, kx = kernel_size
+ sy, sx = (stride, stride) if isinstance(stride, int) else stride
+ py, px = (padding, padding) if isinstance(padding, int) else padding
device: torch.device = input.device
dtype: torch.dtype = input.dtype
input = input.view(b * c, 1, h, w)
@@ -390,42 +405,37 @@ def conv_soft_argmax2d(
center_kernel: torch.Tensor = _get_center_kernel2d(ky, kx, device).to(dtype)
window_kernel: torch.Tensor = _get_window_grid_kernel2d(ky, kx, device).to(dtype)
- # applies exponential normalization trick
- # https://timvieira.github.io/blog/post/2014/02/11/exp-F.normalize-trick/
- # https://github.com/pytorch/pytorch/blob/bcb0bb7e0e03b386ad837015faba6b4b16e3bfb9/aten/src/ATen/native/SoftMax.cpp#L44
- x_max = input.amax(dim=(-2, -1), keepdim=True) # faster than F.adaptive_max_pool2d(input, (1,1))
-
- # max is detached to prevent undesired backprop loops in the graph
- x_exp = ((input - x_max.detach()) / temperature).exp()
-
- # F.avg_pool2d(.., divisor_override = 1.0) - proper way for sum pool in PyTorch 1.2.
- # Not available yet in version 1.0, so let's do manually
- pool_coef: float = float(kx * ky)
-
- # F.softmax denominator
- den = pool_coef * F.avg_pool2d(x_exp, kernel_size, stride=stride, padding=padding) + eps
+ if not (0 <= 2 * py <= ky and 0 <= 2 * px <= kx):
+ raise ValueError(
+ f"padding must be non-negative and at most half of kernel_size. Got {padding} for kernel_size {kernel_size}"
+ )
- x_softmaxpool = pool_coef * F.avg_pool2d(x_exp * input, kernel_size, stride=stride, padding=padding) / den
- x_softmaxpool = x_softmaxpool.view(b, c, x_softmaxpool.size(2), x_softmaxpool.size(3))
+ # Softmax over each window on its own: `softmax` shifts every window by its own maximum, so the denominator is
+ # at least 1 whatever the rest of the map holds and no `eps` is needed. A single `exp` map shifted by the
+ # map-wide maximum underflowed for windows far below it and `eps` then pulled them to their centre (#5020).
+ # The unfolded windows hold `kernel_size` values per output position. The map is divided by the temperature
+ # before it is unfolded, so a tensor temperature broadcasts against the map as before, and padded with `-inf`
+ # logits, which carry no weight.
+ n = b * c
+ h_out = (h + 2 * py - ky) // sy + 1
+ w_out = (w + 2 * px - kx) // sx + 1
+ logits = F.unfold(F.pad(input / temperature, [px, px, py, py], value=float("-inf")), kernel_size, stride=stride)
+ weights = torch.softmax(logits, dim=1)
# We need to output also coordinates
# 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)
- # Coordinates of maxima residual to window center
- # prepare kernel
- coords_max: torch.Tensor = F.conv2d(x_exp, window_kernel, stride=stride, padding=padding)
-
- coords_max = coords_max / den.expand_as(coords_max)
- coords_max = coords_max + grid_global_pooled.expand_as(coords_max)
+ # Coordinates of maxima residual to window center: the softmax-weighted pixel offsets of each window
+ offsets = window_kernel.reshape(2, ky * kx)
+ coords_max = (offsets @ weights).view(n, 2, h_out, w_out) + grid_global_pooled.expand(n, 2, h_out, w_out)
# [:,:, 0, ...] is x
# [:,:, 1, ...] is y
@@ -436,9 +446,13 @@ def conv_soft_argmax2d(
# Back B*C -> (b, c)
coords_max = coords_max.view(b, c, 2, coords_max.size(2), coords_max.size(3))
- if output_value:
- return coords_max, x_softmaxpool
- return coords_max
+ if not output_value:
+ return coords_max
+
+ # Padded positions have value 0 here and weight 0, so they do not enter the pooled value.
+ windows = F.unfold(F.pad(input, [px, px, py, py]), kernel_size, stride=stride)
+ x_softmaxpool = (weights * windows).sum(1).view(b, c, h_out, w_out)
+ return coords_max, x_softmaxpool
def conv_soft_argmax3d(
@@ -464,20 +478,19 @@ 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 defect
- (`#5020 <https://github.com/kornia/kornia/issues/5020>`_). Coordinates follow
+ - See the convention block of :func:`conv_soft_argmax2d`. Coordinates follow
:ref:`Coordinates and sizes <coordinate-conventions>`; this function defaults to pixel coordinates.
Args:
input: the given heatmap with shape :math:`(N, C, D_{in}, H_{in}, W_{in})`.
kernel_size: size of the window.
stride: stride of the window.
- padding: the padding added to each side of the input.
+ padding: the padding added to each side of the input, at most half of ``kernel_size`` on every axis.
temperature: softmax temperature: the input is divided by it; smaller is sharper. Must be positive.
A tensor temperature is not checked under ``torch.compile`` or export.
normalized_coordinates: whether to return the coordinates normalized in the range of :math:`[-1, 1]`.
Otherwise, it will return the coordinates in the range of the input shape.
- eps: small value to avoid zero division.
+ eps: accepted for backward compatibility and ignored; every window's softmax denominator is at least 1.
output_value: if True, val is output, if False, only ij.
strict_maxima_bonus: deprecated since kornia 0.9.0 and ignored; passing it emits a
:class:`DeprecationWarning`. Select strict maxima with :func:`~kornia.geometry.subpix.nms3d` instead.
@@ -519,6 +532,8 @@ def conv_soft_argmax3d(
b, c, d, h, w = input.shape
kz, ky, kx = kernel_size
+ sz, sy, sx = (stride, stride, stride) if isinstance(stride, int) else stride
+ pz, py, px = (padding, padding, padding) if isinstance(padding, int) else padding
device: torch.device = input.device
dtype: torch.dtype = input.dtype
input = input.view(b * c, 1, d, h, w)
@@ -526,22 +541,24 @@ def conv_soft_argmax3d(
center_kernel: torch.Tensor = _get_center_kernel3d(kz, ky, kx, device).to(dtype)
window_kernel: torch.Tensor = _get_window_grid_kernel3d(kz, ky, kx, device).to(dtype)
- # applies exponential normalization trick
- # https://timvieira.github.io/blog/post/2014/02/11/exp-F.normalize-trick/
- # https://github.com/pytorch/pytorch/blob/bcb0bb7e0e03b386ad837015faba6b4b16e3bfb9/aten/src/ATen/native/SoftMax.cpp#L44
- x_max = input.amax(dim=(-3, -2, -1), keepdim=True) # faster than F.adaptive_max_pool3d(input, (1,1,1))
-
- # max is detached to prevent undesired backprop loops in the graph
- x_exp = ((input - x_max.detach()) / temperature).exp()
-
- pool_coef: float = float(kx * ky * kz)
+ if not (0 <= 2 * pz <= kz and 0 <= 2 * py <= ky and 0 <= 2 * px <= kx):
+ raise ValueError(
+ f"padding must be non-negative and at most half of kernel_size. Got {padding} for kernel_size {kernel_size}"
+ )
- # F.softmax denominator
- den = pool_coef * F.avg_pool3d(x_exp.view_as(input), kernel_size, stride=stride, padding=padding) + eps
+ # Softmax over each window on its own, as in conv_soft_argmax2d (#5020): the windows are unfolded slice by
+ # slice and then along depth, holding `kernel_size` values per output position, in (depth, row, column) order
+ # like the window kernel.
+ n = b * c
+ d_out = (d + 2 * pz - kz) // sz + 1
+ h_out = (h + 2 * py - ky) // sy + 1
+ w_out = (w + 2 * px - kx) // sx + 1
+ pad = [px, px, py, py, pz, pz]
+ logits = _unfold3d(F.pad(input / temperature, pad, value=float("-inf")), kernel_size, stride)
+ weights = torch.softmax(logits, dim=2)
# We need to output also coordinates
# 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)
@@ -549,12 +566,10 @@ def conv_soft_argmax3d(
grid_global_pooled = F.conv3d(grid_global, center_kernel, stride=stride)
- # Coordinates of maxima residual to window center
- # prepare kernel
- coords_max: torch.Tensor = F.conv3d(x_exp, window_kernel, stride=stride, padding=padding)
-
- coords_max = coords_max / den.expand_as(coords_max)
- coords_max = coords_max + grid_global_pooled.expand_as(coords_max)
+ # Coordinates of maxima residual to window center: the softmax-weighted voxel offsets of each window
+ offsets = window_kernel.reshape(3, kz * ky * kx)
+ coords_max = (offsets @ weights).view(n, d_out, 3, h_out, w_out).transpose(1, 2)
+ coords_max = coords_max + grid_global_pooled.expand(n, 3, d_out, h_out, w_out)
# [:,:, 0, ...] is depth (scale)
# [:,:, 1, ...] is x
# [:,:, 2, ...] is y
@@ -569,10 +584,8 @@ def conv_soft_argmax3d(
if not output_value:
return coords_max
- x_softmaxpool = (
- pool_coef * F.avg_pool3d(x_exp.view(input.size()) * input, kernel_size, stride=stride, padding=padding) / den
- )
- x_softmaxpool = x_softmaxpool.view(b, c, x_softmaxpool.size(2), x_softmaxpool.size(3), x_softmaxpool.size(4))
+ windows = _unfold3d(F.pad(input, pad), kernel_size, stride)
+ x_softmaxpool = (weights * windows).sum(2).view(b, c, d_out, h_out, w_out)
return coords_max, x_softmaxpool
diff --git a/testing/base.py b/testing/base.py
index a7d766c52..cb915aa7c 100644
--- a/testing/base.py
+++ b/testing/base.py
@@ -343,20 +343,6 @@ def supports_topk(device: torch.device, dtype: torch.dtype) -> bool:
return _supports_kernel_probe(_topk_op, device.type, dtype)
-def _avg_pool3d_op(device_type: str, dtype: torch.dtype) -> None:
- F.avg_pool3d(_probe_zeros(device_type, dtype, 1, 1, 1, 1, 1), 1)
-
-
-def supports_avg_pool3d(device: torch.device, dtype: torch.dtype) -> bool:
- """Whether this device has a 3D average-pooling kernel for ``dtype``.
-
- :func:`kornia.geometry.subpix.conv_soft_argmax3d` pools its windows with ``avg_pool3d``, which
- torch has no float16 / bfloat16 CPU kernel for. Probed at runtime and cached per (device type,
- dtype), like :func:`supports_replicate_padding`.
- """
- return _supports_kernel_probe(_avg_pool3d_op, device.type, dtype)
-
-
class BaseTester:
@staticmethod
def assert_close(
diff --git a/testing/half_precision_xfails/cpu_bfloat16.txt b/testing/half_precision_xfails/cpu_bfloat16.txt
index fdf086bd9..232984a09 100644
--- a/testing/half_precision_xfails/cpu_bfloat16.txt
+++ b/testing/half_precision_xfails/cpu_bfloat16.txt
@@ -290,14 +290,6 @@ call builtins.AssertionError tests/geometry/solvers/test_polynomial_solver.py::T
call builtins.AssertionError tests/geometry/subpix/test_dsnt.py::TestRenderGaussian2d::test_normalized_coordinates[cpu-bfloat16]
call builtins.AssertionError tests/geometry/subpix/test_dsnt.py::TestRenderGaussian2d::test_pixel_coordinates[cpu-bfloat16]
call builtins.AssertionError tests/geometry/subpix/test_spatial_softargmax.py::TestConvQuadInterp3dModule::test_diag[cpu-bfloat16]
-call builtins.AssertionError tests/geometry/subpix/test_spatial_softargmax.py::TestConvSoftArgmax2d::test_hot_diag[cpu-bfloat16]
-call builtins.AssertionError tests/geometry/subpix/test_spatial_softargmax.py::TestConvSoftArgmax2d::test_hot_diag_norm[cpu-bfloat16]
-call builtins.NotImplementedError tests/geometry/subpix/test_spatial_softargmax.py::TestConvSoftArgmax3d::test_cold_diag[cpu-bfloat16]
-call builtins.NotImplementedError tests/geometry/subpix/test_spatial_softargmax.py::TestConvSoftArgmax3d::test_cold_diag_norm[cpu-bfloat16]
-call builtins.NotImplementedError tests/geometry/subpix/test_spatial_softargmax.py::TestConvSoftArgmax3d::test_hot_diag[cpu-bfloat16]
-call builtins.NotImplementedError tests/geometry/subpix/test_spatial_softargmax.py::TestConvSoftArgmax3d::test_hot_diag_norm[cpu-bfloat16]
-call builtins.NotImplementedError tests/geometry/subpix/test_spatial_softargmax.py::TestConvSoftArgmax3d::test_smoke[cpu-bfloat16]
-call builtins.NotImplementedError tests/geometry/subpix/test_spatial_softargmax.py::TestConvSoftArgmax3d::test_smoke_with_val[cpu-bfloat16]
call builtins.AssertionError tests/geometry/subpix/test_spatial_softargmax.py::TestSpatialSoftArgmax2d::test_end_to_end[cpu-bfloat16]
call builtins.AssertionError tests/geometry/test_bbox.py::TestTransformBoxes2D::test_transform_boxes[cpu-bfloat16]
call builtins.AssertionError tests/geometry/test_bbox.py::TestTransformBoxes2D::test_transform_boxes_wh[cpu-bfloat16]
diff --git a/testing/half_precision_xfails/cpu_float16.txt b/testing/half_precision_xfails/cpu_float16.txt
index 13d68a950..d984360bb 100644
--- a/testing/half_precision_xfails/cpu_float16.txt
+++ b/testing/half_precision_xfails/cpu_float16.txt
@@ -298,14 +298,6 @@ call builtins.NotImplementedError tests/geometry/liegroup/test_so2.py::TestSo2::
call builtins.AssertionError tests/geometry/liegroup/test_so3.py::TestSo3::test_ortho[cpu-float16-2]
call builtins.AssertionError tests/geometry/solvers/test_polynomial_solver.py::TestQuarticSolver::test_random[cpu-float16]
call builtins.AssertionError tests/geometry/subpix/test_spatial_softargmax.py::TestConvQuadInterp3dModule::test_diag[cpu-float16]
-call builtins.AssertionError tests/geometry/subpix/test_spatial_softargmax.py::TestConvSoftArgmax2d::test_cold_diag[cpu-float16]
-call builtins.AssertionError tests/geometry/subpix/test_spatial_softargmax.py::TestConvSoftArgmax2d::test_cold_diag_norm[cpu-float16]
-call builtins.NotImplementedError tests/geometry/subpix/test_spatial_softargmax.py::TestConvSoftArgmax3d::test_cold_diag[cpu-float16]
-call builtins.NotImplementedError tests/geometry/subpix/test_spatial_softargmax.py::TestConvSoftArgmax3d::test_cold_diag_norm[cpu-float16]
-call builtins.NotImplementedError tests/geometry/subpix/test_spatial_softargmax.py::TestConvSoftArgmax3d::test_hot_diag[cpu-float16]
-call builtins.NotImplementedError tests/geometry/subpix/test_spatial_softargmax.py::TestConvSoftArgmax3d::test_hot_diag_norm[cpu-float16]
-call builtins.NotImplementedError tests/geometry/subpix/test_spatial_softargmax.py::TestConvSoftArgmax3d::test_smoke[cpu-float16]
-call builtins.NotImplementedError tests/geometry/subpix/test_spatial_softargmax.py::TestConvSoftArgmax3d::test_smoke_with_val[cpu-float16]
call builtins.AssertionError tests/geometry/subpix/test_spatial_softargmax.py::TestSpatialSoftArgmax2d::test_batch2_n2[cpu-float16]
call builtins.AssertionError tests/geometry/subpix/test_spatial_softargmax.py::TestSpatialSoftArgmax2d::test_bottom_right[cpu-float16]
call builtins.AssertionError tests/geometry/subpix/test_spatial_softargmax.py::TestSpatialSoftArgmax2d::test_bottom_right_normalized[cpu-float16]
diff --git a/tests/geometry/subpix/test_spatial_softargmax.py b/tests/geometry/subpix/test_spatial_softargmax.py
index 6f70ac283..0bace3727 100644
--- a/tests/geometry/subpix/test_spatial_softargmax.py
+++ b/tests/geometry/subpix/test_spatial_softargmax.py
@@ -15,6 +15,7 @@
# limitations under the License.
#
+import itertools
import warnings
import pytest
@@ -28,7 +29,7 @@ from kornia.geometry.subpix.spatial_soft_argmax import (
conv_quad_interp3d,
)
-from testing.base import BaseTester, supports_avg_pool3d
+from testing.base import BaseTester
class TestCenterKernel2d(BaseTester):
@@ -425,6 +426,42 @@ class TestConvSoftArgmax2d(BaseTester):
with pytest.raises(ValueError, match="Temperature should be positive"):
getattr(kornia.geometry.subpix, op)(data, temperature=temperature)
+ @pytest.mark.parametrize(
+ "op, shape", [("conv_soft_argmax2d", (2, 3, 5, 7)), ("conv_soft_argmax3d", (2, 3, 4, 5, 7))]
+ )
+ def test_tensor_temperature_matches_float(self, device, dtype, op, shape):
+ # A one-element tensor temperature of any rank that broadcasts against the map gives the float result: the
+ # map is divided before its windows are unfolded, so a (1, 1, 1, 1) temperature does not broadcast against
+ # the (N, k, L) windows instead.
+ data = torch.zeros(shape, device=device, dtype=dtype)
+ data[0, 1, ..., 1, 3] = 2.0
+ data[1, 2, ..., 3, 5] = 1.0
+ fn = getattr(kornia.geometry.subpix, op)
+ expected = fn(data, temperature=0.5, output_value=True)
+ for temperature_shape in ((), (1,), (1,) * len(shape)):
+ temperature = torch.full(temperature_shape, 0.5, device=device, dtype=dtype)
+ actual = fn(data, temperature=temperature, output_value=True)
+ for got, want in zip(actual, expected):
+ self.assert_close(got, want, rtol=0, atol=0)
+
+ @pytest.mark.parametrize(
+ "op, kernel_size, padding",
+ [
+ ("conv_soft_argmax2d", (3, 3), (2, 1)),
+ ("conv_soft_argmax2d", (1, 3), (1, 0)),
+ ("conv_soft_argmax2d", (3, 3), (1, -1)),
+ ("conv_soft_argmax3d", (3, 3, 3), (1, 1, 2)),
+ ("conv_soft_argmax3d", (1, 3, 3), (1, 1, 1)),
+ ("conv_soft_argmax3d", (3, 3, 3), (-1, 1, 1)),
+ ],
+ )
+ def test_padding_over_half_kernel_raises(self, device, dtype, op, kernel_size, padding):
+ # A padding above half the window, or a negative one, raises as the pooling kernels did: past the window
+ # size a window would hold padding only and have no softmax, and a negative padding would crop the map.
+ data = torch.zeros((1, 1) + (3, 5, 7)[-len(kernel_size) :], device=device, dtype=dtype)
+ with pytest.raises(ValueError, match="padding must be non-negative and at most half of kernel_size"):
+ getattr(kornia.geometry.subpix, op)(data, kernel_size, (1,) * len(kernel_size), padding)
+
class TestConvSoftArgmax3d(BaseTester):
def test_smoke(self, device, dtype):
@@ -581,8 +618,6 @@ class TestConvSoftArgmax3d(BaseTester):
def test_window_offset_in_pixels_5017(self, device, dtype, kernel_size):
# 3-D counterpart of TestConvSoftArgmax2d::test_window_offset_in_pixels_5017: the depth offset used to
# come from linspace(-1, 1, d), so a 5-deep window reported depth 4 for a peak at depth 5.
- if device.type == "cpu" and dtype in (torch.float16, torch.bfloat16):
- pytest.skip("conv_soft_argmax3d has no CPU float16/bfloat16 kernel (avg_pool3d)")
kz, ky, kx = kernel_size
data = torch.zeros(1, 1, 11, 11, 13, device=device, dtype=dtype)
data[..., 5, 4, 6] = 50.0
@@ -609,8 +644,6 @@ class TestConvSoftArgmax3d(BaseTester):
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
@@ -632,8 +665,6 @@ class TestConvSoftArgmax3d(BaseTester):
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
@@ -1178,8 +1209,7 @@ class TestStrictMaximaBonusDeprecated(BaseTester):
# `strict_maxima_bonus` is deprecated since kornia 0.9.0. It is still accepted wherever 0.8.3 accepted it,
# by keyword or in its positional slot, but it warns and is ignored: a call that passes it returns what the
# call without it returns, and test_default_adds_no_bonus pins that the latter carries no bonus. The argument
- # handling does not depend on the dtype, so these run in float32 only: conv_soft_argmax3d has no CPU
- # float16/bfloat16 kernel (avg_pool3d).
+ # handling does not depend on the dtype, so these run in float32 only.
_SOFT = kornia.geometry.subpix.conv_soft_argmax3d
_CONV = kornia.geometry.subpix.conv_quad_interp3d
_ITER = kornia.geometry.subpix.iterative_quad_interp3d
@@ -1255,6 +1285,30 @@ class TestStrictMaximaBonusDeprecated(BaseTester):
self.assert_close(got, want, atol=0, rtol=0)
+def _window_softmax_reference(data, kernel_size, stride, padding, temperature):
+ """Softmax of every window of a ``(1, 1, *spatial)`` map over its in-image pixels, in float64 on the CPU.
+
+ Returns the coordinates, channels ``(x, y)`` in 2D and ``(d, x, y)`` in 3D, and the values.
+ """
+ data = data.cpu().double()[0, 0]
+ spatial = data.shape
+ out = [(n + 2 * p - k) // s + 1 for n, k, s, p in zip(spatial, kernel_size, stride, padding)]
+ coords = torch.zeros(len(spatial), *out, dtype=torch.float64)
+ values = torch.zeros(*out, dtype=torch.float64)
+ for index in itertools.product(*(range(n) for n in out)):
+ ranges = [
+ [q for q in range(i * s - p, i * s - p + k) if 0 <= q < n]
+ for i, n, k, s, p in zip(index, spatial, kernel_size, stride, padding)
+ ]
+ pixels = torch.tensor(list(itertools.product(*ranges)), dtype=torch.float64)
+ window = data[tuple(pixels.long().T)]
+ weights = torch.softmax(window / temperature, 0)
+ position = weights @ pixels # (row, column) or (depth, row, column)
+ coords[(slice(None), *index)] = position[[1, 0]] if len(spatial) == 2 else position[[0, 2, 1]]
+ values[index] = weights @ window
+ return coords, values
+
+
class TestConventionsConvSoftArgmax(BaseTester):
def test_convention_conv_soft_argmax2d_is_xy(self, device, dtype):
# Every window returns (x, y) = (column, row) of the input grid: pixel coordinates, or normalized
@@ -1280,8 +1334,6 @@ class TestConventionsConvSoftArgmax(BaseTester):
def test_convention_conv_soft_argmax3d_is_dxy(self, device, dtype):
# The 3-D windows return (d, x, y) = (depth, column, row). D != H != W, one hot voxel at (d 2, row 1, col 6):
# the window on it and the six beside it return (2, 6, 1). Swapping D and W is the relabel control.
- if not supports_avg_pool3d(device, dtype):
- pytest.skip(f"torch has no avg_pool3d kernel for {device.type} {dtype}")
volume = torch.zeros(1, 1, 4, 5, 8, device=device, dtype=dtype)
volume[0, 0, 2, 1, 6] = 30.0
coords, _ = kornia.geometry.subpix.conv_soft_argmax3d(volume, (3, 3, 3))
@@ -1298,26 +1350,25 @@ class TestConventionsConvSoftArgmax(BaseTester):
expected = torch.tensor([1 / 3, 5 / 7, -0.5], device=device, dtype=dtype)
self.assert_close(coords[0, 0, :, 2, 1, 6], expected)
- def test_wart_conv_soft_argmax_eps_erases_far_windows_5020(self, device, dtype):
- # #5020: global stabilization and per-window eps erase a local peak far below the map maximum.
+ def test_convention_conv_soft_argmax_far_window_is_its_own_softmax_5020(self, device, dtype):
+ # #5020: each window is shifted by its own maximum, so a local peak far below the map maximum keeps the
+ # softmax of its own 3 x 3 window and its value, in float16 too, and `eps` plays no part. The map-wide shift
+ # used to send this window to (10, 0) from a gap of 40 and to NaN in float16 from a gap of 20.
heatmap = torch.zeros(1, 1, 7, 15, device=device, dtype=dtype)
- heatmap[0, 0, 3, 2] = 40.0 # the map maximum, eight columns from the window under test
heatmap[0, 0, 3, 10] = 1.0
heatmap[0, 0, 3, 11] = 0.8 # pulls the window's soft-argmax right of its centre
- coords, values = kornia.geometry.subpix.conv_soft_argmax2d(
- heatmap, (3, 3), normalized_coordinates=False, output_value=True
- )
- x, value = coords[0, 0, 0, 3, 10], values[0, 0, 3, 10]
- if dtype == torch.float16:
- assert bool(x.isnan()) and bool(value.isnan())
- else:
- assert abs(float(x) - 10.0) < 1e-6
- assert abs(float(value)) < 1e-6
- coords, values = kornia.geometry.subpix.conv_soft_argmax2d(
- heatmap, (3, 3), normalized_coordinates=False, output_value=True, eps=0.0
- )
- assert float(coords[0, 0, 0, 3, 10]) > 10.05
- assert float(values[0, 0, 3, 10]) > 0.3
+ window = heatmap[0, 0, 2:5, 9:12].cpu().double().flatten() # float64 reference on CPU, MPS has no float64
+ weights = torch.softmax(window, 0)
+ expected_x = (weights * torch.arange(9, 12, dtype=torch.float64).repeat(3)).sum().to(device=device, dtype=dtype)
+ expected_value = (weights * window).sum().to(device=device, dtype=dtype)
+ for far_maximum in (0.0, 20.0, 40.0, 1000.0):
+ heatmap[0, 0, 3, 2] = far_maximum # eight columns from the window under test
+ for eps in (1e-8, 0.0):
+ coords, values = kornia.geometry.subpix.conv_soft_argmax2d(
+ heatmap, (3, 3), normalized_coordinates=False, output_value=True, eps=eps
+ )
+ self.assert_close(coords[0, 0, 0, 3, 10], expected_x)
+ self.assert_close(values[0, 0, 3, 10], expected_value)
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.
@@ -1330,6 +1381,30 @@ class TestConventionsConvSoftArgmax(BaseTester):
assert even.shape[-1] == 10
self.assert_close(even[0, 0, :, 2, -1], expected)
+ @pytest.mark.parametrize(
+ "op, shape, kernel_size, stride, padding",
+ [
+ ("conv_soft_argmax2d", (6, 9), (3, 4), (2, 3), (1, 2)),
+ ("conv_soft_argmax3d", (5, 6, 7), (3, 2, 3), (2, 1, 2), (1, 1, 1)),
+ ],
+ )
+ def test_convention_conv_soft_argmax_is_the_softmax_of_each_window(
+ self, device, dtype, op, shape, kernel_size, stride, padding
+ ):
+ # Every window, with unequal strides, kernel sides and paddings, is the softmax of its in-image pixels:
+ # a padded position carries no weight, not the weight of a 0 logit. A deterministic map in [0, 2] keeps the
+ # border windows' padded positions within a few units of temperature of their pixels.
+ numel = 1
+ for n in shape:
+ numel *= n
+ data = ((torch.arange(numel, device=device) * 7 % 11) / 5).reshape(1, 1, *shape).to(dtype)
+ coords, values = getattr(kornia.geometry.subpix, op)(
+ data, kernel_size, stride, padding, 0.5, normalized_coordinates=False, output_value=True
+ )
+ expected_coords, expected_values = _window_softmax_reference(data, kernel_size, stride, padding, 0.5)
+ self.assert_close(coords[0, 0], expected_coords.to(device=device, dtype=dtype))
+ self.assert_close(values[0, 0], expected_values.to(device=device, dtype=dtype))
+
class TestConventionsQuadInterp3d(BaseTester):
_FUNCTIONS = (kornia.geometry.subpix.conv_quad_interp3d, kornia.geometry.subpix.iterative_quad_interp3d)