π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
fix(geometry): make spatial_softmax2d's temperature divide the input, like conv_soft_argmax2d's (#5035)
Dmytro Mishkince432b886be4
diff --git a/changelog.d/5035.breaking.md b/changelog.d/5035.breaking.mdnew file mode 100644index 000000000..f1aa86e7e--- /dev/null+++ b/changelog.d/5035.breaking.md@@ -0,0 +1,6 @@+`spatial_softmax2d`, `spatial_soft_argmax2d` and `SpatialSoftArgmax2d` now treat `temperature` as a softmax+temperature, as `conv_soft_argmax2d` and `conv_soft_argmax3d` already did: the input is divided by it, so a smaller+value gives a sharper distribution. Previously the input was multiplied by `temperature`, so a larger value was+sharper; a Python float raised `AttributeError`; and `0` or a negative value was accepted (`0` returned a uniform map,+a negative value inverted it). A float is now accepted, and a temperature that is not positive raises `ValueError`.+To keep an old result, pass `1 / temperature`. The default, `1.0`, gives the same output as before.diff --git a/changelog.d/5035.fixed.md b/changelog.d/5035.fixed.mdnew file mode 100644index 000000000..6dfc2cb4c--- /dev/null+++ b/changelog.d/5035.fixed.md@@ -0,0 +1 @@+`conv_soft_argmax2d` and `conv_soft_argmax3d` now compile with `torch.compile(fullgraph=True)` when `temperature` is a tensor. Their positivity check read the tensor under compile, because `is_exporting()` is `False` inside `torch.compile` on recent torch; the check now runs only outside graph capture, as in `spatial_softmax2d`.diff --git a/kornia/geometry/subpix/dsnt.py b/kornia/geometry/subpix/dsnt.pyindex a2fe77481..77f19f195 100644--- a/kornia/geometry/subpix/dsnt.py+++ b/kornia/geometry/subpix/dsnt.py@@ -28,6 +28,7 @@ import torchimport torch.nn.functional as Ffrom kornia.core.check import KORNIA_CHECK_IS_TENSOR, KORNIA_CHECK_SHAPE+from kornia.core.utils import is_compilingfrom kornia.geometry.grid import create_meshgrid@@ -36,7 +37,21 @@ def _validate_batched_image_tensor_input(tensor: torch.Tensor) -> None:KORNIA_CHECK_SHAPE(tensor, ["B", "C", "H", "W"])-def spatial_softmax2d(input: torch.Tensor, temperature: Optional[torch.Tensor] = None) -> torch.Tensor:+def _check_positive_temperature(temperature: torch.Tensor | float) -> None:+ """Raise ``ValueError`` unless ``temperature`` is positive; ``NaN`` is rejected as well.++ A tensor is read only outside graph capture: under ``torch.compile`` or export, reading its value would be a+ data-dependent branch, so a tensor temperature is not checked there.+ """+ if isinstance(temperature, torch.Tensor):+ if is_compiling() or bool((temperature > 0).all()):+ return+ elif temperature > 0:+ return+ raise ValueError(f"Temperature should be positive float or torch.Tensor. Got: {temperature}")+++def spatial_softmax2d(input: torch.Tensor, temperature: Optional[torch.Tensor | float] = None) -> torch.Tensor:r"""Apply the Softmax function over features in each image channel.Note that this function behaves differently to :py:class:`torch.nn.Softmax2d`, which@@ -44,7 +59,8 @@ def spatial_softmax2d(input: torch.Tensor, temperature: Optional[torch.Tensor] =Args:input: the input torch.Tensor with shape :math:`(B, N, H, W)`.- temperature: factor to apply to input, adjusting the "smoothness" of the output distribution.+ temperature: softmax temperature: the input is divided by it; smaller is sharper. Must be positive.+ ``None`` means ``1.0``. A tensor temperature is not checked under ``torch.compile`` or export.Returns:a 2D probability distribution per image channel with shape :math:`(B, N, H, W)`.@@ -64,11 +80,13 @@ def spatial_softmax2d(input: torch.Tensor, temperature: Optional[torch.Tensor] =batch_size, channels, height, width = input.shapeif temperature is None:- temperature = torch.tensor(1.0)- temperature = temperature.to(device=input.device, dtype=input.dtype)+ 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, -1)- x_soft = F.softmax(x * temperature, dim=-1)+ x_soft = F.softmax(x / temperature, dim=-1)return x_soft.view(batch_size, channels, height, width)diff --git a/kornia/geometry/subpix/spatial_soft_argmax.py b/kornia/geometry/subpix/spatial_soft_argmax.pyindex 674a872f7..9ef4ffb86 100644--- a/kornia/geometry/subpix/spatial_soft_argmax.py+++ b/kornia/geometry/subpix/spatial_soft_argmax.py@@ -23,11 +23,10 @@ import torchimport torch.nn.functional as Ffrom torch import nn-from kornia.core.utils import is_exportingfrom kornia.geometry.conversions import normalize_pixel_coordinates, normalize_pixel_coordinates3dfrom kornia.geometry.grid import create_meshgrid, create_meshgrid3d-from .dsnt import spatial_expectation2d, spatial_softmax2d+from .dsnt import _check_positive_temperature, spatial_expectation2d, spatial_softmax2dfrom .nms import nms3d# Flat offsets for gathering the full 3x3x3 neighbourhood of a voxel.@@ -324,7 +323,8 @@ def conv_soft_argmax2d(kernel_size: the size of the window.stride: the stride of the window.padding: input zero padding.- temperature: factor to apply to input.+ 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.@@ -356,9 +356,7 @@ def conv_soft_argmax2d(if not len(input.shape) == 4:raise ValueError(f"Invalid input shape, we expect BxCxHxW. Got: {input.shape}")- # A tensor temperature is read here, which graph capture cannot do; skip the value check under export.- if not is_exporting() and temperature <= 0:- raise ValueError(f"Temperature should be positive float or torch.Tensor. Got: {temperature}")+ _check_positive_temperature(temperature)b, c, h, w = input.shapeky, kx = kernel_size@@ -440,7 +438,8 @@ def conv_soft_argmax3d(kernel_size: size of the window.stride: stride of the window.padding: input zero padding.- temperature: factor to apply to input.+ 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.@@ -478,9 +477,7 @@ def conv_soft_argmax3d(if not len(input.shape) == 5:raise ValueError(f"Invalid input shape, we expect BxCxDxHxW. Got: {input.shape}")- # A tensor temperature is read here, which graph capture cannot do; skip the value check under export.- if not is_exporting() and temperature <= 0:- raise ValueError(f"Temperature should be positive float or torch.Tensor. Got: {temperature}")+ _check_positive_temperature(temperature)b, c, d, h, w = input.shapekz, ky, kx = kernel_size@@ -545,13 +542,14 @@ def conv_soft_argmax3d(def spatial_soft_argmax2d(- input: torch.Tensor, temperature: Optional[torch.Tensor] = None, normalized_coordinates: bool = True+ input: torch.Tensor, temperature: Optional[torch.Tensor | float] = None, normalized_coordinates: bool = True) -> torch.Tensor:r"""Compute the Spatial Soft-Argmax 2D of a given input heatmap.Args:input: the given heatmap with shape :math:`(B, N, H, W)`.- temperature: factor to apply to input.+ temperature: softmax temperature: the input is divided by it; smaller is sharper. Must be positive.+ ``None`` means ``1.0``. 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.@@ -568,8 +566,6 @@ def spatial_soft_argmax2d(tensor([[[1.0000, 1.0000]]])"""- if temperature is None:- temperature = torch.tensor(1.0)input_soft: torch.Tensor = spatial_softmax2d(input, temperature)output: torch.Tensor = spatial_expectation2d(input_soft, normalized_coordinates)return output@@ -581,11 +577,11 @@ class SpatialSoftArgmax2d(nn.Module):See :func:`~kornia.geometry.subpix.spatial_soft_argmax2d` for details."""- def __init__(self, temperature: Optional[torch.Tensor] = None, normalized_coordinates: bool = True) -> None:+ def __init__(self, temperature: Optional[torch.Tensor | float] = None, normalized_coordinates: bool = True) -> None:super().__init__()if temperature is None:temperature = torch.tensor(1.0)- self.temperature: torch.Tensor = temperature+ self.temperature: torch.Tensor | float = temperatureself.normalized_coordinates: bool = normalized_coordinatesdef __repr__(self) -> str:diff --git a/tests/geometry/subpix/test_dsnt.py b/tests/geometry/subpix/test_dsnt.pyindex 2280b9506..f2577c353 100644--- a/tests/geometry/subpix/test_dsnt.py+++ b/tests/geometry/subpix/test_dsnt.py@@ -134,6 +134,32 @@ class TestSpatialSoftmax2d(BaseTester):self.assert_close(op(input), op_optimized(input))+ @pytest.mark.parametrize("as_tensor", [False, True])+ @pytest.mark.parametrize("temperature", [0.5, 2.0])+ def test_temperature_divides_input(self, device, dtype, temperature, as_tensor):+ # An asymmetric map, so dividing by T and multiplying by T give different distributions for T != 1.+ input = torch.tensor([[[[0.0, 1.0, 3.0], [2.0, -1.0, 0.5]]]], device=device, dtype=dtype)+ t = torch.tensor(temperature, device=device, dtype=dtype) if as_tensor else temperature++ actual = kornia.geometry.subpix.spatial_softmax2d(input, t)++ # The float64 reference is computed on CPU: MPS has no float64.+ reference = input.cpu().double().reshape(1, 1, -1)+ expected = torch.softmax(reference / temperature, dim=-1).view(1, 1, 2, 3)+ self.assert_close(actual, expected.to(device=device, dtype=dtype))+ wrong = torch.softmax(reference * temperature, dim=-1).view(1, 1, 2, 3)+ assert not torch.allclose(actual.cpu().double(), wrong, atol=1e-2)++ @pytest.mark.parametrize("temperature", [0.0, -1.0, float("nan"), "tensor", "nan_tensor"])+ def test_nonpositive_temperature_raises(self, device, dtype, temperature):+ input = torch.zeros(1, 1, 2, 3, device=device, dtype=dtype)+ if temperature == "tensor":+ temperature = torch.tensor(0.0, device=device, dtype=dtype)+ elif temperature == "nan_tensor":+ temperature = torch.tensor(float("nan"), device=device, dtype=dtype)+ with pytest.raises(ValueError, match="Temperature should be positive"):+ kornia.geometry.subpix.spatial_softmax2d(input, temperature)+class TestSpatialExpectation2d(BaseTester):@pytest.fixture(diff --git a/tests/geometry/subpix/test_spatial_softargmax.py b/tests/geometry/subpix/test_spatial_softargmax.pyindex fcebaa6a6..a3c303b32 100644--- a/tests/geometry/subpix/test_spatial_softargmax.py+++ b/tests/geometry/subpix/test_spatial_softargmax.py@@ -142,6 +142,26 @@ class TestSpatialSoftArgmax2d(BaseTester):self.assert_close(coord[1, 1, 0].item(), 1.0, atol=1e-4, rtol=1e-4) # bottom-rightself.assert_close(coord[1, 1, 1].item(), 1.0, atol=1e-4, rtol=1e-4)+ def test_temperature_divides_input(self, device, dtype):+ # An asymmetric map: a soft-argmax at T = 0.5 must equal the expectation of softmax(x / 0.5).+ sample = torch.tensor([[[[0.0, 1.0, 3.0], [2.0, -1.0, 0.5]]]], device=device, dtype=dtype)+ # The float64 reference is computed on CPU: MPS has no float64.+ probs = torch.softmax(sample.cpu().double().reshape(1, 1, -1) / 0.5, dim=-1).view(1, 1, 2, 3)+ expected = kornia.geometry.subpix.spatial_expectation2d(probs, normalized_coordinates=False)+ expected = expected.to(device=device, dtype=dtype)++ actual = kornia.geometry.subpix.spatial_soft_argmax2d(sample, 0.5, normalized_coordinates=False)+ self.assert_close(actual, expected)+ module = kornia.geometry.subpix.SpatialSoftArgmax2d(temperature=0.5, normalized_coordinates=False)+ self.assert_close(module(sample), expected)++ def test_nonpositive_temperature_raises(self, device, dtype):+ sample = torch.zeros(1, 1, 2, 3, device=device, dtype=dtype)+ with pytest.raises(ValueError, match="Temperature should be positive"):+ kornia.geometry.subpix.spatial_soft_argmax2d(sample, 0.0)+ with pytest.raises(ValueError, match="Temperature should be positive"):+ kornia.geometry.subpix.SpatialSoftArgmax2d(temperature=-1.0)(sample)+def test_gradcheck(self, device):sample = torch.rand(2, 3, 3, 2, device=device, dtype=torch.float64)self.gradcheck(kornia.geometry.subpix.spatial_soft_argmax2d, (sample))@@ -319,6 +339,26 @@ class TestConvSoftArgmax2d(BaseTester):self.assert_close(val, expected_val, atol=1e-4, rtol=1e-4)self.assert_close(coords, expected_coord, atol=1e-4, rtol=1e-4)+ def test_dynamo_tensor_temperature(self, device, dtype, torch_optimizer):+ # The positivity check reads a tensor temperature; it must not break graph capture.+ data = torch.zeros(1, 1, 5, 7, device=device, dtype=dtype)+ data[..., 2, 4] = 1.0+ temperature = torch.tensor(0.5, device=device, dtype=dtype)+ op = kornia.geometry.subpix.conv_soft_argmax2d+ op_opt = torch_optimizer(op, fullgraph=True)+ self.assert_close(op(data, temperature=temperature), op_opt(data, temperature=temperature))++ @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))]+ )+ def test_nonpositive_temperature_raises(self, device, dtype, temperature, op, shape):+ data = torch.zeros(shape, device=device, dtype=dtype)+ if temperature == "tensor":+ temperature = torch.tensor([0.5, -1.0], device=device, dtype=dtype)+ with pytest.raises(ValueError, match="Temperature should be positive"):+ getattr(kornia.geometry.subpix, op)(data, temperature=temperature)+class TestConvSoftArgmax3d(BaseTester):def test_smoke(self, device, dtype):@@ -461,6 +501,16 @@ class TestConvSoftArgmax3d(BaseTester):self.assert_close(val, expected_val, atol=1e-4, rtol=1e-4)self.assert_close(coords, expected_coord, atol=1e-4, rtol=1e-4)+ def test_dynamo_tensor_temperature(self, device, dtype, torch_optimizer):+ # The positivity check reads a tensor temperature; it must not break graph capture.+ data = torch.zeros(1, 1, 3, 5, 7, device=device, dtype=dtype)+ data[..., 1, 2, 4] = 1.0+ temperature = torch.tensor(0.5, device=device, dtype=dtype)+ op = kornia.geometry.subpix.conv_soft_argmax3d+ op_opt = torch_optimizer(op, fullgraph=True)+ for expected, actual in zip(op(data, temperature=temperature), op_opt(data, temperature=temperature)):+ self.assert_close(expected, actual)+class TestConvQuadInterp3dModule(BaseTester):def test_smoke(self, device, dtype):