Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

fix(geometry): keep narrow float16 Gaussian heatmaps finite (#5948)

Devulapalli Naga Sri Vaishnavi5ab8c5de4d9f
diff --git a/changelog.d/5948.fixed.md b/changelog.d/5948.fixed.md
new file mode 100644
index 000000000..29019d421
--- /dev/null
+++ b/changelog.d/5948.fixed.md
@@ -0,0 +1 @@
+`render_gaussian2d` evaluates float16 `mean` and `std` in float32 and returns the heatmap in float16. A narrow float16 Gaussian, such as a one-pixel `std` in normalized coordinates on a grid more than about 550 pixels wide, used to return a NaN heatmap and NaN gradients.
diff --git a/kornia/geometry/subpix/dsnt.py b/kornia/geometry/subpix/dsnt.py
index 4aaf0c022..5a5d9603e 100644
--- a/kornia/geometry/subpix/dsnt.py
+++ b/kornia/geometry/subpix/dsnt.py
@@ -151,6 +151,7 @@ def render_gaussian2d(
Convention:
- ``mean`` and ``std`` follow :ref:`Coordinates and sizes <coordinate-conventions>`; ``size`` is
``(height, width)``. The default normalized coordinates are corner-aligned.
+ - Float16 parameters are evaluated in float32; the heatmap retains the input dtype.
Args:
mean: the mean location of the Gaussian to render, :math:`(\mu_x, \mu_y)`. Shape: :math:`(*, 2)`.
@@ -182,6 +183,11 @@ def render_gaussian2d(
xs = torch.linspace(0, width - 1, width, device=device, dtype=compute_dtype)
ys = torch.linspace(0, height - 1, height, device=device, dtype=compute_dtype)
+ # Promote before squaring and reciprocating std: a narrow float16 Gaussian otherwise
+ # overflows its inverse variance (or underflows std**2) and produces NaNs at its centre.
+ if dtype == torch.float16:
+ mean = mean.to(compute_dtype)
+ std = std.to(compute_dtype)
mu_x = mean[..., 0].unsqueeze(-1)
mu_y = mean[..., 1].unsqueeze(-1)
sigma_x = std[..., 0].unsqueeze(-1)
diff --git a/testing/half_precision_eager_rng.py b/testing/half_precision_eager_rng.py
index 85158d284..ae7986c1d 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",
- 151,
+ 179,
"torch.randn",
1,
(
diff --git a/tests/geometry/subpix/test_dsnt.py b/tests/geometry/subpix/test_dsnt.py
index c56869009..f8529ca62 100644
--- a/tests/geometry/subpix/test_dsnt.py
+++ b/tests/geometry/subpix/test_dsnt.py
@@ -24,6 +24,33 @@ from testing.base import BaseTester
class TestRenderGaussian2d(BaseTester):
+ @pytest.mark.parametrize("normalized", [False, True])
+ @pytest.mark.parametrize("sigma", [1e-3, 1e-4])
+ @pytest.mark.parametrize("axis", [0, 1])
+ def test_narrow_gaussian(self, device, dtype, normalized, sigma, axis):
+ center = 0.0 if normalized else 2.0
+ mean = torch.tensor([[center, center]], device=device, dtype=dtype, requires_grad=True)
+ std_xy = [0.25, 0.25]
+ std_xy[axis] = sigma
+ std = torch.tensor([std_xy], device=device, dtype=dtype, requires_grad=True)
+
+ actual = kornia.geometry.subpix.render_gaussian2d(mean, std, (5, 5), normalized)
+ # Direct Gaussian PDF on CPU in float64, using the same representable parameters.
+ coords = torch.linspace(-1.0, 1.0, 5, dtype=torch.float64) if normalized else torch.arange(5).double()
+ vectors = torch.exp(-0.5 * ((coords[:, None] - center) / std.detach().cpu().double()) ** 2)
+ expected = vectors[:, 1, None] * vectors[:, 0]
+ expected = (expected / expected.sum()).unsqueeze(0).to(device=device, dtype=dtype)
+
+ assert actual.dtype == dtype
+ assert torch.isfinite(actual).all()
+ self.assert_close(actual, expected)
+ self.assert_close(actual.sum(), actual.new_tensor(1.0))
+ (actual * torch.arange(25, device=device, dtype=dtype).view(1, 5, 5)).sum().backward()
+ assert mean.grad is not None
+ assert std.grad is not None
+ assert torch.isfinite(mean.grad).all()
+ assert torch.isfinite(std.grad).all()
+
@pytest.fixture
def gaussian(self, device, dtype):
# For a standard gaussian on 5 points [-1, -0.5, 0, 0.5, 1] with std=0.25
@@ -95,9 +122,10 @@ class TestRenderGaussian2d(BaseTester):
assert torch.isfinite(mean.grad).all()
assert torch.isfinite(std.grad).all()
- def test_dynamo(self, device, dtype, torch_optimizer):
+ @pytest.mark.parametrize("sigma", [0.25, 1e-3])
+ def test_dynamo(self, device, dtype, torch_optimizer, sigma):
mean = torch.tensor([0.0, 0.0], dtype=dtype, device=device)
- std = torch.tensor([0.25, 0.25], dtype=dtype, device=device)
+ std = torch.tensor([sigma, sigma], dtype=dtype, device=device)
op = kornia.geometry.subpix.render_gaussian2d
op_optimized = torch_optimizer(op)