Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

fix(geometry): preserve the float16 quaternion normalization guard (#4162)

fly1d072aff2ca869
diff --git a/CHANGELOG.md b/CHANGELOG.md
index dea7b2b07..6f3100a25 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -569,6 +569,12 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
trim only padding instead of dropping merged boxes or exposing old padding as
real boxes (#4168, #4175).
+* `normalize_quaternion` floors a positive `eps` at the smallest positive `float16` subnormal, so its default
+ `eps=1e-12` remains an active division guard and a zero quaternion returns finite zeros instead of NaNs without
+ changing non-zero representable `float16` magnitudes. An explicit `eps=0.0` still disables the guard. This also
+ keeps `Quaternion.normalize`, `quaternion_to_rotation_matrix`, and their downstream pose conversions finite for
+ that input, matching the existing `float32`, `float64`, and `bfloat16` behavior (#4162).
+
* `Boxes3D.to_tensor` and `Boxes3D.get_boxes_shape` are differentiable again (#1396). Both reduce a box's 8
vertices to its min/max corner with `amin`/`amax`, which is a genuine kink -- not differentiable in the
classical sense -- wherever multiple vertices exactly tie for an axis extremum. Every face of an
diff --git a/kornia/geometry/conversions.py b/kornia/geometry/conversions.py
index a147f62f9..d6ccf1405 100644
--- a/kornia/geometry/conversions.py
+++ b/kornia/geometry/conversions.py
@@ -734,11 +734,12 @@ def normalize_quaternion(quaternion: torch.Tensor, eps: float = 1.0e-12) -> torc
returns ``zeros(4)``, and with ``eps=0.0`` the zero quaternion returns
``[nan, nan, nan, nan]`` instead. ``float32`` and ``bfloat16`` behave
the same up to their rounding (``0.10000000149011612`` and
- ``0.099609375`` for the first input). In ``float16`` both ``1e-13`` and
- the default ``eps`` round to ``0``, so the clamp is a no-op and each of
- those two inputs already returns ``[nan, nan, nan, nan]`` at the
- default β€” the same underflow class as
- `#3966 <https://github.com/kornia/kornia/issues/3966>`_. Tracked in
+ ``0.099609375`` for the first input). For ``float16``, a positive
+ ``eps`` is floored at the dtype's smallest positive subnormal value, so
+ the default guard remains active and a zero quaternion also returns
+ ``zeros(4)`` without clamping non-zero representable magnitudes. An
+ explicit ``eps=0.0`` still disables that guard. The remaining
+ sub-``eps`` behavior is tracked in
`#3952 <https://github.com/kornia/kornia/issues/3952>`_.
Args:
@@ -760,7 +761,10 @@ def normalize_quaternion(quaternion: torch.Tensor, eps: float = 1.0e-12) -> torc
if not quaternion.shape[-1] == 4:
raise ValueError(f"Input must be a tensor of shape (*, 4). Got {quaternion.shape}")
- return F.normalize(quaternion, p=2.0, dim=-1, eps=eps)
+
+ # Exact smallest positive float16 subnormal, kept literal for TorchScript support.
+ safe_eps = max(eps, 5.960464477539063e-08) if quaternion.dtype == torch.float16 and eps > 0.0 else eps
+ return F.normalize(quaternion, p=2.0, dim=-1, eps=safe_eps)
# based on:
@@ -798,8 +802,9 @@ def quaternion_to_rotation_matrix(quaternion: torch.Tensor) -> torch.Tensor:
approaches the maximum possible ``2``), while the ``1e6`` end is
``nan`` outright because ``0.5 * 1e6`` overflows the dtype.
Once ``||q||`` drops below
- :func:`~kornia.geometry.conversions.normalize_quaternion`'s
- ``eps = 1e-12`` the clamp takes over and rescaling changes the matrix
+ :func:`~kornia.geometry.conversions.normalize_quaternion`'s effective
+ floor (``eps = 1e-12``, raised to the smallest positive subnormal in
+ ``float16``), the clamp takes over and rescaling changes the matrix
outright: in ``float64``, ``q * 1e-13`` and ``q`` can give matrices
that differ by order 1
- :func:`~kornia.geometry.conversions.quaternion_to_axis_angle` is
@@ -819,11 +824,9 @@ def quaternion_to_rotation_matrix(quaternion: torch.Tensor) -> torch.Tensor:
.. warning::
The zero quaternion returns the identity matrix rather than raising:
``quaternion_to_rotation_matrix(torch.zeros(4))`` is ``eye(3)`` in
- ``float64``, ``float32`` and ``bfloat16``. In ``float16`` the internal
- ``eps = 1e-12`` normalisation floor rounds to ``0``, the guard it
- provides disappears and the matrix is all-``nan`` instead β€” the same
- underflow class as
- `#3966 <https://github.com/kornia/kornia/issues/3966>`_. Tracked in
+ ``float64``, ``float32``, ``bfloat16`` and ``float16``. This silently
+ treats an input that is not a rotation as the identity rather than
+ raising. Tracked in
`#3952 <https://github.com/kornia/kornia/issues/3952>`_.
Args:
@@ -2980,12 +2983,13 @@ def ARKitQTVecs_to_ColmapQTVecs(qvec: torch.Tensor, tvec: torch.Tensor) -> tuple
of** ``||q||``: rescaling it moves the resulting pose only by the working
dtype's rounding as long as ``||q||`` stays **above**
:func:`~kornia.geometry.conversions.normalize_quaternion`'s
- ``eps = 1e-12`` and **below** the point at which the norm's
- sum-of-squares accumulator overflows. Over 64 random unit quaternions
- rescaled by factors from ``1e-3`` to ``1e5``, the output rotation and
- translation moved at the ``1e-06`` scale in ``float32`` β€” a few ulps
- of their entries, with the maximum moving from draw to draw, so this
- is an order of magnitude and not a bound. ``q`` and
+ effective floor (``eps = 1e-12``, raised to the smallest positive
+ subnormal in ``float16``) and **below** the point at which the norm's
+ sum-of-squares accumulator overflows. Over 64 random unit
+ quaternions rescaled by factors from ``1e-3`` to ``1e5``, the output
+ rotation and translation moved at the ``1e-06`` scale in ``float32``
+ β€” a few ulps of their entries, with the maximum moving from draw to
+ draw, so this is an order of magnitude and not a bound. ``q`` and
``-q`` give bitwise the same output at every scale tried, since they
are the same rotation
- **past either end the pose changes outright, silently.** Below the
@@ -3061,20 +3065,14 @@ def ARKitQTVecs_to_ColmapQTVecs(qvec: torch.Tensor, tvec: torch.Tensor) -> tuple
`#3951 <https://github.com/kornia/kornia/issues/3951>`_.
.. warning::
- The all-zero quaternion is never rejected, and what it gives back
- instead **splits by dtype**. In ``float64``, ``float32`` and
- ``bfloat16`` the internal normalisation floor absorbs it:
- ``torch.zeros(1, 4)`` with ``t = (1, 1, 1)`` returns the
- plausible-looking ``q = [0., 1., 0., 0.]``, ``t = (-1, 1, 1)`` in
- ``float32`` β€” the same answer as the identity input, at every one of
- those three dtypes β€” rather than raising. In ``float16`` the default
- ``eps = 1e-12`` underflows to ``0`` (``bfloat16``'s wider exponent
- keeps it), so the clamp is a no-op, the normalisation divides ``0`` by
- ``0``, and **both returned tensors are entirely** ``nan``. Neither
- branch is an error: validate the quaternion before calling if the input
- may be degenerate. This is the downstream reach of the sub-``eps``
- clamp in :func:`~kornia.geometry.conversions.normalize_quaternion`,
- whose own warning carries the same ``float16`` underflow. Tracked in
+ The all-zero quaternion is never rejected. At every floating dtype, the
+ internal normalisation floor absorbs it: ``torch.zeros(1, 4)`` with
+ ``t = (1, 1, 1)`` returns the plausible-looking
+ ``q = [0., 1., 0., 0.]``, ``t = (-1, 1, 1)`` in ``float32`` β€” the same
+ answer as the identity input β€” rather than raising. Validate the
+ quaternion before calling if the input may be degenerate. This is the
+ downstream reach of the sub-``eps`` clamp in
+ :func:`~kornia.geometry.conversions.normalize_quaternion`. Tracked in
`#3952 <https://github.com/kornia/kornia/issues/3952>`_.
Args:
diff --git a/tests/geometry/test_conversions.py b/tests/geometry/test_conversions.py
index a11e9479b..84f7b50a6 100644
--- a/tests/geometry/test_conversions.py
+++ b/tests/geometry/test_conversions.py
@@ -1546,6 +1546,25 @@ class TestQuaternionToRotationMatrix(BaseTester):
)
self.assert_close(out_reversed, expected.flip(0))
+ def test_convention_normalize_quaternion_zero_uses_the_default_guard_4021(self, device):
+ _skip_if_dtype_unavailable(device, torch.float16)
+ quaternion = torch.zeros(4, device=device, dtype=torch.float16)
+
+ out = kornia.geometry.conversions.normalize_quaternion(quaternion)
+
+ assert_close(out, quaternion, atol=0.0, rtol=0.0)
+
+ without_guard = kornia.geometry.conversions.normalize_quaternion(quaternion, eps=0.0)
+ assert torch.isnan(without_guard).all()
+
+ def test_convention_normalize_quaternion_preserves_float16_subnormal_4021(self, device):
+ _skip_if_dtype_unavailable(device, torch.float16)
+ quaternion = torch.tensor([5.960464477539063e-08, 0.0, 0.0, 0.0], device=device, dtype=torch.float16)
+
+ out = kornia.geometry.conversions.normalize_quaternion(quaternion)
+
+ assert_close(out, torch.tensor([1.0, 0.0, 0.0, 0.0], device=device, dtype=torch.float16))
+
@pytest.mark.xfail(
raises=AssertionError,
reason="normalize_quaternion divides by max(β€–qβ€–, eps), so below eps it returns a non-unit "
@@ -1566,11 +1585,7 @@ class TestQuaternionToRotationMatrix(BaseTester):
# so fixing #3952 makes this XPASS and forces the mark out. Companion wart:
# test_wart_normalize_quaternion_scales_by_norm_over_eps_3952.
if dtype == torch.float16:
- pytest.skip(
- "float16 cannot represent either 1e-13 or the default eps=1e-12 -- both round to 0, so the input is "
- "the zero quaternion and the output is NaN, which is a different claim (same underflow class as "
- "kornia#3966)"
- )
+ pytest.skip("float16 cannot represent the non-zero 1e-13 input used to pin the sub-eps behavior")
quaternion = torch.tensor([1e-13, 0.0, 0.0, 0.0], device=device, dtype=dtype)
@@ -1585,7 +1600,8 @@ class TestQuaternionToRotationMatrix(BaseTester):
# sub-eps outputs. Two cells here plus a third in the eps=0 control below, each
# discriminating a different fix shape:
# (1) β€–qβ€– = 1e-13 with eps = 1e-12 comes back as [0.1, 0, 0, 0] -- flips under every fix
- # (identity fallback, smaller eps, raise);
+ # (identity fallback, smaller eps, raise). float16 cannot represent this input, so
+ # that cell applies only to the other dtypes;
# (2) the exactly-zero quaternion comes back as zeros -- does NOT flip under a
# "leave the input alone when β€–qβ€– < eps" fix, which is exactly the shape that would
# leave cell (1) fixed and this one still broken.
@@ -1597,23 +1613,19 @@ class TestQuaternionToRotationMatrix(BaseTester):
# -> [0.1, 0.0, 0.0, 0.0] (float32: [0.10000000149011612, 0, 0, 0];
# bfloat16: [0.099609375, 0, 0, 0])
# normalize_quaternion(torch.zeros(4, dtype=torch.float64), eps=1e-12) -> [0, 0, 0, 0]
- if dtype == torch.float16:
- pytest.skip(
- "float16 cannot represent either 1e-13 or the default eps=1e-12 -- both round to 0, so both "
- "cells collapse to NaN (same underflow class as kornia#3966)"
- )
_skip_if_mps_clamp_caching(device)
normalize_quaternion = kornia.geometry.conversions.normalize_quaternion
- sub_eps = normalize_quaternion(torch.tensor([1e-13, 0.0, 0.0, 0.0], device=device, dtype=dtype), eps=1e-12)
zero = normalize_quaternion(torch.zeros(4, device=device, dtype=dtype), eps=1e-12)
- assert_close(
- sub_eps,
- torch.tensor([0.1, 0.0, 0.0, 0.0], device=device, dtype=dtype),
- msg=_issue_msg("kornia#3952: a sub-eps quaternion is no longer scaled by ||q|| / eps"),
- )
+ if dtype != torch.float16:
+ sub_eps = normalize_quaternion(torch.tensor([1e-13, 0.0, 0.0, 0.0], device=device, dtype=dtype), eps=1e-12)
+ assert_close(
+ sub_eps,
+ torch.tensor([0.1, 0.0, 0.0, 0.0], device=device, dtype=dtype),
+ msg=_issue_msg("kornia#3952: a sub-eps quaternion is no longer scaled by ||q|| / eps"),
+ )
assert_close(
zero,
torch.zeros(4, device=device, dtype=dtype),
@@ -1634,13 +1646,8 @@ class TestQuaternionToRotationMatrix(BaseTester):
# [nan, nan, nan, nan], mps gives [0, 0, 0, 0] for the same three calls in sequence, while
# the eps=0 call *alone* gives NaN on both). That is the torch defect already probed by
# _skip_if_mps_clamp_caching further down this file, which is what guards this pin.
- # Snippet used to generate expected (torch only, executed on cpu at float64/float32/bfloat16):
+ # Snippet used to generate expected (torch only, executed on cpu at every floating dtype):
# normalize_quaternion(torch.zeros(4, dtype=torch.float64), eps=0.0) -> [nan] * 4
- if dtype == torch.float16:
- pytest.skip(
- "float16 cannot represent the default eps=1e-12 either, so the zero quaternion is already NaN with "
- "the default and there is no eps=0 contrast to draw (same underflow class as kornia#3966)"
- )
_skip_if_mps_clamp_caching(device)
out = kornia.geometry.conversions.normalize_quaternion(torch.zeros(4, device=device, dtype=dtype), eps=0.0)
@@ -1657,15 +1664,9 @@ class TestQuaternionToRotationMatrix(BaseTester):
# quaternion_to_rotation_matrix its own guard while normalize_quaternion stays as it is.
# If it fails, one of those happened -- flip/remove the #3952 strict xfail above and check
# which. NOT a contract that the zero quaternion must map to the identity.
- # Snippet used to generate expected (torch only, executed on cpu at float64/float32/bfloat16):
+ # Snippet used to generate expected (torch only, executed on cpu at every floating dtype):
# quaternion_to_rotation_matrix(torch.zeros(4, dtype=torch.float64))
# -> [[1., 0., 0.], [0., 1., 0.], [0., 0., 1.]]
- if dtype == torch.float16:
- pytest.skip(
- "at float16 the default eps=1e-12 inside normalize_quaternion underflows to 0, so the zero "
- "quaternion yields an all-NaN matrix rather than the identity (same underflow class as kornia#3966)"
- )
-
out = kornia.geometry.conversions.quaternion_to_rotation_matrix(torch.zeros(4, device=device, dtype=dtype))
assert_close(
@@ -5680,30 +5681,23 @@ class TestCARKitToColmap(BaseTester):
self.assert_close(q_negated, q_reference)
self.assert_close(t_negated, t_reference)
- def test_wart_zero_quaternion_is_absorbed_or_nans_by_dtype_3952(self, device, dtype):
+ def test_wart_zero_quaternion_is_absorbed_3952(self, device, dtype):
# Wart pin for the downstream reach of kornia#3952 into this function, companion to its
- # zero-quaternion warning: the all-zero input is not rejected, and what it produces instead
- # SPLITS BY DTYPE, which is the half the warning got wrong before this pin existed.
- # float64/float32/bfloat16: normalize_quaternion's β€–qβ€– < eps clamp absorbs the zero, the
- # internal rotation comes back as the identity, and the call returns exactly what the
- # IDENTITY quaternion returns -- a plausible pose, silently, for an input that is not a
- # rotation at all.
- # float16: the default eps = 1e-12 underflows to 0 there (bfloat16's wider exponent keeps
- # it: 1.0018652574217413e-12), so the clamp is a no-op, the normalisation divides 0 by 0
- # and the whole pose is NaN. Same underflow class as kornia#3966.
+ # zero-quaternion warning: the all-zero input is not rejected. normalize_quaternion's
+ # β€–qβ€– < eps clamp absorbs the zero at every dtype, the internal rotation comes back as the
+ # identity, and the call returns exactly what the IDENTITY quaternion returns -- a
+ # plausible pose, silently, for an input that is not a rotation at all.
# The first two legs assert against the IDENTITY input's own output rather than against a
# literal, so the claim the docstring makes -- "the same answer as the identity input" --
# is what runs, at every dtype and on every backend, with no constant to re-measure per
# build. The third leg pins the one value the warning quotes outright, t = (-1, 1, 1),
# which is exact in every dtype here; without it the first two would still pass if BOTH
# routes moved together.
- # If the non-float16 leg fails, #3952 was (partly) fixed, or this function grew a guard --
- # check which. If the float16 leg fails, the eps reaching normalize_quaternion is no longer
- # underflowing, which is the #3966 half. NOT a contract that either is correct.
+ # If this fails, #3952 was (partly) fixed, or this function grew a guard -- check which.
+ # NOT a contract that absorbing the zero quaternion is correct.
# Snippet used to generate expected (torch only, executed on cpu):
# ARKitQTVecs_to_ColmapQTVecs(torch.zeros(1, 4), torch.ones(1, 3, 1))
# -> q [0., 1., 0., 0.], t [-1., 1., 1.] (float64 q_x: 1.0000000012499999)
- # the same call at float16 -> q [nan] * 4, t [nan] * 3
_skip_if_dtype_unavailable(device, dtype)
zeros = torch.zeros(1, 4, device=device, dtype=dtype)
identity = torch.tensor([[1.0, 0.0, 0.0, 0.0]], device=device, dtype=dtype)
@@ -5711,12 +5705,6 @@ class TestCARKitToColmap(BaseTester):
q_zero, t_zero = ARKitQTVecs_to_ColmapQTVecs(zeros, tvec)
- if dtype == torch.float16:
- assert torch.isnan(q_zero).all() and torch.isnan(t_zero).all(), _issue_msg(
- "kornia#3952/#3966: the float16 zero quaternion no longer underflows to an all-NaN pose"
- )
- return
-
q_identity, t_identity = ARKitQTVecs_to_ColmapQTVecs(identity, tvec)
assert_close(