Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

fix(geometry): rotate by the direction of a non-unit So3 quaternion (#5452)

Dipak Chaudharic99260f2862d
diff --git a/changelog.d/5452.fixed.md b/changelog.d/5452.fixed.md
new file mode 100644
index 000000000..34c6d0149
--- /dev/null
+++ b/changelog.d/5452.fixed.md
@@ -0,0 +1 @@
+`So3.matrix()`, `So3.adjoint()` and `So3 * p` now use the rotation of `q / |q|` for a non-unit quaternion, as `Quaternion.matrix()` does, instead of returning a scaled matrix that is not a rotation and scaling points by `|q|^2`. `Se3` and `NamedPose` inherit the fix. The quaternion is still stored as given, so an `nn.Parameter` stays registered; gradients with respect to it now pass through the normalisation.
diff --git a/docs/source/get-started/conventions.rst b/docs/source/get-started/conventions.rst
index ac12d800a..15a34283c 100644
--- a/docs/source/get-started/conventions.rst
+++ b/docs/source/get-started/conventions.rst
@@ -129,8 +129,8 @@ Rotations and rigid motions
:class:`~kornia.geometry.liegroup.Se3`, :class:`~kornia.geometry.liegroup.So2` and
:class:`~kornia.geometry.liegroup.Se2` compose the same way and act on a point as ``R p + t``, with ``R`` the
``matrix()`` of the rotation part. ``So2`` and ``Se2`` do so for any complex number, and a non-unit one also scales by
-its modulus; ``So3`` and ``Se3`` need a unit quaternion
-(`#4942 <https://github.com/kornia/kornia/issues/4942>`_). The tangent vectors of ``Se3`` and ``Se2`` put the
+its modulus; ``So3`` and ``Se3`` rotate by the direction :math:`q / |q|` of a non-unit quaternion, without scaling,
+like ``Quaternion.matrix()``. The tangent vectors of ``Se3`` and ``Se2`` put the
rotation part, in radians, last: ``[υ, ω]`` and ``[vx, vy, θ]``. ``log`` is principal: its rotation angle is at most
:math:`\pi` in magnitude. The Jacobians of ``So3`` satisfy
:math:`\exp(\omega + \delta) \approx \exp(\omega) \exp(J_r \delta) = \exp(J_l \delta) \exp(\omega)`. A transform
diff --git a/kornia/geometry/liegroup/se3.py b/kornia/geometry/liegroup/se3.py
index 14b024c64..96676e1b4 100644
--- a/kornia/geometry/liegroup/se3.py
+++ b/kornia/geometry/liegroup/se3.py
@@ -45,12 +45,11 @@ class Se3(nn.Module):
(:ref:`Rotations and rigid motions <rotation-conventions>` maps it onto Sophus and GTSAM): ``exp`` rotates by
``So3.exp(omega)`` and translates by :math:`V(\omega) \upsilon`, ``hat`` is
:math:`[[\hat\omega, \upsilon], [0, 0]]`, and ``log`` is principal, with :math:`|\omega| \le \pi`.
- - ``matrix()`` is the 4x4 :math:`[[R, t], [0, 1]]`. When both rotations are unit, ``a * b`` is
- ``a.matrix() @ b.matrix()``, so ``b`` acts first, and ``g * p`` is :math:`R p + t`. ``adjoint()`` is
- :math:`[[R, \hat t R], [0, R]]`.
+ - ``matrix()`` is the 4x4 :math:`[[R, t], [0, 1]]`. ``a * b`` is ``a.matrix() @ b.matrix()``, so ``b`` acts
+ first, and ``g * p`` is :math:`R p + t`. ``adjoint()`` is :math:`[[R, \hat t R], [0, R]]`.
- The rotation is an :class:`~kornia.geometry.liegroup.So3`, whose storage and point-shape conventions
- apply, including its non-unit quaternion defect (`#4942 <https://github.com/kornia/kornia/issues/4942>`_).
- ``from_matrix`` ignores the bottom row.
+ apply: a non-unit quaternion stands for the rotation of its direction. ``from_matrix`` ignores the bottom
+ row.
- ``t`` is always a tensor registered as module state, whichever constructor built the pose; a ``Vector3``
passed to the constructor is unwrapped. ``g * p`` returns a ``Vector3`` only when ``p`` is one.
- ``state_dict()``, ``load_state_dict()`` and module device/dtype conversions include both the rotation
@@ -74,8 +73,8 @@ class Se3(nn.Module):
Internally represented by an So3 rotation and a translation 3-vector.
Args:
- rotation: So3 group encompassing a rotation, or a Quaternion to wrap in one; it is not normalised
- (`#4942 <https://github.com/kornia/kornia/issues/4942>`_).
+ rotation: So3 group encompassing a rotation, or a Quaternion to wrap in one; it is stored as given, and
+ a non-unit quaternion stands for the rotation of its direction.
translation: translation torch.Tensor with the shape of :math:`(B, 3)`, or a Vector3 wrapping one; the
tensor is what gets stored.
@@ -364,7 +363,7 @@ class Se3(nn.Module):
Args:
qxyz: torch.Tensor of shape :math:`(B, 7)` laid out as ``[qw, qx, qy, qz, x, y, z]``, scalar first; the
- quaternion is not normalised (`#4942 <https://github.com/kornia/kornia/issues/4942>`_).
+ quaternion is stored as given, and a non-unit one stands for the rotation of its direction.
Example:
>>> qxyz = torch.tensor([0., 0., 0., 1., 0., 0., 1.])
diff --git a/kornia/geometry/liegroup/so3.py b/kornia/geometry/liegroup/so3.py
index 7b9b6cc0f..57c090b44 100644
--- a/kornia/geometry/liegroup/so3.py
+++ b/kornia/geometry/liegroup/so3.py
@@ -86,10 +86,13 @@ class So3(nn.Module):
``q.to_axis_angle()``: it reads only the direction of ``q``, within the range limits stated on
:class:`~kornia.geometry.quaternion.Quaternion`, and returns the principal vector, of norm at most
:math:`\pi`, the same for ``q`` and ``-q`` below a half turn.
- - For a unit quaternion, ``a * b`` composes like ``a.matrix() @ b.matrix()``, so ``b`` acts first; ``s * p``
- rotates points ``p`` of shape :math:`(B, 3)`, a tensor or a ``Vector3``, as :math:`R p`; and ``adjoint()``
- is :math:`R` itself.
+ - ``a * b`` composes like ``a.matrix() @ b.matrix()``, so ``b`` acts first; ``s * p`` rotates points ``p`` of
+ shape :math:`(B, 3)`, a tensor or a ``Vector3``, as :math:`R p`; and ``adjoint()`` is :math:`R` itself.
:ref:`Rotations and rigid motions <rotation-conventions>` compares these with scipy, Sophus and Eigen.
+ - A non-unit quaternion stands for the rotation of its direction :math:`q / |q|`, as for
+ :meth:`~kornia.geometry.quaternion.Quaternion.matrix`: ``matrix()`` and ``s * p`` normalise it where they
+ use it, so ``matrix()`` is always a rotation and ``s * p`` keeps the norm of ``p``. ``q`` returns the
+ quaternion as stored, which keeps an ``nn.Parameter`` registered and following optimiser steps.
- For a small :math:`\delta`,
:math:`\exp(\omega + \delta) \approx \exp(\omega) \exp(J_r \delta) = \exp(J_l \delta) \exp(\omega)`,
with :math:`J_r` = ``right_jacobian(omega)`` and :math:`J_l` = ``left_jacobian(omega)`` =
@@ -100,9 +103,6 @@ class So3(nn.Module):
- The quaternion is registered as module state following
:class:`~kornia.geometry.quaternion.Quaternion`'s buffer/parameter convention, including rotations
produced by ``exp``, ``identity``, ``random``, ``from_matrix`` and group operations.
- - Known defect: the quaternion is stored as given, so with a non-unit ``q`` the ``matrix()`` is not a
- rotation and ``s * p`` scales ``p`` by :math:`|q|^2`
- (`#4942 <https://github.com/kornia/kornia/issues/4942>`_).
Example:
>>> q = Quaternion.identity()
@@ -154,7 +154,9 @@ class So3(nn.Module):
KORNIA_CHECK_SHAPE(_right_data, ["*", "3"])
w = torch.zeros(*right.shape[:-1], 1, device=right.device, dtype=right.dtype)
quat = Quaternion(torch.cat((w, _right_data), -1))
- out = (self.q * quat * self.q.conj()).vec
+ # q p q* scales p by |q|^2, so rotate by the unit direction of q
+ q = self.q.normalize()
+ out = (q * quat * q.conj()).vec
return Vector3(out) if isinstance(right, Vector3) else out
raise TypeError(f"Not So3 or torch.Tensor type. Got: {type(right)}")
@@ -291,8 +293,11 @@ class So3(nn.Module):
[0., 0., 1.]])
"""
- w = self.q.w[..., None]
- x, y, z = self.q.x[..., None], self.q.y[..., None], self.q.z[..., None]
+ # The formula below holds for a unit quaternion only. Normalising here rather than in the constructor keeps
+ # the stored quaternion, possibly an nn.Parameter, as the module state.
+ q = self.q.normalize()
+ w = q.w[..., None]
+ x, y, z = q.x[..., None], q.y[..., None], q.z[..., None]
q0 = 1 - 2 * y**2 - 2 * z**2
q1 = 2 * x * y - 2 * z * w
q2 = 2 * x * z + 2 * y * w
diff --git a/kornia/geometry/pose.py b/kornia/geometry/pose.py
index b11ee096b..e0157715b 100644
--- a/kornia/geometry/pose.py
+++ b/kornia/geometry/pose.py
@@ -51,9 +51,7 @@ class NamedPose:
- ``NamedPose(pose, frame_src="a", frame_dst="b")`` is ``b_from_a``: :meth:`transform_points` maps points in
frame ``a`` to frame ``b``, so ``NamedPose(pose, frame_src="1", frame_dst="0")`` is ``trans_01`` in the
notation of :func:`~kornia.geometry.linalg.relative_transformation`, for an ``Se2`` and an ``Se3`` pose alike.
- - ``c_from_b * b_from_a`` is ``c_from_a``. For valid rigid poses, its matrix is
- ``c_from_b.pose.matrix() @ b_from_a.pose.matrix()``; an ``Se3`` pose with a non-unit quaternion is not
- guaranteed to satisfy this identity (`#4942 <https://github.com/kornia/kornia/issues/4942>`_).
+ - ``c_from_b * b_from_a`` is ``c_from_a``, whose matrix is ``c_from_b.pose.matrix() @ b_from_a.pose.matrix()``.
The left operand's ``frame_src`` must equal the right operand's ``frame_dst``, otherwise ``*`` raises
``ValueError``; :meth:`inverse` inverts the pose and swaps the frame names.
- The pose must be an ``Se2`` or an ``Se3``: an ``So3``, ``So2``, ``Quaternion`` or tensor is rejected at
diff --git a/testing/half_precision_xfails/cpu_bfloat16.txt b/testing/half_precision_xfails/cpu_bfloat16.txt
index 92c2bab5d..35f015ecf 100644
--- a/testing/half_precision_xfails/cpu_bfloat16.txt
+++ b/testing/half_precision_xfails/cpu_bfloat16.txt
@@ -224,6 +224,7 @@ call builtins.AssertionError tests/geometry/liegroup/test_se3.py::TestSe3::test_
call builtins.AssertionError tests/geometry/liegroup/test_se3.py::TestSe3::test_mul_point[cpu-bfloat16-None]
call builtins.AssertionError tests/geometry/liegroup/test_se3.py::TestSe3::test_mul_vector[cpu-bfloat16-2]
call builtins.AssertionError tests/geometry/liegroup/test_se3.py::TestSe3::test_mul_vector[cpu-bfloat16-5]
+call builtins.AssertionError tests/geometry/liegroup/test_se3.py::TestSe3::test_mul_vector[cpu-bfloat16-None]
call builtins.RuntimeError tests/geometry/liegroup/test_so2.py::TestSo2::test_adjoint[cpu-bfloat16-1]
call builtins.RuntimeError tests/geometry/liegroup/test_so2.py::TestSo2::test_adjoint[cpu-bfloat16-2]
call builtins.RuntimeError tests/geometry/liegroup/test_so2.py::TestSo2::test_adjoint[cpu-bfloat16-5]
diff --git a/testing/half_precision_xfails/cpu_float16.txt b/testing/half_precision_xfails/cpu_float16.txt
index ad4dbf4e2..d09bdd633 100644
--- a/testing/half_precision_xfails/cpu_float16.txt
+++ b/testing/half_precision_xfails/cpu_float16.txt
@@ -271,11 +271,8 @@ call builtins.NotImplementedError tests/geometry/liegroup/test_se2.py::TestSe2::
call builtins.NotImplementedError tests/geometry/liegroup/test_se2.py::TestSe2::test_random[cpu-float16-2]
call builtins.NotImplementedError tests/geometry/liegroup/test_se2.py::TestSe2::test_random[cpu-float16-5]
call builtins.NotImplementedError tests/geometry/liegroup/test_se2.py::TestSe2::test_random[cpu-float16-None]
-call builtins.AssertionError tests/geometry/liegroup/test_se3.py::TestSe3::test_mul[cpu-float16-1]
call builtins.AssertionError tests/geometry/liegroup/test_se3.py::TestSe3::test_mul[cpu-float16-5]
-call builtins.AssertionError tests/geometry/liegroup/test_se3.py::TestSe3::test_mul[cpu-float16-None]
call builtins.AssertionError tests/geometry/liegroup/test_se3.py::TestSe3::test_mul_point[cpu-float16-5]
-call builtins.AssertionError tests/geometry/liegroup/test_se3.py::TestSe3::test_mul_vector[cpu-float16-2]
call builtins.AssertionError tests/geometry/liegroup/test_se3.py::TestSe3::test_mul_vector[cpu-float16-5]
call builtins.NotImplementedError tests/geometry/liegroup/test_so2.py::TestSo2::test_mul[cpu-float16-1]
call builtins.NotImplementedError tests/geometry/liegroup/test_so2.py::TestSo2::test_mul[cpu-float16-2]
diff --git a/tests/geometry/liegroup/test_se3.py b/tests/geometry/liegroup/test_se3.py
index 0e0c2bf87..ac015bf8c 100644
--- a/tests/geometry/liegroup/test_se3.py
+++ b/tests/geometry/liegroup/test_se3.py
@@ -494,8 +494,7 @@ class TestSe3(BaseTester):
self.assert_close((g * Se3.exp(v)).matrix(), (Se3.exp(ad_v) * g).matrix())
def test_convention_se3_composition_is_left_matrix_product(self, device, dtype):
- # With unit rotations from exp, a * b is the matrix product a b: b acts first on a point. Non-unit
- # quaternions violate this #4942 precondition.
+ # a * b is the matrix product a b: b acts first on a point.
a = Se3.exp(torch.tensor([1.0, -2.0, 3.0, 0.4, 0.2, -0.3], device=device, dtype=dtype))
b = Se3.exp(torch.tensor([0.3, 0.1, -0.2, -0.1, 0.3, 0.05], device=device, dtype=dtype))
self.assert_close(a.r.q.norm(), torch.ones((), device=device, dtype=dtype))
diff --git a/tests/geometry/liegroup/test_so3.py b/tests/geometry/liegroup/test_so3.py
index 9df4093d2..838117b40 100644
--- a/tests/geometry/liegroup/test_so3.py
+++ b/tests/geometry/liegroup/test_so3.py
@@ -637,24 +637,53 @@ class TestSo3Conventions(BaseTester):
p = torch.tensor([p], device=device, dtype=dtype)
self.assert_close(rot(theta) * p, torch.tensor([expected], device=device, dtype=dtype))
- def test_wart_so3_non_unit_quaternion_not_normalised_4942(self, device, dtype):
- # #4942 https://github.com/kornia/kornia/issues/4942: So3 stores the quaternion as given, and matrix() and
- # So3 * p use the unit-quaternion formulas, so a non-unit q gives a matrix that is not a rotation and points
- # scaled by |q|^2. This test turns red when So3 normalises its quaternion.
+ def test_convention_so3_non_unit_quaternion_is_its_direction_4942(self, device, dtype):
+ # #4942 https://github.com/kornia/kornia/issues/4942: a non-unit q is the rotation of q / |q|, as for
+ # Quaternion.matrix(). matrix() used to be a scaled non-rotation (det 4.56^3 here) and So3 * p scaled p by
+ # |q|^2 = 4.56.
data = torch.tensor([[2.0, 0.2, -0.6, 0.4]], device=device, dtype=dtype)
- squared_norm = 4.56
s = So3(Quaternion(data))
+ unit = So3(Quaternion(data).normalize())
p = torch.tensor([[1.0, 2.0, 3.0]], device=device, dtype=dtype)
m = s.matrix()
# det = m0 . (m1 x m2), written out so it runs where torch.linalg.det has no half-precision kernel
det = (m[:, 0] * torch.linalg.cross(m[:, 1], m[:, 2], dim=-1)).sum(-1)
- assert bool((det > 2.0).all()), det
- self.assert_close((s * p).norm(dim=-1), squared_norm * p.norm(dim=-1))
- # control: the same data through Quaternion.matrix(), and through So3 once normalised, is a rotation
- self.assert_close(So3(Quaternion(data).normalize()).matrix(), Quaternion(data).matrix())
- self.assert_close((So3(Quaternion(data).normalize()) * p).norm(dim=-1), p.norm(dim=-1))
- # log() is outside the defect: it reads only the direction of q
- self.assert_close(s.log(), So3(Quaternion(data).normalize()).log())
+ self.assert_close(det, torch.ones_like(det))
+ self.assert_close(m, Quaternion(data).matrix())
+ self.assert_close(m, unit.matrix())
+ self.assert_close(s.adjoint(), unit.adjoint())
+ # unit is normalised twice and s once, which is more than one rounding apart in half precision
+ half = dtype in (torch.float16, torch.bfloat16)
+ self.assert_close(s * p, unit * p, low_tolerance=half)
+ self.assert_close((s * p).norm(dim=-1), p.norm(dim=-1), low_tolerance=half)
+ self.assert_close(s.log(), unit.log())
+ # the quaternion itself is kept as given
+ self.assert_close(s.q.data, data)
+
+ def test_convention_so3_parameter_quaternion_stays_module_state_4942(self, device, dtype):
+ # Normalising where the quaternion is used, rather than once in the constructor, keeps an nn.Parameter
+ # quaternion registered, and matrix() follows an update of the Parameter.
+ holder = _RotationHolder(torch.tensor([[2.0, 0.0, 0.0, 0.0]], device=device, dtype=dtype), as_parameter=True)
+ assert "rot._q._data" in holder.state_dict()
+ self.assert_close(holder.rot.matrix(), torch.eye(3, device=device, dtype=dtype)[None])
+ with torch.no_grad():
+ holder.rot.q.data.copy_(torch.tensor([[0.0, 0.0, 0.0, 3.0]], device=device, dtype=dtype))
+ # (0, 0, 0, 3) is the half turn about z
+ expected = torch.diag(torch.tensor([-1.0, -1.0, 1.0], device=device, dtype=dtype))[None]
+ self.assert_close(holder.rot.matrix(), expected)
+ # the graph is rebuilt on every use, so a second backward through the rotation works
+ for _ in range(2):
+ holder.rot.matrix().sum().backward()
+
+ def test_convention_so3_non_unit_quaternion_gradient_has_no_radial_part_4942(self, device, dtype):
+ # matrix() and So3 * p depend on q / |q| only, so their gradient with respect to q is orthogonal to q.
+ data = torch.tensor([[2.0, 0.2, -0.6, 0.4]], device=device, dtype=dtype, requires_grad=True)
+ p = torch.tensor([[1.0, 2.0, 3.0]], device=device, dtype=dtype)
+ atol = 3e-2 if dtype in (torch.float16, torch.bfloat16) else 1e-5
+ for output in (So3(Quaternion(data)).matrix(), So3(Quaternion(data)) * p):
+ (grad,) = torch.autograd.grad(output.sum(), data)
+ cosine = (grad * data.detach()).sum(-1) / (grad.norm(dim=-1) * data.detach().norm(dim=-1))
+ self.assert_close(cosine, torch.zeros_like(cosine), rtol=0.0, atol=atol)
def test_convention_so3_from_matrix_is_unchecked_by_default(self, device, dtype):
# kornia#4773: with the default check_rotation=False, from_matrix returns an apparently valid result for an
diff --git a/tests/geometry/test_pose.py b/tests/geometry/test_pose.py
index bf7ce39ef..74424f401 100644
--- a/tests/geometry/test_pose.py
+++ b/tests/geometry/test_pose.py
@@ -217,7 +217,7 @@ class TestNamedPoseConventions(BaseTester):
def test_convention_named_pose_composition_order(self, device, dtype):
g1, g2 = self._poses(device, dtype)
- # The matrix product rule applies to unit rotations; Se3 accepts non-unit quaternions under #4942.
+ # Unit rotations from exp, so the expected matrix below is a product of rotations.
self.assert_close(g1.r.q.norm(), torch.ones((), device=device, dtype=dtype))
self.assert_close(g2.r.q.norm(), torch.ones((), device=device, dtype=dtype))
b_from_a = NamedPose(g1, frame_src="a", frame_dst="b")
diff --git a/tests/geometry/test_quaternion.py b/tests/geometry/test_quaternion.py
index 45a0c6bc9..0d8baa85b 100644
--- a/tests/geometry/test_quaternion.py
+++ b/tests/geometry/test_quaternion.py
@@ -792,7 +792,7 @@ class TestQuaternionConventions(BaseTester):
q = Quaternion(data)
# precondition: |q| = sqrt(4.56) = 2.14, far from unit
assert (q.norm() - 1.0).abs().max() > 1.0
- # matrix() is the rotation of q / |q|, a proper rotation (So3.matrix() is not, #4942)
+ # matrix() is the rotation of q / |q|, a proper rotation, as So3.matrix() is (#4942)
rotation = q.matrix()
self.assert_close(rotation, q.normalize().matrix())
eye = torch.eye(3, device=device, dtype=dtype)[None]