Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

fix(geometry): stabilize spatial softmax at sharp temperatures in half precision (#6206)

jasnnbdaf439da2a3
diff --git a/changelog.d/6206.fixed.md b/changelog.d/6206.fixed.md
new file mode 100644
index 000000000..a6c034c82
--- /dev/null
+++ b/changelog.d/6206.fixed.md
@@ -0,0 +1 @@
+`spatial_softmax2d`, and the soft-argmax functions built on it, no longer return `NaN` in `float16` when a sharp `temperature` would push the scaled logits past the dtype range: the logits are shifted by their per-map maximum before the division.
diff --git a/kornia/geometry/subpix/dsnt.py b/kornia/geometry/subpix/dsnt.py
index 5a5d9603e..d464e51f2 100644
--- a/kornia/geometry/subpix/dsnt.py
+++ b/kornia/geometry/subpix/dsnt.py
@@ -85,7 +85,17 @@ def spatial_softmax2d(input: torch.Tensor, temperature: Optional[torch.Tensor |
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())
+
+ # 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``
+ # is reachable in float16) before softmax gets a chance to stabilize the values. The shift is a constant, so it
+ # takes no gradient; an empty map has nothing to shift and no maximum.
+ if height * width > 0:
+ x = x - x.amax(dim=-1, keepdim=True).detach()
x_soft = F.softmax(x / temperature, dim=-1)
return x_soft.view(batch_size, channels, height, width)
diff --git a/tests/geometry/subpix/test_dsnt.py b/tests/geometry/subpix/test_dsnt.py
index f8529ca62..412b81cc1 100644
--- a/tests/geometry/subpix/test_dsnt.py
+++ b/tests/geometry/subpix/test_dsnt.py
@@ -195,7 +195,7 @@ class TestSpatialSoftmax2d(BaseTester):
self.assert_close(actual, expected)
- @pytest.mark.parametrize("shape", [(0, 3, 4, 5), (2, 0, 4, 5)])
+ @pytest.mark.parametrize("shape", [(0, 3, 4, 5), (2, 0, 4, 5), (2, 3, 0, 5), (2, 3, 4, 0)])
def test_empty_batch_or_channels(self, device, dtype, shape):
input = torch.rand(shape, device=device, dtype=dtype)
actual = kornia.geometry.subpix.spatial_softmax2d(input)
@@ -234,6 +234,28 @@ class TestSpatialSoftmax2d(BaseTester):
with pytest.raises(ValueError, match="Temperature should be positive"):
kornia.geometry.subpix.spatial_softmax2d(input, temperature)
+ @pytest.mark.parametrize("map_dtype", [torch.uint8, torch.int64])
+ def test_integer_map_is_divided_in_floating_point(self, device, map_dtype):
+ # The per-map shift must not run in the map's integer dtype: in uint8, 0 - 255 wraps to 1.
+ heatmap = torch.tensor([[[[0, 255], [3, 7]]]], device=device)
+ 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)
+
+ 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.
+ heatmap = torch.zeros(1, 1, 64, 64, device=device, dtype=torch.float16)
+ heatmap[..., 32, 31] = 10.0
+ heatmap[..., 32, 32] = 11.0
+ temperature = torch.tensor(1e-4, device=device, dtype=torch.float16)
+
+ probabilities = kornia.geometry.subpix.spatial_softmax2d(heatmap, temperature)
+ assert torch.isfinite(probabilities).all(), "expected a finite distribution"
+ self.assert_close(probabilities.sum(dim=(-2, -1)), torch.ones(1, 1, device=device, dtype=heatmap.dtype))
+
+ coordinates = kornia.geometry.subpix.spatial_soft_argmax2d(heatmap, temperature, normalized_coordinates=False)
+ self.assert_close(coordinates, torch.tensor([[[32.0, 32.0]]], device=device, dtype=heatmap.dtype))
+
class TestSpatialExpectation2d(BaseTester):
@pytest.fixture(