π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
fix(geometry): normalize a float16 zero vector to zero, not NaN, in Vector3.normalized, Vector2.normalized and ParametrizedLine.through (#5084)
εΊζ’η8c4d22013cfa
diff --git a/changelog.d/5084.fixed.md b/changelog.d/5084.fixed.mdnew file mode 100644index 000000000..899510fc1--- /dev/null+++ b/changelog.d/5084.fixed.md@@ -0,0 +1,4 @@+`Vector3.normalized` and `Vector2.normalized` return a zero vector, not NaN, for a float16 zero input, and its+gradient is zero instead of inf; `ParametrizedLine.through` does the same for coincident points when value checks are+disabled. They now share `normalize_quaternion`'s arithmetic, and a non-zero input keeps its `F.normalize` value bit+for bit (#5062).diff --git a/kornia/geometry/conversions.py b/kornia/geometry/conversions.pyindex 7179f4bd9..49da88c75 100644--- a/kornia/geometry/conversions.py+++ b/kornia/geometry/conversions.py@@ -735,22 +735,35 @@ def normalize_quaternion(quaternion: torch.Tensor, eps: float = 1.0e-12) -> torcif not quaternion.shape[-1] == 4:raise ValueError(f"Input must be a tensor of shape (*, 4). Got {quaternion.shape}")- safe_eps: float = max(eps, 5.960464477539063e-08) if quaternion.dtype == torch.float16 and eps > 0.0 else eps- norm = torch.linalg.vector_norm(quaternion, ord=2, dim=-1, keepdim=True)+ return _normalize_last_dim(quaternion, eps)+++def _normalize_last_dim(x: torch.Tensor, eps: float) -> torch.Tensor:+ """Divide ``x`` by the L2 norm of its last axis, floored at ``eps``.++ The arithmetic of :func:`normalize_quaternion`, shared with :meth:`kornia.geometry.vector.Vector3.normalized`,+ :meth:`kornia.geometry.vector.Vector2.normalized` and :meth:`kornia.geometry.line.ParametrizedLine.through`.+ Its values match ``torch.nn.functional.normalize(x, p=2, dim=-1, eps=eps)`` wherever the norm is nonzero. Their+ default ``eps=1e-12`` rounds to ``0`` in float16, where ``normalize`` turns a zero vector into ``0 / 0 = NaN``+ (#4021, #5062); here a row whose norm is exactly zero takes a separate arm (``x / eps``, or a constant zero where+ float16 cannot hold ``1 / eps``), so with a positive ``eps`` the zero vector stays zero in every dtype.+ """+ safe_eps: float = max(eps, 5.960464477539063e-08) if x.dtype == torch.float16 and eps > 0.0 else eps+ norm = torch.linalg.vector_norm(x, ord=2, dim=-1, keepdim=True)# Only an exactly-zero norm takes the constant arms below; a NaN norm compares unequal to zero and goes# through the division, so NaN in gives NaN out. The eps floor is a value floor selected by torch.where,# so its derivative does not depend on the torch version the way clamp's derivative at the bound does.mask = norm != 0.0safe_norm = torch.where(mask, norm, torch.ones_like(norm))denom = torch.where(safe_norm < safe_eps, torch.full_like(safe_norm, safe_eps), safe_norm)- out = quaternion / denom+ out = x / denomif eps == 0.0:- return torch.where(mask, out, torch.full_like(quaternion, float("nan")))- if quaternion.dtype == torch.float16 and safe_eps * 65504.0 < 1.0:- # The exact derivative of q / eps at q = 0 is I / eps, which overflows float16 (#4623); use a zero gradient.- return torch.where(mask, out, torch.zeros_like(quaternion))- # Below eps the function is q / eps, so the zero quaternion keeps its exact derivative I / eps.- return torch.where(mask, out, quaternion / torch.full_like(quaternion, safe_eps))+ return torch.where(mask, out, torch.full_like(x, float("nan")))+ if x.dtype == torch.float16 and safe_eps * 65504.0 < 1.0:+ # The exact derivative of x / eps at x = 0 is I / eps, which overflows float16 (#4623); use a zero gradient.+ return torch.where(mask, out, torch.zeros_like(x))+ # Below eps the function is x / eps, so the zero vector keeps its exact derivative I / eps.+ return torch.where(mask, out, x / torch.full_like(x, safe_eps))# based on:diff --git a/kornia/geometry/line.py b/kornia/geometry/line.pyindex 215022385..dd8307a75 100644--- a/kornia/geometry/line.py+++ b/kornia/geometry/line.py@@ -20,12 +20,12 @@from typing import Iterator, Optional, Tuple, Unionimport torch-import torch.nn.functional as Ffrom torch import nnfrom kornia.core.check import KORNIA_CHECK, KORNIA_CHECK_IS_TENSOR, KORNIA_CHECK_SHAPE, are_checks_enabledfrom kornia.core.exceptions import ValueCheckErrorfrom kornia.core.utils import _torch_svd_cast, is_compiling, register_module_state+from kornia.geometry.conversions import _normalize_last_dimfrom kornia.geometry.linalg import batched_dot_productfrom kornia.geometry.plane import Hyperplanefrom kornia.geometry.vector import Scalar@@ -108,7 +108,7 @@ class ParametrizedLine(nn.Module):if not torch.jit.is_scripting() and are_checks_enabled() and not is_compiling():if not bool((direction.abs().amax(dim=-1) > 0).all()):raise ValueCheckError("ParametrizedLine.through requires two distinct points; p0 and p1 coincide.")- return ParametrizedLine(p0, F.normalize(direction, p=2, dim=-1))+ return ParametrizedLine(p0, _normalize_last_dim(direction, 1e-12))def point_at(self, t: Union[float, torch.Tensor, Scalar]) -> torch.Tensor:"""Get the point at :math:`t` along this line.diff --git a/kornia/geometry/vector.py b/kornia/geometry/vector.pyindex 0deb9f1f6..cc5ca85f0 100644--- a/kornia/geometry/vector.py+++ b/kornia/geometry/vector.py@@ -18,10 +18,10 @@from typing import Optional, Tuple, Union, castimport torch-import torch.nn.functional as Ffrom kornia.core.check import KORNIA_CHECKfrom kornia.core.tensor_wrapper import TensorWrapper, _wrap # type: ignore[attr-defined]+from kornia.geometry.conversions import _normalize_last_dimfrom kornia.geometry.linalg import batched_dot_product, batched_squared_norm__all__ = ["Scalar", "Vector2", "Vector3"]@@ -71,7 +71,7 @@ class Vector3(TensorWrapper):The last dimension is normalized with the L2 norm, so each``(x, y, z)`` vector has length one when the input norm is nonzero."""- return Vector3(F.normalize(self.data, p=2, dim=-1))+ return Vector3(_normalize_last_dim(self.data, 1e-12))def dot(self, right: "Vector3") -> Scalar:"""Compute dot products with another 3D vector wrapper.@@ -204,7 +204,7 @@ class Vector2(TensorWrapper):The last dimension is normalized so each ``(x, y)`` vector haslength one when the input norm is nonzero."""- return Vector2(F.normalize(self.data, p=2, dim=-1))+ return Vector2(_normalize_last_dim(self.data, 1e-12))def dot(self, right: "Vector2") -> Scalar:"""Compute dot products with another 2D vector wrapper.diff --git a/tests/geometry/test_line.py b/tests/geometry/test_line.pyindex 3a36455aa..d12b5003d 100644--- a/tests/geometry/test_line.py+++ b/tests/geometry/test_line.py@@ -44,6 +44,36 @@ class TestParametrizedLine(BaseTester):self.assert_close(l1.origin, p0)self.assert_close(l1.direction, direction_expected)+ def test_through_coincident_points_direction_is_zero_5062(self, device, dtype):+ # #5062: through(p, p) normalizes the zero vector p1 - p0, which gave a NaN direction in float16 and zeros in+ # every other dtype. Coincident points are degenerate input that a value check may reject (#5041), so this+ # pins the arithmetic with the checks disabled: zeros in every dtype.+ p = torch.tensor([1.0, 2.0], device=device, dtype=dtype)+ p1 = p.clone().requires_grad_(True)+ checks_were_enabled = are_checks_enabled()+ disable_checks()+ try:+ line = ParametrizedLine.through(p, p1)+ finally:+ if checks_were_enabled:+ enable_checks()+ assert line.direction.dtype == dtype+ assert torch.equal(line.direction, torch.zeros(2, device=device, dtype=dtype))+ # The gradient at the zero direction is I / eps with eps = 1e-12, as with F.normalize, except in float16,+ # where I / eps overflows and the gradient is zero instead of inf.+ line.direction.sum().backward()+ expected = torch.zeros_like(p) if dtype == torch.float16 else torch.full_like(p, 1e12)+ self.assert_close(p1.grad, expected)++ def test_through_short_direction_is_unit(self, device, dtype):+ # A direction of norm 5 * 2**-20 (about 4.8e-6, exact float16 subnormals) is normalized as by+ # F.normalize(p=2, dim=-1): the 1e-12 norm floor stays below it.+ p0 = torch.zeros(2, device=device, dtype=dtype)+ p1 = torch.tensor([3.0 * 2**-20, -4.0 * 2**-20], device=device, dtype=dtype)+ line = ParametrizedLine.through(p0, p1)+ assert torch.equal(line.direction, torch.nn.functional.normalize(p1, p=2, dim=-1))+ self.assert_close(line.direction, torch.tensor([0.6, -0.8], device=device, dtype=dtype))+def test_point_at(self, device, dtype):p0 = torch.tensor([0.0, 0.0], device=device, dtype=dtype)p1 = torch.tensor([1.0, 0.0], device=device, dtype=dtype)diff --git a/tests/geometry/test_vector.py b/tests/geometry/test_vector.pyindex 79c3f615d..cd78ac1aa 100644--- a/tests/geometry/test_vector.py+++ b/tests/geometry/test_vector.py@@ -78,6 +78,43 @@ class TestVector3(BaseTester):res: Scalar = p0.squared_norm()assert res.shape == () if shape is None else shape+ def test_normalized(self, device, dtype):+ # A zero row normalizes to zero in every dtype (#5062: in float16 it used to be 0 / 0 = NaN, because+ # F.normalize's eps=1e-12 floor rounds to 0 there), next to an ordinary row.+ vec = Vector3(torch.tensor([[0.0, 3.0, -4.0], [0.0, 0.0, 0.0]], device=device, dtype=dtype))+ out = vec.normalized()+ assert isinstance(out, Vector3)+ assert out.data.dtype == dtype+ self.assert_close(out.data[0], torch.tensor([0.0, 0.6, -0.8], device=device, dtype=dtype))+ assert torch.equal(out.data[1], torch.zeros(3, device=device, dtype=dtype))++ def test_normalized_matches_functional_normalize(self, device, dtype):+ # Away from the zero vector the values are those of F.normalize(p=2, dim=-1), bit for bit, at every scale.+ # The row of norm 3e-6 (float16 subnormals) is a unit vector only while the norm floor stays below it.+ vec = Vector3(+ torch.tensor(+ [+ [3.0, 0.0, 4.0],+ [1e-3, -2e-3, 2e-3],+ [100.0, 100.0, -100.0],+ [0.5, 0.25, 0.125],+ [1e-6, -2e-6, 2e-6],+ ],+ device=device,+ dtype=dtype,+ )+ )+ assert torch.equal(vec.normalized().data, torch.nn.functional.normalize(vec.data, p=2, dim=-1))++ def test_normalized_zero_vector_gradient_is_finite_5062(self, device, dtype):+ # The gradient at the zero vector is I / eps with eps = 1e-12, as with F.normalize, except in float16, where+ # I / eps overflows and the gradient is zero instead of inf.+ zero = torch.zeros(2, 3, device=device, dtype=dtype, requires_grad=True)+ Vector3(zero).normalized().data.sum().backward()+ assert torch.isfinite(zero.grad).all()+ expected = torch.zeros_like(zero) if dtype == torch.float16 else torch.full_like(zero, 1e12)+ self.assert_close(zero.grad, expected)+@pytest.mark.skip(reason="not implemented yet")def test_jit(self, device, dtype):pass@@ -146,6 +183,29 @@ class TestVector2(BaseTester):res: Scalar = p0.squared_norm()assert res.shape == () if shape is None else shape+ def test_normalized(self, device, dtype):+ # A zero row normalizes to zero in every dtype (#5062: NaN in float16 before), next to an ordinary row.+ vec = Vector2(torch.tensor([[-3.0, 4.0], [0.0, 0.0]], device=device, dtype=dtype))+ out = vec.normalized()+ assert isinstance(out, Vector2)+ assert out.data.dtype == dtype+ self.assert_close(out.data[0], torch.tensor([-0.6, 0.8], device=device, dtype=dtype))+ assert torch.equal(out.data[1], torch.zeros(2, device=device, dtype=dtype))++ def test_normalized_matches_functional_normalize(self, device, dtype):+ # As for Vector3: the values of F.normalize(p=2, dim=-1) away from the zero vector, the 5e-6 row included.+ vec = Vector2(+ torch.tensor([[-3.0, 4.0], [1e-3, 2e-3], [100.0, -100.0], [3e-6, -4e-6]], device=device, dtype=dtype)+ )+ assert torch.equal(vec.normalized().data, torch.nn.functional.normalize(vec.data, p=2, dim=-1))++ def test_normalized_zero_vector_gradient_is_finite_5062(self, device, dtype):+ zero = torch.zeros(2, 2, device=device, dtype=dtype, requires_grad=True)+ Vector2(zero).normalized().data.sum().backward()+ assert torch.isfinite(zero.grad).all()+ expected = torch.zeros_like(zero) if dtype == torch.float16 else torch.full_like(zero, 1e12)+ self.assert_close(zero.grad, expected)+@pytest.mark.skip(reason="not implemented yet")def test_jit(self, device, dtype):pass