Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

fix(geometry): compute Quaternion.polar_angle with atan2 so its gradient is zero, not nan, at the identity (#4981)

εŒΊζ’“η2ccfeb221bee
diff --git a/changelog.d/4976.added.md b/changelog.d/4976.added.md
index 2bf46dbb5..45c09c832 100644
--- a/changelog.d/4976.added.md
+++ b/changelog.d/4976.added.md
@@ -1 +1 @@
-Convention blocks for `Quaternion`, `average_quaternions` and `So3` (storage, product order, principal `log`, Jacobian sides), a "Rotations and rigid motions" section on the Conventions & Pitfalls page with the scipy / Sophus / Eigen mapping, and 19 convention and wart pins; the warts are documented and linked (#3950, #3952, #3953, #4773, #4923, #4927, #4942, #4974), not fixed.
+Convention blocks for `Quaternion`, `average_quaternions` and `So3` (storage, product order, principal `log`, Jacobian sides), a "Rotations and rigid motions" section on the Conventions & Pitfalls page with the scipy / Sophus / Eigen mapping, and 19 convention and wart pins; the warts are documented and linked (#3950, #3952, #3953, #4773, #4923, #4942, #4974), not fixed.
diff --git a/changelog.d/4981.fixed.md b/changelog.d/4981.fixed.md
new file mode 100644
index 000000000..b87faade7
--- /dev/null
+++ b/changelog.d/4981.fixed.md
@@ -0,0 +1 @@
+`Quaternion.polar_angle` is computed as `atan2(|v|, w)` instead of `acos(w / |q|)`: the same angle up to rounding (at most 2.6e-6 rad on random float32 unit quaternions; angles below `sqrt(eps)`, which used to come out as exactly 0, are now resolved), and its gradient at the identity and at every other quaternion with a zero vector part is zero instead of `nan`. (#4927)
diff --git a/kornia/geometry/quaternion.py b/kornia/geometry/quaternion.py
index b812d873b..ef509f253 100644
--- a/kornia/geometry/quaternion.py
+++ b/kornia/geometry/quaternion.py
@@ -73,9 +73,7 @@ class Quaternion(nn.Module):
(`#3953 <https://github.com/kornia/kornia/issues/3953>`_) and for most rotations at a pitch of
:math:`\pm\pi/2` (`#3950 <https://github.com/kornia/kornia/issues/3950>`_); below a norm of ``1e-12``,
``matrix()`` and ``slerp`` give wrong results, and the zero quaternion's ``matrix()`` is the identity
- (`#3952 <https://github.com/kornia/kornia/issues/3952>`_); ``polar_angle`` gives a non-finite gradient at
- the identity and near it, wherever ``w / |q|`` rounds to 1
- (`#4927 <https://github.com/kornia/kornia/issues/4927>`_); data given as a plain tensor is not
+ (`#3952 <https://github.com/kornia/kornia/issues/3952>`_); data given as a plain tensor is not
registered with ``nn.Module``, so an enclosing module's ``state_dict()``, ``load_state_dict()`` and
``.to()`` skip it, while an ``nn.Parameter`` is saved, restored and moved
(`#4923 <https://github.com/kornia/kornia/issues/4923>`_).
@@ -413,7 +411,9 @@ class Quaternion(nn.Module):
tensor(0.)
"""
- return (self.scalar / self.norm()).acos()
+ # atan2(|v|, w) is the same angle, but it keeps the digits of an angle below sqrt(eps) that acos(w / |q|)
+ # rounds to zero, and its gradient on the real axis (v = 0, the identity included) is zero instead of nan.
+ return torch.atan2(self.vec.norm(dim=-1), self.scalar)
def matrix(self) -> torch.Tensor:
"""Convert the quaternion to a rotation matrix of shape :math:`(B, 3, 3)`.
diff --git a/tests/geometry/test_quaternion.py b/tests/geometry/test_quaternion.py
index 8eec8b549..89d848edf 100644
--- a/tests/geometry/test_quaternion.py
+++ b/tests/geometry/test_quaternion.py
@@ -203,6 +203,53 @@ class TestQuaternion(BaseTester):
data = torch.tensor([[-2.0, 0.0, 0.0, 0.0]], device=device, dtype=torch.float64)
self.gradcheck(lambda x: (Quaternion(x) ** t).data, (data,))
+ def test_polar_angle(self, device, dtype):
+ # polar_angle is acos(w / |q|), half the rotation angle, in [0, pi], and the same for every positive scale of q
+ angles = torch.tensor([0.0, 0.3, 1.2, math.pi / 2, math.pi - 0.1, math.pi], dtype=torch.float64)
+ axis = torch.tensor(
+ [[0.0, 0.0, 1.0], [0.6, 0.0, 0.8], [-0.36, 0.48, 0.8], [1.0, 0.0, 0.0], [0.0, -1.0, 0.0], [0.0, 0.0, 1.0]]
+ )
+ data = torch.cat((angles.cos()[:, None], angles.sin()[:, None] * axis.double()), -1)
+ q = Quaternion(data.to(device=device, dtype=dtype))
+ expected = angles.to(device=device, dtype=dtype)
+ self.assert_close(q.polar_angle, expected)
+ self.assert_close((q * 3.0).polar_angle, expected)
+ self.assert_close(Quaternion(q.data[1]).polar_angle, expected[1])
+
+ def test_polar_angle_small_angle(self, device, dtype):
+ # below sqrt(eps) the norm of q rounds to |w|, so acos(w / |q|) returned exactly 0 for an angle that is not
+ # zero (#4927); q = (1, tan(theta) n) has polar angle theta whatever the formula
+ eps = torch.finfo(dtype).eps
+ theta = math.sqrt(eps) / 8
+ data = torch.tensor([[1.0, math.tan(theta) * 0.6, 0.0, math.tan(theta) * 0.8]], device=device, dtype=dtype)
+ expected = torch.tensor([theta], device=device, dtype=dtype)
+ # no absolute tolerance, the old result 0 is within the default one
+ self.assert_close(Quaternion(data).polar_angle, expected, rtol=8 * eps, atol=0.0)
+
+ def test_polar_angle_gradient_is_zero_on_the_real_axis(self, device, dtype):
+ # acos has an infinite derivative at 1, so the gradient of polar_angle used to be nan at the identity and at
+ # every other quaternion with a zero vector part (#4927); atan2(|v|, w) gives the zero subgradient there
+ data = torch.tensor(
+ [[1.0, 0.0, 0.0, 0.0], [-1.0, 0.0, 0.0, 0.0], [2.0, 0.0, 0.0, 0.0], [0.8, 0.0, 0.6, 0.0]],
+ device=device,
+ dtype=dtype,
+ requires_grad=True,
+ )
+ Quaternion(data).polar_angle.sum().backward()
+ self.assert_close(data.grad[:3], torch.zeros_like(data.grad[:3]), rtol=0.0, atol=0.0)
+ # d acos(w / |q|) / d(w, x, y, z) at (0.8, 0, 0.6, 0) is (-0.6, 0, 0.8, 0)
+ expected = torch.tensor([-0.6, 0.0, 0.8, 0.0], device=device, dtype=dtype)
+ self.assert_close(data.grad[3], expected)
+
+ def test_polar_angle_gradcheck(self, device):
+ # identity, negative real axis, generic, and pure imaginary (w = 0)
+ data = torch.tensor(
+ [[1.0, 0.0, 0.0, 0.0], [-2.0, 0.0, 0.0, 0.0], [1.0, 0.5, -0.3, 0.2], [0.0, 0.3, -0.4, 0.5]],
+ device=device,
+ dtype=torch.float64,
+ )
+ self.gradcheck(lambda x: Quaternion(x).polar_angle, (data,))
+
@pytest.mark.parametrize("batch_size", (None, 1, 2, 5))
def test_quaternion_scalar_multiplication(self, device, dtype, batch_size):
"""Test scalar multiplication for issue #3101."""
@@ -616,27 +663,6 @@ class TestQuaternionConventions(BaseTester):
# to_axis_angle is the principal log, so the arbitrary sign of the eigenvector does not matter
self.assert_close(out.to_axis_angle(), expected.to(device=device, dtype=dtype), rtol=0.0, atol=tol)
- def test_wart_quaternion_polar_angle_gradient_nonfinite_at_identity_4927(self, device, dtype):
- # #4927 https://github.com/kornia/kornia/issues/4927: polar_angle gives a non-finite gradient at the identity,
- # the usual initialisation, and near it. This test turns red when the gradient becomes finite at either.
- identity = torch.tensor([[1.0, 0.0, 0.0, 0.0]], device=device, dtype=dtype, requires_grad=True)
- Quaternion(identity).polar_angle.sum().backward()
- assert not bool(torch.isfinite(identity.grad).all()), identity.grad
- # a half-angle of sqrt(eps) / 2 is small enough that w / |q| rounds to 1, so a fix that guards only the exact
- # identity leaves this row non-finite
- h = 0.5 * math.sqrt(torch.finfo(dtype).eps)
- near = torch.tensor(
- [[math.cos(h), 0.6 * math.sin(h), 0.0, 0.8 * math.sin(h)]], device=device, dtype=dtype, requires_grad=True
- )
- # precondition: the vector part survives the rounding, so this is not the identity again
- assert bool((near[:, 1:] != 0).any())
- Quaternion(near).polar_angle.sum().backward()
- assert not bool(torch.isfinite(near.grad).all()), near.grad
- # control: away from the identity the same expression has a finite gradient
- q = self._unit([[0.9, 0.1, -0.3, 0.2]], device, dtype).requires_grad_(True)
- Quaternion(q).polar_angle.sum().backward()
- assert bool(torch.isfinite(q.grad).all()), q.grad
-
def test_wart_average_quaternions_weights_by_member_norm_4974(self, device, dtype):
# https://github.com/kornia/kornia/issues/4974: average_quaternions uses stored q_i q_i^T, so rescaling a
# member by 3 weights it by 9, while matrix(), to_axis_angle(), polar_angle and slerp ignore a positive scale.