π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
fix(subpix): fix the four defects reported in #6472 (#6512)
Lucas Santlemeb4a7dbb9ab5a
diff --git a/changelog.d/6512.fixed.md b/changelog.d/6512.fixed.mdnew file mode 100644index 000000000..56a4bc740--- /dev/null+++ b/changelog.d/6512.fixed.md@@ -0,0 +1 @@+Fixed four defects in `kornia.geometry.subpix`: the `SpatialSoftArgmax2d` repr dropped its opening parenthesis, `conv_soft_argmax3d` raised a `TypeError` for an integer `stride`, `render_gaussian2d` returned an all-NaN map for a zero `std` instead of raising, and `spatial_softmax2d` truncated a tensor temperature cast to an integer heatmap's dtype.diff --git a/kornia/geometry/subpix/dsnt.py b/kornia/geometry/subpix/dsnt.pyindex 1368c8588..98d72bc28 100644--- a/kornia/geometry/subpix/dsnt.py+++ b/kornia/geometry/subpix/dsnt.py@@ -27,7 +27,7 @@ from typing import Optionalimport torchimport torch.nn.functional as F-from kornia.core.check import KORNIA_CHECK_IS_TENSOR, KORNIA_CHECK_SHAPE+from kornia.core.check import KORNIA_CHECK_IS_TENSOR, KORNIA_CHECK_SHAPE, _check_asyncfrom kornia.core.utils import is_compilingfrom kornia.geometry.grid import create_meshgrid@@ -82,13 +82,15 @@ def spatial_softmax2d(input: torch.Tensor, temperature: Optional[torch.Tensor |if temperature is None:temperature = 1.0_check_positive_temperature(temperature)- if isinstance(temperature, torch.Tensor):- temperature = temperature.to(device=input.device, dtype=input.dtype)x = input.reshape(batch_size, channels, height * width)# An integer map is divided in the default floating dtype, as ``x / temperature`` does; the shift below would wrap# in its own dtype (``uint8``).if not x.is_floating_point():x = x.to(torch.get_default_dtype())+ if isinstance(temperature, torch.Tensor):+ # Cast the temperature to the dtype the division runs in, not to the input's: an integer input dtype would+ # truncate a fractional temperature first (0.5 to 0, which then divides by zero, and 2.5 to 2).+ temperature = temperature.to(device=input.device, dtype=x.dtype)# Softmax is invariant to a shift by a constant per map. Subtracting the maximum leaves every logit at or below# zero, so dividing by a sharp temperature cannot overflow the input dtype (``max|logit| / temperature > 65504``@@ -166,7 +168,7 @@ def render_gaussian2d(Args:mean: the mean location of the Gaussian to render, :math:`(\mu_x, \mu_y)`. Shape: ``(*, 2)``.std: the standard deviation of the Gaussian to render, :math:`(\sigma_x, \sigma_y)`.- Shape ``(*, 2)``. Should be able to be broadcast with `mean`.+ Shape ``(*, 2)``. Should be able to be broadcast with `mean`. Every entry must be nonzero.size: the (height, width) of the output image.normalized_coordinates: whether ``mean`` and ``std`` are assumed to use coordinates normalizedin the range of :math:`[-1, 1]`. Otherwise, coordinates are assumed to be in the range of the output shape.@@ -178,6 +180,10 @@ def render_gaussian2d(if not (std.dtype == mean.dtype and std.device == mean.device):raise TypeError("Expected inputs to have the same dtype and device")+ # A zero std makes the inverse variance infinite, and the map comes out all NaN. The check runs where ``std``+ # lives, so a device tensor is not read back on the host (see ``_check_async``).+ _check_async((std != 0).all(), "std should be nonzero")+height, width = sizedtype = mean.dtypedevice = mean.devicediff --git a/kornia/geometry/subpix/spatial_soft_argmax.py b/kornia/geometry/subpix/spatial_soft_argmax.pyindex 73941acfc..4fdb36dbb 100644--- a/kornia/geometry/subpix/spatial_soft_argmax.py+++ b/kornia/geometry/subpix/spatial_soft_argmax.py@@ -253,7 +253,7 @@ class ConvSoftArgmax3d(nn.Module):def __init__(self,kernel_size: tuple[int, int, int] = (3, 3, 3),- stride: tuple[int, int, int] = (1, 1, 1),+ stride: int | tuple[int, int, int] = (1, 1, 1),padding: tuple[int, int, int] = (1, 1, 1),temperature: torch.Tensor | float = 1.0,normalized_coordinates: bool = False,@@ -467,7 +467,7 @@ def conv_soft_argmax2d(def conv_soft_argmax3d(input: torch.Tensor,kernel_size: tuple[int, int, int] = (3, 3, 3),- stride: tuple[int, int, int] = (1, 1, 1),+ stride: int | tuple[int, int, int] = (1, 1, 1),padding: tuple[int, int, int] = (1, 1, 1),temperature: torch.Tensor | float = 1.0,normalized_coordinates: bool = False,@@ -563,7 +563,7 @@ def conv_soft_argmax3d(h_out = (h + 2 * py - ky) // sy + 1w_out = (w + 2 * px - kx) // sx + 1pad = [px, px, py, py, pz, pz]- logits = _unfold3d(F.pad(input / temperature, pad, value=float("-inf")), kernel_size, stride)+ logits = _unfold3d(F.pad(input / temperature, pad, value=float("-inf")), kernel_size, (sz, sy, sx))weights = torch.softmax(logits, dim=2)# We need to output also coordinates@@ -573,7 +573,7 @@ def conv_soft_argmax3d(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)+ grid_global_pooled = F.conv3d(grid_global, center_kernel, stride=(sz, sy, sx))# Coordinates of maxima residual to window center: the softmax-weighted voxel offsets of each windowoffsets = window_kernel.reshape(3, kz * ky * kx)@@ -593,7 +593,7 @@ def conv_soft_argmax3d(if not output_value:return coords_max- windows = _unfold3d(F.pad(input, pad), kernel_size, stride)+ windows = _unfold3d(F.pad(input, pad), kernel_size, (sz, sy, sx))x_softmaxpool = (weights * windows).sum(2).view(b, c, d_out, h_out, w_out)return coords_max, x_softmaxpool@@ -651,7 +651,7 @@ class SpatialSoftArgmax2d(nn.Module):def __repr__(self) -> str:return (f"{self.__class__.__name__}"- f"temperature={self.temperature}, "+ f"(temperature={self.temperature}, "f"normalized_coordinates={self.normalized_coordinates})")diff --git a/testing/half_precision_eager_rng.py b/testing/half_precision_eager_rng.pyindex f315bdcc2..8bef99dc9 100644--- a/testing/half_precision_eager_rng.py+++ b/testing/half_precision_eager_rng.py@@ -188,7 +188,7 @@ AUDITED_EAGER_RNG_CALLS = tuple(),*_audited("tests/geometry/subpix/test_dsnt.py",- 179,+ 198,"torch.randn",1,(diff --git a/tests/geometry/subpix/test_dsnt.py b/tests/geometry/subpix/test_dsnt.pyindex 412b81cc1..b0ffbf39f 100644--- a/tests/geometry/subpix/test_dsnt.py+++ b/tests/geometry/subpix/test_dsnt.py@@ -19,6 +19,8 @@ import pytestimport torchimport kornia+from kornia.core._compat import torch_version_ge+from kornia.core.exceptions import AsyncCheckErrorfrom testing.base import BaseTester@@ -83,6 +85,23 @@ class TestRenderGaussian2d(BaseTester):self.assert_close(actual[0], gaussian, rtol=1e-5, atol=1e-5)+ @pytest.mark.parametrize("std", [[0.0, 0.25], [0.25, 0.0], [0.0, 0.0]])+ def test_zero_std_raises(self, device: torch.device, dtype: torch.dtype, std: list[float]) -> None:+ # A zero std used to render an all-NaN map: the inverse variance is infinite and 0 * inf is NaN.+ if device.type == "cuda":+ pytest.skip("not on CUDA: the value check is a device-side assert that invalidates the context")+ mean = torch.tensor([[0.0, 0.0]], device=device, dtype=dtype)+ std_t = torch.tensor([std], device=device, dtype=dtype)++ # From torch 2.13 the MPS assert raises at the next synchronization; elsewhere the host read raises at once.+ if device.type == "mps" and torch_version_ge(2, 13):+ kornia.geometry.subpix.render_gaussian2d(mean, std_t, (5, 5), True)+ with pytest.raises(RuntimeError, match="std should be nonzero"):+ torch.mps.synchronize()+ else:+ with pytest.raises(AsyncCheckError, match="std should be nonzero"):+ kornia.geometry.subpix.render_gaussian2d(mean, std_t, (5, 5), True)+@pytest.mark.parametrize("normalized", [False, True])def test_in_image_sums_to_one(self, device, dtype, normalized):# An off-centre, anisotropic Gaussian well inside a 9 x 11 grid: the per-axis renormalisation makes it sum to@@ -241,6 +260,22 @@ class TestSpatialSoftmax2d(BaseTester):expected = kornia.geometry.subpix.spatial_softmax2d(heatmap.to(torch.get_default_dtype()))self.assert_close(kornia.geometry.subpix.spatial_softmax2d(heatmap.to(map_dtype)), expected)+ @pytest.mark.parametrize("map_dtype", [torch.uint8, torch.int64])+ @pytest.mark.parametrize("temperature", [0.5, 2.5])+ def test_integer_map_with_tensor_temperature(+ self, device: torch.device, map_dtype: torch.dtype, temperature: float+ ) -> None:+ # A tensor temperature was cast to the map's integer dtype before the logits were promoted, so 0.5+ # became 0 (an all-NaN result) and 2.5 became 2. It must match the same temperature on the float map.+ heatmap = torch.tensor([[[[0, 5], [0, 0]]]], device=device)+ t = torch.tensor(temperature, device=device)++ expected = kornia.geometry.subpix.spatial_softmax2d(heatmap.to(torch.get_default_dtype()), t)+ actual = kornia.geometry.subpix.spatial_softmax2d(heatmap.to(map_dtype), t)++ assert torch.isfinite(actual).all()+ self.assert_close(actual, expected)+def test_sharp_temperature_does_not_overflow_float16(self, device):# #6087: dividing the raw logits by a sharp temperature overflowed float16 (max|logit| / temperature ># 65504) before softmax could stabilize them, so a finite heatmap returned NaN coordinates.diff --git a/tests/geometry/subpix/test_spatial_softargmax.py b/tests/geometry/subpix/test_spatial_softargmax.pyindex 36ba6d6fb..3a862b687 100644--- a/tests/geometry/subpix/test_spatial_softargmax.py+++ b/tests/geometry/subpix/test_spatial_softargmax.py@@ -166,6 +166,12 @@ class TestSpatialSoftArgmax2d(BaseTester):m = kornia.geometry.subpix.SpatialSoftArgmax2d()assert m(sample).shape == (2, 1, 2)+ def test_repr(self) -> None:+ # The repr dropped the opening parenthesis: "SpatialSoftArgmax2dtemperature=1.0, ...)".+ assert repr(kornia.geometry.subpix.SpatialSoftArgmax2d()) == (+ "SpatialSoftArgmax2d(temperature=1.0, normalized_coordinates=True)"+ )+@pytest.mark.parametrize("shape", [(0, 3, 4, 5), (2, 0, 4, 5)])def test_empty_batch_or_channels(self, device, dtype, shape):sample = torch.rand(shape, device=device, dtype=dtype)@@ -637,6 +643,17 @@ class TestConvSoftArgmax3d(BaseTester):assert coords.shape == (1, 1, 3, 3, 3, 3)assert val.shape == (1, 1, 3, 3, 3)+ @pytest.mark.parametrize("stride", [1, 2])+ def test_int_stride_matches_tuple_stride(self, device: torch.device, dtype: torch.dtype, stride: int) -> None:+ # An int stride raised TypeError in _unfold3d, which unpacks the stride; the 2D form accepts an int.+ sample = torch.rand(1, 1, 4, 5, 6, device=device, dtype=dtype)++ expected = kornia.geometry.subpix.conv_soft_argmax3d(sample, (3, 3, 3), (stride,) * 3, (1, 1, 1))+ actual = kornia.geometry.subpix.conv_soft_argmax3d(sample, (3, 3, 3), stride, (1, 1, 1))++ self.assert_close(actual[0], expected[0])+ self.assert_close(actual[1], expected[1])+def test_gradcheck(self, device):sample = torch.rand(1, 2, 3, 5, 5, device=device, dtype=torch.float64)self.gradcheck(kornia.geometry.subpix.conv_soft_argmax3d, (sample), nondet_tol=1e-8)