Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

fix(geometry): normalise render_gaussian2d with a per-axis softmax instead of a +1e-8 bias (#5036)

Dmytro Mishkind406cc569579
diff --git a/changelog.d/5036.breaking.md b/changelog.d/5036.breaking.md
new file mode 100644
index 000000000..1dac932af
--- /dev/null
+++ b/changelog.d/5036.breaking.md
@@ -0,0 +1,6 @@
+`render_gaussian2d` now normalises each axis with a softmax over the Gaussian's exponents instead of dividing by the
+sum plus `1e-8`. A Gaussian inside the image now sums to 1 up to roundoff; the `1e-8` term used to leave it about
+`1e-8` short. A mean far outside the grid now renders the grid part of the Gaussian rescaled to sum to one, which
+puts its mass on the nearest border row or column, in every dtype and with finite gradients. Previously the `1e-8`
+term made such a heatmap lose its mass once the mean was about six standard deviations outside the grid, and it was
+exactly zero once every sample underflowed.
diff --git a/kornia/geometry/subpix/dsnt.py b/kornia/geometry/subpix/dsnt.py
index 77f19f195..9cb029283 100644
--- a/kornia/geometry/subpix/dsnt.py
+++ b/kornia/geometry/subpix/dsnt.py
@@ -141,6 +141,9 @@ def render_gaussian2d(
) -> torch.Tensor:
r"""Render the PDF of a 2D Gaussian distribution.
+ Each axis is normalised over the grid, so the heatmap sums to one. A mean outside the grid renders the part of
+ the Gaussian that falls on the grid, rescaled to sum to one; far outside, that mass sits on the nearest border.
+
Args:
mean: the mean location of the Gaussian to render, :math:`(\mu_x, \mu_y)`. Shape: :math:`(*, 2)`.
std: the standard deviation of the Gaussian to render, :math:`(\sigma_x, \sigma_y)`.
@@ -188,13 +191,11 @@ def render_gaussian2d(
k_x = -0.5 * torch.reciprocal(sigma_x**2)
k_y = -0.5 * torch.reciprocal(sigma_y**2)
- # Assemble the 2D Gaussian.
- gauss_x = torch.exp(dist_x_sq * k_x)
- gauss_y = torch.exp(dist_y_sq * k_y)
-
- # Rescale so that values sum to one.
- gauss_x = gauss_x / (gauss_x.sum(dim=-1, keepdim=True) + 1e-8)
- gauss_y = gauss_y / (gauss_y.sum(dim=-1, keepdim=True) + 1e-8)
+ # Assemble each axis normalised to sum to one: softmax(dists * ks) = exp(dists * ks) / sum(exp(dists * ks)).
+ # Softmax subtracts the largest exponent first, so the normaliser is at least 1: no bias term is needed, a mean
+ # far off the grid cannot underflow the sum to 0, and the gradient stays finite at any distance.
+ gauss_x = torch.softmax(dist_x_sq * k_x, dim=-1)
+ gauss_y = torch.softmax(dist_y_sq * k_y, dim=-1)
# Cast the 1-D vectors, not the (*, H, W) outer product, to avoid a full-size float32 intermediate.
return gauss_y.to(dtype).unsqueeze(-1) * gauss_x.to(dtype).unsqueeze(-2)
diff --git a/testing/half_precision_eager_rng.py b/testing/half_precision_eager_rng.py
index 3d4731ca6..4b69f73dc 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",
- 112,
+ 149,
"torch.randn",
1,
(
diff --git a/tests/geometry/subpix/test_dsnt.py b/tests/geometry/subpix/test_dsnt.py
index f2577c353..03f262eb0 100644
--- a/tests/geometry/subpix/test_dsnt.py
+++ b/tests/geometry/subpix/test_dsnt.py
@@ -56,6 +56,43 @@ class TestRenderGaussian2d(BaseTester):
self.assert_close(actual[0], gaussian, rtol=1e-5, atol=1e-5)
+ @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
+ # one up to roundoff (a +1e-8 bias in the denominators left this one 8.3e-9 short, visible only in float64).
+ size = (9, 11)
+ mean_px, std_px = [4.3, 3.7], [1.2, 0.8]
+ if normalized:
+ mean = [2 * mean_px[0] / (size[1] - 1) - 1, 2 * mean_px[1] / (size[0] - 1) - 1]
+ std = [2 * std_px[0] / (size[1] - 1), 2 * std_px[1] / (size[0] - 1)]
+ else:
+ mean, std = mean_px, std_px
+ mean_t = torch.tensor([mean], device=device, dtype=dtype)
+ std_t = torch.tensor([std], device=device, dtype=dtype)
+
+ heatmap = kornia.geometry.subpix.render_gaussian2d(mean_t, std_t, size, normalized)
+
+ total = heatmap.cpu().double().sum().item() # on CPU: MPS has no float64
+ tol = 1e-12 if dtype == torch.float64 else 4 * torch.finfo(dtype).eps
+ assert abs(total - 1.0) < tol, f"sum {total!r} is not 1 within {tol}"
+
+ @pytest.mark.parametrize("mean_x", [-14.0, -60.0])
+ def test_mean_far_off_grid_renders_on_border(self, device, dtype, mean_x):
+ # With std 1, the nearest x sample of a mean at -14 has exp(-98) = 2.7e-43, subnormal in float32; at -60,
+ # exp(-1800) is 0 in every dtype. Either way the heatmap is the grid part of the Gaussian rescaled to one:
+ # all of the x mass on column 0, and there the y profile of a mean at y = 2. The gradient stays finite.
+ mean = torch.tensor([[mean_x, 2.0]], device=device, dtype=dtype, requires_grad=True)
+ std = torch.tensor([[1.0, 1.0]], device=device, dtype=dtype, requires_grad=True)
+
+ heatmap = kornia.geometry.subpix.render_gaussian2d(mean, std, (5, 5), False)
+
+ y_profile = torch.softmax(-0.5 * (torch.arange(5, dtype=torch.float64) - 2.0) ** 2, dim=-1)
+ self.assert_close(heatmap[0, :, 0], y_profile.to(device=device, dtype=dtype))
+ self.assert_close(heatmap[..., 1:], torch.zeros_like(heatmap[..., 1:]))
+ (heatmap * torch.arange(25, device=device, dtype=dtype).view(1, 5, 5)).sum().backward()
+ assert mean.grad is not None and std.grad is not None
+ assert torch.isfinite(mean.grad).all() and torch.isfinite(std.grad).all()
+
def test_dynamo(self, device, dtype, torch_optimizer):
mean = torch.tensor([0.0, 0.0], dtype=dtype, device=device)
std = torch.tensor([0.25, 0.25], dtype=dtype, device=device)