Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

fix: keep NaN in _l2_normalize instead of zeroing the vector (#5409)

Anshuman Nayan442c6b0e8138
diff --git a/changelog.d/5409.fixed.md b/changelog.d/5409.fixed.md
new file mode 100644
index 000000000..ffb0ecf01
--- /dev/null
+++ b/changelog.d/5409.fixed.md
@@ -0,0 +1,4 @@
+`kornia.core.utils._l2_normalize`, the L2 normalisation behind the feature descriptors, no longer
+turns a vector holding a NaN into an all-zero vector. Only a vector whose largest magnitude is
+exactly zero takes the zero branch; a NaN now propagates as it does from
+`torch.nn.functional.normalize`.
diff --git a/kornia/core/utils.py b/kornia/core/utils.py
index 8adce0563..aec398a77 100644
--- a/kornia/core/utils.py
+++ b/kornia/core/utils.py
@@ -157,12 +157,14 @@ def _l2_normalize(input: torch.Tensor, dim: int = 1) -> torch.Tensor:
the normalised tensor, in ``input``'s dtype. An all-zero vector normalises to zero with a
zero gradient: a zero vector has no direction, and the gradient of the ``eps`` clamp there,
``1 / eps``, is ~1e12 in float32 and overflows to ``inf`` once cast back to float16. A
- non-zero vector keeps ``normalize``'s value and gradient.
+ non-zero vector, including one that holds a NaN, keeps ``normalize``'s value and gradient.
"""
x = input.float() if input.dtype == torch.float16 else input
# `amax` rather than a squared norm, so a tiny non-zero vector cannot underflow into the zero branch.
- nonzero = x.abs().amax(dim=dim, keepdim=True) > 0
- out = torch.where(nonzero, F.normalize(x, dim=dim, eps=1e-12), torch.zeros_like(x))
+ # `== 0` rather than `> 0`: `amax` propagates NaN and `NaN > 0` is False, which sent a vector holding
+ # a NaN down the zero branch and hid the NaN that `normalize` returns.
+ zero = x.abs().amax(dim=dim, keepdim=True) == 0
+ out = torch.where(zero, torch.zeros_like(x), F.normalize(x, dim=dim, eps=1e-12))
return out.to(input.dtype)
diff --git a/tests/feature/test_siftdesc.py b/tests/feature/test_siftdesc.py
index 9056354e8..f5968729a 100644
--- a/tests/feature/test_siftdesc.py
+++ b/tests/feature/test_siftdesc.py
@@ -242,6 +242,17 @@ class TestSIFTConstantPatchIsFinite(BaseTester):
torch.nn.functional.normalize(y_ref.float(), dim=1, eps=1e-12).to(desc_dtype).sum().backward()
self.assert_close(y.grad, y_ref.grad)
+ def test_l2_normalize_propagates_nan(self, device):
+ from kornia.core.utils import _l2_normalize
+
+ nan, inf = float("nan"), float("inf")
+ # [-3, 0]: a non-zero vector whose largest entry is 0, so the zero test must run on magnitudes
+ x = torch.tensor([[nan, 1.0], [inf, 0.0], [0.0, 0.0], [3.0, 4.0], [-3.0, 0.0]], device=device)
+ out = _l2_normalize(x, dim=1)
+ # a vector holding a NaN is not a zero vector: it keeps `F.normalize`'s NaN instead of becoming zeros
+ assert bool(torch.isnan(out[0]).all()), out[0]
+ torch.testing.assert_close(out[1:], torch.nn.functional.normalize(x[1:], dim=1), equal_nan=True)
+
@pytest.mark.parametrize("desc_dtype", [torch.float16, torch.bfloat16, torch.float32])
def test_dense_sift(self, device, desc_dtype):
if not supports_replicate_padding(device, desc_dtype):