Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

docs(geometry): per-op Convention blocks for conversions (batch 3b: rotation representations) (#3967)

Dmytro Mishkinf0a06c707c8b
diff --git a/kornia/geometry/conversions.py b/kornia/geometry/conversions.py
index 3abd00c1f..087ba084f 100644
--- a/kornia/geometry/conversions.py
+++ b/kornia/geometry/conversions.py
@@ -416,6 +416,64 @@ def convert_affinematrix_to_homography3d(A: torch.Tensor) -> torch.Tensor:
def axis_angle_to_rotation_matrix(axis_angle: torch.Tensor) -> torch.Tensor:
r"""Convert 3d vector of axis-angle rotation to 3x3 rotation matrix.
+ Convention:
+ - the input is the rotation axis scaled by the angle, in **radians**,
+ and must be batched β€” a bare ``(3,)`` vector raises (see the shape
+ warning below): ``[[0., 0., pi/2]]`` is a quarter turn about ``+z``,
+ while ``[[0., 0., 90.]]`` is 90 *radians* about ``+z`` and returns a
+ matrix whose leading entry is ``cos(90) = -0.4481``. The 2-D op
+ :func:`~kornia.geometry.conversions.angle_to_rotation_matrix` reads
+ **degrees** instead
+ - applied on the left to a column vector, ``+theta`` about ``+z`` maps
+ ``x_hat`` to ``y_hat`` (right-hand rule): ``[[0., 0., 0.6]]`` sends
+ ``(1., 0., 0.)`` to ``(0.8253, 0.5646, 0.)``. The quaternion route
+ :func:`~kornia.geometry.conversions.quaternion_to_rotation_matrix`
+ turns the same way
+ - ``angle_axis_to_rotation_matrix`` is the deprecated alias of this
+ function since 0.7.0; it emits a ``DeprecationWarning`` and forwards
+ to this function, returning an equal result β€” see the alias warning
+ below
+
+ .. warning::
+ The returned matrix is **not orthogonal**: ``eps = 1e-6`` is added to
+ the angle when the axis is normalised, which shrinks the axis. In
+ ``float64`` at ``theta = pi/2`` about ``+z``, ``det(R)`` is
+ ``0.9999974535249636`` and ``max|R R^T - I|`` is
+ ``2.5464750363912714e-06``; the determinant is axis-independent to the
+ last digit or two, while the orthogonality residual is not (a generic
+ axis gives
+ ``2.091747640764474e-06``). ``float32`` is no better
+ (``2.5033950805664062e-06`` on the same input), and
+ the second example below hides it β€” the printed ``1.0000e+00`` at
+ ``R[0, 0]`` is really ``0.9999987483024597``. Below an internal
+ threshold on ``theta ** 2`` the first-order matrix
+ ``[[1, -rz, ry], [rz, 1, -rx], [-ry, rx, 1]]`` is returned instead, with
+ ``det = 1 + theta ** 2``: in ``float64`` the input ``[0., 0., 1e-3]``
+ takes that branch (``det = 1.000001``) while ``1e-3 * (1, 2, 3)/sqrt(14)``
+ does not (``det = 0.9999999970044947``), so which branch an input takes
+ depends on its axis and dtype. Tracked in
+ `#3947 <https://github.com/kornia/kornia/issues/3947>`_.
+
+ .. warning::
+ Only rank-2 input is accepted, despite the guard's ``(*, 3)`` message:
+ ``(3,)`` raises ``IndexError: Dimension out of range``, ``(2, 5, 3)``
+ raises ``ValueError: too many values to unpack (expected 3)`` and
+ ``(1, 1, 3)`` raises ``ValueError: not enough values to unpack``.
+ Composing with
+ :func:`~kornia.geometry.conversions.rotation_matrix_to_axis_angle`
+ therefore fails for every rotation-matrix rank but 3. Tracked in
+ `#3955 <https://github.com/kornia/kornia/issues/3955>`_.
+
+ .. warning::
+ Calling any of this module's four deprecated aliases
+ (``angle_axis_to_rotation_matrix``, ``rotation_matrix_to_angle_axis``,
+ ``quaternion_to_angle_axis``, ``angle_axis_to_quaternion``) rewrites the
+ process-global ``DeprecationWarning`` filters, so
+ ``-W error::DeprecationWarning`` does not turn the warning into an error
+ and every later ``DeprecationWarning`` raised in the process is affected
+ too. Tracked in
+ `#3956 <https://github.com/kornia/kornia/issues/3956>`_.
+
Args:
axis_angle: tensor of 3d vector of axis-angle rotations in radians with shape :math:`(N, 3)`.
@@ -519,11 +577,35 @@ def angle_axis_to_rotation_matrix(axis_angle: torch.Tensor) -> torch.Tensor: #
def rotation_matrix_to_axis_angle(rotation_matrix: torch.Tensor) -> torch.Tensor:
r"""Convert 3x3 rotation matrix to Rodrigues vector in radians.
+ Convention:
+ - any number of leading batch dimensions is accepted: :math:`(3, 3)`
+ gives :math:`(3,)` and :math:`(2, 5, 3, 3)` gives :math:`(2, 5, 3)`
+ - the output is the rotation axis scaled by the angle in **radians**,
+ the parametrization
+ :func:`~kornia.geometry.conversions.axis_angle_to_rotation_matrix`
+ consumes β€” but that function accepts only rank-2 input, so the
+ :math:`(3,)` and :math:`(2, 5, 3)` results above cannot be fed
+ straight back (see its shape warning)
+ - the round trip through
+ :func:`~kornia.geometry.conversions.axis_angle_to_rotation_matrix` is
+ accurate only to about ``1e-6`` even in ``float64`` β€” measured
+ ``8.0e-07`` at ``theta = 1e-3`` and ``5.4e-07`` at ``theta = pi``
+ about ``(1, 2, 3)/sqrt(14)`` β€” because of that function's
+ `#3947 <https://github.com/kornia/kornia/issues/3947>`_
+ - the input is **not** checked for being a rotation matrix:
+ ``zeros(3, 3)`` returns ``[0., 0., 3.1416]``, ``2 * eye(3)`` returns
+ ``[0., 0., 0.]``, and the reflection ``diag(-1, 1, 1)``
+ (``det = -1``) also returns ``[0., 0., 0.]``, i.e. is silently
+ reported as no rotation at all
+ - ``rotation_matrix_to_angle_axis`` is the deprecated alias of this
+ function since 0.7.0; see the alias warning on
+ :func:`~kornia.geometry.conversions.axis_angle_to_rotation_matrix`
+
Args:
- rotation_matrix: rotation matrix of shape :math:`(N, 3, 3)`.
+ rotation_matrix: rotation matrix of shape :math:`(*, 3, 3)`.
Returns:
- Rodrigues vector transformation of shape :math:`(N, 3)`.
+ Rodrigues vector transformation of shape :math:`(*, 3)`.
Example:
>>> input = torch.tensor([[1., 0., 0.],
@@ -558,9 +640,33 @@ def rotation_matrix_to_quaternion(rotation_matrix: torch.Tensor, eps: float = 1.
The quaternion vector has components in (w, x, y, z) format.
+ Convention:
+ - the returned components are ``(w, x, y, z)``, real part first β€” the
+ layout, and its silent misreading, are spelled out on
+ :func:`~kornia.geometry.conversions.quaternion_to_rotation_matrix`
+ - the sign is **not** canonicalised to ``w >= 0``. For
+ ``trace(R) > 0`` the returned ``w`` is non-negative, but for
+ ``trace(R) <= 0`` it is the dominant of ``x, y, z`` that is forced
+ non-negative and ``w`` may be negative: 170 degrees about
+ ``(1, 2, -3)/sqrt(14)`` (``trace = -0.9696``) returns
+ ``[-0.0872, -0.2662, -0.5325, 0.7987]``
+ - the input is **not** checked for being a rotation matrix; see the
+ degenerate inputs listed on
+ :func:`~kornia.geometry.conversions.rotation_matrix_to_axis_angle`
+
+ .. warning::
+ ``eps`` is added *inside* the square root that produces the dominant
+ component, so with the default the result is not a unit quaternion. In
+ ``float64``, ``rotation_matrix_to_quaternion(torch.eye(3))`` returns
+ ``[1.0000000012499999, 0., 0., 0.]`` (``||q|| - 1`` is ``1.25e-09``),
+ while ``eps=0.0`` returns exactly ``[1., 0., 0., 0.]``. The inflation is
+ below one ulp of 1.0 in ``float32``, ``float16`` and ``bfloat16``, where
+ the identity already comes back exactly unit. Tracked in
+ `#3951 <https://github.com/kornia/kornia/issues/3951>`_.
+
Args:
rotation_matrix: the rotation matrix to convert with shape :math:`(*, 3, 3)`.
- eps: small value to avoid zero division.
+ eps: added inside the square root of the dominant component; see the warning above.
Return:
the rotation in quaternion with shape :math:`(*, 4)`.
@@ -633,10 +739,33 @@ def normalize_quaternion(quaternion: torch.Tensor, eps: float = 1.0e-12) -> torc
The quaternion should be in (x, y, z, w) or (w, x, y, z) format.
+ Convention:
+ - it is an L2 normalisation of the **last** axis and nothing else, which
+ is why the ``(x, y, z, w)`` or ``(w, x, y, z)`` phrasing above is
+ accurate here: ``[4., 3., 2., 1.]`` normalises to the reversal of what
+ ``[1., 2., 3., 4.]`` gives
+ - the sign is preserved β€” ``normalize_quaternion(-q)`` is exactly
+ ``-normalize_quaternion(q)``, there is no ``w >= 0``
+ canonicalisation
+
+ .. warning::
+ When ``||q|| < eps`` the output is **not** a unit quaternion and no
+ error is raised: in ``float64`` with the default ``eps = 1e-12``,
+ ``[1e-13, 0., 0., 0.]`` returns ``[0.1, 0., 0., 0.]`` and ``zeros(4)``
+ 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
+ `#3952 <https://github.com/kornia/kornia/issues/3952>`_.
+
Args:
quaternion: a tensor containing a quaternion to be normalized.
The tensor can be of shape :math:`(*, 4)`.
- eps: small value to avoid division by zero.
+ eps: floor on the norm used as the divisor; see the warning above.
Return:
the normalized quaternion of shape :math:`(*, 4)`.
@@ -665,6 +794,71 @@ def quaternion_to_rotation_matrix(quaternion: torch.Tensor) -> torch.Tensor:
The quaternion should be in (w, x, y, z) format.
+ Convention:
+ - the quaternion is ``(w, x, y, z)``, **real part first**, shape
+ :math:`(*, 4)` in and :math:`(*, 3, 3)` out. ``[1., 0., 0., 0.]``
+ gives the identity and ``[0., 0., 0., 1.]`` gives
+ ``[[-1., 0., 0.], [0., -1., 0.], [0., 0., 1.]]``, a half turn about
+ ``+z`` β€” so a caller passing ``(x, y, z, w)`` gets a valid-looking
+ rotation matrix and no error
+ - ``q`` and ``-q`` are the same rotation (double cover) and return
+ bit-identical matrices
+ - the input is normalised internally:
+ ``quaternion_to_rotation_matrix(2 * q)`` is bitwise
+ ``quaternion_to_rotation_matrix(q)`` (400 000 random unit
+ quaternions, at every dtype). Rescaling by random factors between
+ ``1e-6`` and ``1e6`` moves the matrix only by the working dtype's
+ rounding in ``float64`` and ``float32`` (by ``1.3e-15`` and
+ ``6.0e-07`` over 2000 random unit quaternions), but the
+ reduced-precision dtypes do **not** hold to that: ``bfloat16`` moves
+ by ``3.1e-02``, and ``float16`` loses the property altogether β€” near
+ the top of that range the rescaled matrix bears no relation to the
+ input at all (entries live in ``[-1, 1]``, and the deviation
+ 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
+ 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
+ scale-safe over its own range, given in its Convention block; the two
+ functions that are **not** are
+ :func:`~kornia.geometry.conversions.quaternion_exp_to_log` and
+ :func:`~kornia.geometry.conversions.euler_from_quaternion`, whose
+ warnings give the measured errors
+ - applied on the left to a column vector, ``+theta`` about ``+z`` maps
+ ``x_hat`` to ``y_hat`` (right-hand rule)
+ - the output dtype follows the input at every shape but one: an
+ **unbatched** ``float16`` or ``bfloat16`` quaternion of shape
+ ``(4,)`` returns a ``float32`` matrix, so the same call on ``q`` and
+ on ``q[None]`` returns two different dtypes β€” see the warning below.
+ :func:`~kornia.geometry.conversions.normalize_quaternion`,
+ :func:`~kornia.geometry.conversions.quaternion_to_axis_angle` and
+ :func:`~kornia.geometry.conversions.quaternion_exp_to_log` return the
+ input dtype at every shape
+
+ .. warning::
+ An **unbatched** ``float16`` or ``bfloat16`` quaternion of shape
+ ``(4,)`` returns a ``float32`` matrix; the same quaternion batched β€”
+ ``(1, 4)``, ``(2, 4)``, ``(3, 3, 4)`` β€” returns the input dtype. The
+ three diagonal entries are computed against a 0-dim ``float32``
+ literal, and type promotion ranks a dimensioned tensor above a 0-dim
+ one: batched components therefore keep their dtype, while the 0-dim
+ components of an unbatched input tie with the literal and ``float32``
+ wins the category. Tracked in
+ `#3954 <https://github.com/kornia/kornia/issues/3954>`_.
+
+ .. 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
+ `#3952 <https://github.com/kornia/kornia/issues/3952>`_.
+
Args:
quaternion: a tensor containing a quaternion to be converted.
The tensor can be of shape :math:`(*, 4)`.
@@ -739,6 +933,46 @@ def quaternion_to_axis_angle(quaternion: torch.Tensor) -> torch.Tensor:
Adapted from ceres C++ library: ceres-solver/include/ceres/rotation.h
+ Convention:
+ - the input is ``(w, x, y, z)``, real part first (see
+ :func:`~kornia.geometry.conversions.quaternion_to_rotation_matrix`),
+ and the output is the rotation axis scaled by the angle in
+ **radians**
+ - for ``w != 0`` the double cover is collapsed: ``q`` and ``-q`` return
+ the same vector, the representative with ``|theta| <= pi``, and in
+ ``float64`` the two are bit-identical (400 000 random finite
+ quaternions). At lower precision they agree to the working dtype's
+ rounding
+ - at exactly ``w = 0`` β€” a half turn, and ``0.`` is exactly
+ representable β€” the collapse does not happen and the two return exact
+ negations: ``[0., 1., 0., 0.]`` gives ``[pi, 0., 0.]`` while
+ ``[-0., -1., 0., 0.]`` gives ``[-pi, 0., 0.]``, the same rotation
+ written the other way round
+ - the input need not be unit: ``quaternion_to_axis_angle(2 * q)`` is
+ bitwise ``quaternion_to_axis_angle(q)`` (400 000 random unit
+ quaternions, at every dtype). Rescaling by random factors between
+ ``1e-6`` and ``1e6`` moves the result only by the working dtype's
+ rounding in ``float64`` and ``float32`` (by ``8.9e-16`` and
+ ``4.8e-07`` over 2000 random unit quaternions), but the
+ reduced-precision dtypes do **not** hold to that: ``bfloat16`` moves
+ by ``3.1e-02`` and ``float16`` by over ``3`` radians, and the ``1e6``
+ end is ``nan`` at ``float16`` because ``0.5 * 1e6`` overflows the
+ dtype.
+ At extreme scales the squares of the vector part underflow and the
+ result does change: in ``float32``,
+ ``quaternion_to_axis_angle(q * 1e-25)`` returns exactly
+ ``2 * (q * 1e-25)[..., 1:]``
+ - ``quaternion_to_angle_axis`` is the deprecated alias of this function
+ since 0.7.0; see the alias warning on
+ :func:`~kornia.geometry.conversions.axis_angle_to_rotation_matrix`
+
+ .. warning::
+ The gradient at the identity quaternion is ``nan``:
+ ``quaternion_to_axis_angle(torch.tensor([1., 0., 0., 0.])).sum().backward()``
+ leaves ``[nan, nan, nan, nan]`` in ``.grad``, from an unclamped
+ ``sqrt(0)``. Away from the identity the gradient is finite. Tracked in
+ `#3949 <https://github.com/kornia/kornia/issues/3949>`_.
+
Args:
quaternion: tensor with quaternions.
@@ -793,11 +1027,62 @@ def quaternion_to_angle_axis(quaternion: torch.Tensor) -> torch.Tensor: # noqa:
def quaternion_log_to_exp(quaternion: torch.Tensor, eps: float = 1.0e-8) -> torch.Tensor:
r"""Apply exponential map to log quaternion.
- The quaternion should be in (w, x, y, z) format.
+ Convention:
+ - the **input** is a 3-vector of shape :math:`(*, 3)`, not a
+ quaternion; the **output** is the quaternion of shape :math:`(*, 4)`
+ in ``(w, x, y, z)`` order (see
+ :func:`~kornia.geometry.conversions.quaternion_to_rotation_matrix`)
+ - the map is ``w = cos(||v||)`` with vector part
+ ``sin(||v||) * v / ||v||``, so whenever ``||v||`` is computed finitely
+ the output is a unit quaternion up to the working dtype's rounding.
+ Two inputs escape that: the ``float16`` zero vector, and any ``v``
+ large enough that ``||v||`` overflows β€” see the two warnings below
+ - ``pi/2 < ||v|| < 3 * pi/2`` lands in the ``w < 0`` half of the double
+ cover β€” at ``||v|| = 2`` the real part is ``-0.4161468365471424``.
+ ``w`` is ``cos(||v||)``, so the sign turns over again beyond that
+ interval rather than staying negative
+ - ``v`` is therefore **half** the axis-angle vector: the result agrees
+ with ``axis_angle_to_quaternion(2 * v)`` to the rounding of the
+ working dtype, but **not** bit-for-bit: ``[0.15, 0.2, 0.25]`` already
+ disagrees at ``bfloat16``, and in ``float64`` most random vectors do
+ too
+ - for a **unit** ``q``, ``quaternion_log_to_exp(quaternion_exp_to_log(q))``
+ returns ``q`` up to rounding, except that the pure-real
+ ``[-1., 0., 0., 0.]`` comes back as ``[1., 0., 0., 0.]`` β€” the other
+ half of the same rotation
+
+ .. warning::
+ In ``float16`` the default ``eps = 1e-8`` rounds to ``0``, so the clamp
+ that guards the division is a no-op and the zero vector returns
+ ``[1., nan, nan, nan]``. It is the only input that does: ``torch.norm``
+ does not underflow at ``float16``, so every ``v`` that is not exactly
+ zero has a non-zero norm and is unaffected. ``float64``, ``float32``
+ and ``bfloat16`` return ``[1., 0., 0., 0.]`` for ``zeros(3)``, and so
+ does ``float16`` with a representable ``eps`` (e.g. ``eps=1e-3``).
+ Tracked in
+ `#3966 <https://github.com/kornia/kornia/issues/3966>`_.
+
+ .. warning::
+ ``||v||`` is computed with ``torch.norm(p=2)``, which forms the sum of
+ squares and so overflows to ``inf`` far below the largest finite input.
+ Beyond that point **all four** components come back ``nan``, even
+ though the exponential map of a large finite vector is a perfectly good
+ unit quaternion. Where the turnover sits depends on the accumulator:
+ ``float32`` and ``bfloat16`` accumulate in their own dtype and so
+ overflow once ``||v||`` passes ``sqrt(finfo.max)`` β€” from about
+ ``1.8446744e19`` in ``float32`` (against a ``finfo.max`` of ``3.4e38``)
+ and about ``1.841e19`` in ``bfloat16`` β€” as does ``float64``, from
+ about ``1.3407808e154`` (against ``1.8e308``). ``float16`` accumulates
+ in wider precision, so its squares never overflow and it turns over
+ only once the true ``||v||`` exceeds what ``float16`` itself can hold,
+ near ``65520``. That still happens, but it takes **two or more**
+ non-zero components, since a single one cannot exceed ``65504``:
+ ``[37824., 37824., 37824.]`` is finite while
+ ``[37856., 37856., 37856.]`` is all ``nan``. Tracked in
+ `#3975 <https://github.com/kornia/kornia/issues/3975>`_.
Args:
- quaternion: a tensor containing a quaternion to be converted.
- The tensor can be of shape :math:`(*, 3)`.
+ quaternion: the log quaternion, a tensor of shape :math:`(*, 3)`.
eps: a small number for clamping.
Return:
@@ -833,6 +1118,42 @@ def quaternion_exp_to_log(quaternion: torch.Tensor, eps: float = 1.0e-8) -> torc
The quaternion should be in (w, x, y, z) format.
+ Convention:
+ - the input is the quaternion of shape :math:`(*, 4)` in
+ ``(w, x, y, z)`` order and the output is a 3-vector of shape
+ :math:`(*, 3)`, the argument
+ :func:`~kornia.geometry.conversions.quaternion_log_to_exp` takes
+ - for a **unit** ``q`` on the ``w >= 0`` half of the double cover the
+ result is ``quaternion_to_axis_angle(q) / 2``. On the ``w < 0`` half the two
+ part company: this function applies ``acos(w)`` as given, while
+ :func:`~kornia.geometry.conversions.quaternion_to_axis_angle`
+ collapses the double cover. For the ``q`` whose log is ``v``,
+ ``quaternion_exp_to_log(-q)`` is ``-(pi - ||v||) * v / ||v||``
+ - ``quaternion_exp_to_log(quaternion_log_to_exp(v))`` returns ``v`` for
+ ``0 < ||v|| < pi`` and the wrapped ``||v|| - 2 * pi`` above ``pi``
+ (``pi + 0.5`` comes back as ``-2.6415926535897936``). At exactly
+ ``||v|| = pi``, and only in ``float64``, it collapses to ``3.85e-08``
+ β€” there ``cos(pi)`` rounds to ``-1`` and the vector part falls under
+ the ``eps`` clamp. Both are properties of the map, not defects
+
+ .. warning::
+ The input is **not** normalised, so a non-unit quaternion is silently
+ given a wrong log: ``[0.5, 0.5, 0., 0.]`` returns
+ ``[1.0471975511965976, 0., 0.]``, 33 % larger than the
+ ``[0.7853981633974484, 0., 0.]`` of the same rotation normalised, and
+ ``[2., 0., 0., 0.]`` returns the origin because ``w`` is clamped to
+ ``1``. Tracked in
+ `#3953 <https://github.com/kornia/kornia/issues/3953>`_.
+
+ .. warning::
+ In ``float16`` the default ``eps = 1e-8`` underflows to ``0``, so the
+ clamp that guards the division is a no-op and **any** quaternion with a
+ zero vector part returns ``[nan, nan, nan]`` β€” including the identity
+ ``[1., 0., 0., 0.]``, whose log is the origin at every other dtype.
+ Passing a representable ``eps`` (e.g. ``eps=1e-3``) returns
+ ``[0., 0., 0.]`` there. Tracked in
+ `#3966 <https://github.com/kornia/kornia/issues/3966>`_.
+
Args:
quaternion: a tensor containing a quaternion to be converted.
The tensor can be of shape :math:`(*, 4)`.
@@ -879,6 +1200,37 @@ def axis_angle_to_quaternion(axis_angle: torch.Tensor) -> torch.Tensor:
Adapted from ceres C++ library: ceres-solver/include/ceres/rotation.h
+ Convention:
+ - the input is the rotation axis scaled by the angle in **radians**,
+ shape :math:`(*, 3)`; the output is ``(w, x, y, z)`` with
+ ``w = cos(theta / 2)``, shape :math:`(*, 4)` (see
+ :func:`~kornia.geometry.conversions.quaternion_to_rotation_matrix`
+ for the layout)
+ - nothing is canonicalised, so ``theta > pi`` returns the ``w < 0`` half
+ of the double cover: ``[2 * pi, 0., 0.]`` gives ``[-1., 0., 0., 0.]``
+ - the round trip with
+ :func:`~kornia.geometry.conversions.quaternion_to_axis_angle` is exact
+ in ``float64``: the measured error is ``0`` to ``2.2e-16`` at
+ ``theta = 0``, ``1e-3``, ``0.7``, ``2`` and ``pi`` about
+ ``(1, 2, 3)/sqrt(14)``
+ - ``angle_axis_to_quaternion`` is the deprecated alias of this function
+ since 0.7.0; see the alias warning on
+ :func:`~kornia.geometry.conversions.axis_angle_to_rotation_matrix`
+
+ .. warning::
+ The gradient at the zero rotation is ``nan``:
+ ``axis_angle_to_quaternion(torch.zeros(3)).sum().backward()`` leaves
+ ``[nan, nan, nan]`` in ``.grad``, from an unclamped ``sqrt(0)``.
+ Tracked in `#3949 <https://github.com/kornia/kornia/issues/3949>`_.
+
+ .. warning::
+ An integer tensor returns an all-zero integer tensor instead of a
+ quaternion: ``axis_angle_to_quaternion(torch.tensor([1, 0, 0]))`` is
+ ``tensor([0, 0, 0, 0])`` of dtype ``int64``, against the ``float32``
+ answer ``[0.8776, 0.4794, 0., 0.]``, because the output buffer is
+ allocated with the input dtype. Tracked in
+ `#3948 <https://github.com/kornia/kornia/issues/3948>`_.
+
Args:
axis_angle: tensor with axis angle in radians.
@@ -941,7 +1293,59 @@ def euler_from_quaternion(
) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
"""Convert a quaternion coefficients to Euler angles.
- Returned angles are in radians in XYZ convention.
+ Convention:
+ - the four quaternion coefficients are passed as **separate** tensors in
+ ``(w, x, y, z)`` order, not as one :math:`(*, 4)` tensor, and their
+ shapes must be exactly equal: broadcastable shapes such as ``(2,)``
+ and ``(1,)`` raise ``BaseError: Validation condition failed``, and
+ Python floats raise ``AttributeError``
+ - the return is a tuple of three tensors ``(roll, pitch, yaw)`` in
+ **radians**, with ``roll`` about ``x``, ``pitch`` about ``y`` and
+ ``yaw`` about ``z``; the composition they stand for is documented on
+ :func:`~kornia.geometry.conversions.quaternion_from_euler`
+ - away from ``|pitch| = pi/2`` it returns the triple of the input
+ rotation folded into ``roll, yaw`` in ``[-pi, pi]`` β€” the interval is
+ closed at both ends: they come from ``atan2``, which reaches ``Β±pi``
+ with the endpoint's sign decided by signed zeros, so ``w = -0.0,
+ x = 1.0, y = 0.0, z = -0.0`` returns roll exactly ``-pi`` while the
+ ``+0.0`` twin returns ``+pi`` β€” and ``pitch`` in
+ ``[-pi/2, pi/2]``, which inside those ranges is the input itself: the
+ ``float64`` round trip of ``(0.3, 0.7, 1.1)`` through
+ :func:`~kornia.geometry.conversions.quaternion_from_euler` returns to
+ ``2.2e-16``, while ``(0.2, 2.5, 0.3)`` comes back as
+ ``(-2.9416, 0.6416, -2.8416)`` β€” a different triple for the same
+ rotation, to ``1.1e-16``
+
+ .. warning::
+ At ``pitch = Β±pi/2`` the returned triple usually does not represent the
+ input rotation, and no gimbal-lock branch exists to say so. ``roll`` and
+ ``yaw`` come from ``atan2`` of two quantities that cancel to nothing
+ there, so the triple that comes back is decided by rounding: it varies
+ between dtypes, between PyTorch versions, and under a one-ulp change of
+ the input pitch, and no specific triple is quoted here for that reason.
+ What is stable is that ``pitch`` lands within about ``sqrt(eps)`` of
+ ``Β±pi/2`` β€” the ``asin`` argument rounds to within an ulp of ``1``, and
+ ``asin(1 - d)`` is ``pi/2 - sqrt(2d)`` β€” and that the reconstructed
+ rotation is far from the input. Whether ``Β±pi/2`` is reached exactly
+ depends on dtype and build: at ``float64`` it is exact here, while the
+ ``float32`` round trip of ``(0.1, pi/2, 0.2)`` returns pitch
+ ``1.570451``, ``3.45e-4`` *below* ``float32``'s ``pi/2`` β€” an exact
+ ``pitch == pi/2`` check never fires there. Random ``(roll, yaw)``
+ at ``pitch = +pi/2`` fail this way, while ``|pitch| < pi/4`` round trips
+ to rounding. The rotation does survive on the diagonal
+ ``roll = yaw`` at ``+pi/2`` (and ``roll = -yaw`` at ``-pi/2``), where
+ random draws round trip to within a few parts in ``1e8``, though
+ ``roll`` and ``yaw`` are still not returned individually. Tracked in
+ `#3950 <https://github.com/kornia/kornia/issues/3950>`_.
+
+ .. warning::
+ The input is **not** normalised, so a non-unit quaternion silently gives
+ a wrong triple: for the ``q`` of ``(0.3, 0.7, 1.1)``, passing ``2 * q``
+ returns ``[1.6560585860248003, 1.5707963267948966,
+ 2.1048169977173687]``. The middle value is exactly ``pi/2`` β€” the
+ over-scaled input saturates the ``asin`` and is reported as
+ gimbal-locked. Tracked in
+ `#3953 <https://github.com/kornia/kornia/issues/3953>`_.
Args:
w: quaternion :math:`q_w` coefficient.
@@ -979,7 +1383,20 @@ def quaternion_from_euler(
) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]:
"""Convert Euler angles to quaternion coefficients.
- Euler angles are assumed to be in radians in XYZ convention.
+ Convention:
+ - ``roll``, ``pitch`` and ``yaw`` are in **radians** and turn about
+ ``x``, ``y`` and ``z`` respectively; the rotation they compose to is
+ ``R = Rz(yaw) @ Ry(pitch) @ Rx(roll)`` β€” extrinsic X-Y-Z about the
+ fixed axes, equivalently intrinsic Z-Y'-X''. The order matters: at
+ ``(0.3, 0.7, 1.1)`` the returned quaternion's matrix differs from
+ ``Rx @ Ry @ Rz`` by ``0.64``, from ``Ry @ Rz @ Rx`` by ``0.55`` and
+ from ``Rx @ Rz @ Ry`` by ``0.25``
+ - the three arguments must have exactly equal shapes; broadcastable
+ shapes such as ``(2,)`` and ``(1,)`` raise
+ ``BaseError: Validation condition failed``
+ - the return is a tuple of **four separate tensors** ``(w, x, y, z)``,
+ not a :math:`(*, 4)` tensor: ``(0.3, 0.7, 1.1)`` gives
+ ``[0.8186, -0.0575, 0.3624, 0.4418]``
Args:
roll: the roll euler angle.
diff --git a/tests/geometry/test_conversions.py b/tests/geometry/test_conversions.py
index 827836370..bf113e158 100644
--- a/tests/geometry/test_conversions.py
+++ b/tests/geometry/test_conversions.py
@@ -17,6 +17,7 @@
import inspect
import sys
+import warnings
from functools import partial
import numpy as np
@@ -61,6 +62,52 @@ def rtol(device, dtype):
return 1.0e-4
+def _runs_without_raising(func, *args, **kwargs) -> bool:
+ # Shared boolean adapter for the kornia#3955 strict-xfail call sites below, whose CURRENT
+ # behavior is a raise. That mark carries raises=AssertionError so that an unrelated
+ # environment error cannot silently *satisfy* the mark and stop the pin from testing anything;
+ # that in turn means the xfail body must fail as an assertion and must never let the exception
+ # escape. Asserting on this boolean is how each call site does it. Retire this helper together
+ # with the #3955 pins.
+ try:
+ func(*args, **kwargs)
+ except Exception:
+ return False
+ return True
+
+
+def _issue_msg(text: str):
+ # torch.testing.assert_close accepts msg as a callable that receives its own diff report; this
+ # wrapper prefixes the issue number so that the assert_close-based bug pins below name their
+ # issue in the failure text, the way their bare-assert siblings do. The test names carry the
+ # number too, but the failure text is what a future XPASS or wart flip is read from.
+ # The pins using it call the module-level assert_close rather than BaseTester.assert_close,
+ # which does not forward msg; the two apply the same dtype-aware default tolerances.
+ return lambda default_message: f"{text}\n{default_message}"
+
+
+def _skip_if_dtype_unavailable(device, dtype) -> None:
+ # Visible skip (never a silent guard) for the dtype-hardcoded pins below. Those pins drop the
+ # dtype fixture on purpose so they run in every test configuration, which means they would
+ # otherwise also run on a device that cannot represent the dtype at all -- MPS has no float64
+ # -- and the resulting TypeError would satisfy a raises=AssertionError xfail mark instead of
+ # the assertion the pin documents. Probed at runtime rather than hardcoded per backend so the
+ # skip retires itself once a backend gains the dtype.
+ try:
+ torch.zeros(1, device=device, dtype=dtype)
+ except (TypeError, RuntimeError) as err:
+ pytest.skip(f"{dtype} is unavailable on device {device}: {err}")
+
+
+def _undo_3954_upcast(matrix: torch.Tensor, dtype: torch.dtype) -> torch.Tensor:
+ # quaternion_to_rotation_matrix returns float32 for unbatched (4,) float16/bfloat16 input
+ # (kornia#3954, pinned in TestQuaternionToRotationMatrix; batched input keeps its dtype).
+ # Callers cast the result back so each pin stays about its own claim and nothing else. When
+ # #3954 is fixed this becomes a no-op: delete it and its call sites in the same edit that
+ # retires the #3954 wart pins.
+ return matrix.to(dtype)
+
+
class TestAngleAxisToQuaternion(BaseTester):
# based on:
# https://github.com/ceres-solver/ceres-solver/blob/master/internal/ceres/rotation_test.cc#L271
@@ -131,6 +178,231 @@ class TestAngleAxisToQuaternion(BaseTester):
# evaluate function gradient
self.gradcheck(partial(kornia.geometry.conversions.axis_angle_to_quaternion), (axis_angle,))
+ def test_convention_theta_beyond_pi_returns_the_w_negative_half(self, device, dtype):
+ # Convention pin: axis_angle_to_quaternion applies w = cos(theta/2) and
+ # (x, y, z) = sin(theta/2) * axis verbatim, with NO canonicalisation to w >= 0, so any
+ # theta > pi comes back in the w < 0 half of the double cover. A full turn about +x gives
+ # (-1, 0, 0, 0) -- the same rotation as the identity quaternion (1, 0, 0, 0) that a
+ # canonicalising implementation would return, but not the same four numbers. The second
+ # case is off-axis (theta = 4 rad about (1, 2, 3)/sqrt(14)) so that a sign flip on any
+ # single component is caught as well.
+ # Snippet used to generate expected (stdlib only):
+ # import math
+ # math.cos(math.pi), math.sin(math.pi) -> (-1.0, 1.2246467991473532e-16)
+ # n = math.sqrt(14.0); axis = (1 / n, 2 / n, 3 / n); theta = 4.0
+ # [theta * a for a in axis]
+ # -> [1.0690449676496976, 2.138089935299395, 3.2071349029490928]
+ # [math.cos(theta / 2)] + [math.sin(theta / 2) * a for a in axis]
+ # -> [-0.4161468365471424, 0.24301995956120354, 0.48603991912240707, 0.7290598786836107]
+ full_turn = kornia.geometry.conversions.axis_angle_to_quaternion(
+ torch.tensor([6.283185307179586, 0.0, 0.0], device=device, dtype=dtype)
+ )
+ # Asserted structurally rather than through assert_close against [-1, 0, 0, 0]: the vector
+ # part is sin(theta/2) at theta = 2*pi, whose error is ~1 ulp of the dtype, and at float16
+ # that is 9.675e-04 against the shared float16 atol of 1e-3 -- 96.75% of the budget, so one
+ # extra ulp (a backend doing native half-precision sin rather than upcasting, e.g. CUDA)
+ # turns this green cell red. Default CI runs float32/float64 only, so it is unexercised
+ # today. What the pin is actually about is the *convention* -- w = cos(theta/2) with no
+ # canonicalisation to w >= 0 -- and that part is exact at every dtype, so w is compared
+ # exactly and the vector part is bounded by a few ulp instead.
+ assert full_turn[0].item() == -1.0, (
+ f"axis_angle_to_quaternion no longer returns the w < 0 half at theta = 2*pi "
+ f"(got w = {full_turn[0].item()!r}); a canonicalising implementation would give +1"
+ )
+ vector_tol = 4 * torch.finfo(dtype).eps
+ assert full_turn[1:].abs().max().item() <= vector_tol, (
+ f"axis_angle_to_quaternion vector part at theta = 2*pi is no longer zero to a few ulp "
+ f"(got {full_turn[1:].tolist()}, tolerance {vector_tol})"
+ )
+
+ off_axis = kornia.geometry.conversions.axis_angle_to_quaternion(
+ torch.tensor([1.0690449676496976, 2.138089935299395, 3.2071349029490928], device=device, dtype=dtype)
+ )
+ self.assert_close(
+ off_axis,
+ torch.tensor(
+ [-0.4161468365471424, 0.24301995956120354, 0.48603991912240707, 0.7290598786836107],
+ device=device,
+ dtype=dtype,
+ ),
+ )
+
+ def test_convention_axis_angle_quaternion_roundtrip_is_exact_in_float64(self, device):
+ # Convention pin: axis_angle_to_quaternion and quaternion_to_axis_angle are exact inverses
+ # in float64 over the whole [0, pi] range, including the two singular points theta = 0 and
+ # theta = pi. This is what separates the quaternion leg from the matrix leg: the same
+ # round-trip through axis_angle_to_rotation_matrix is only accurate to ~1e-6 even in
+ # float64 (see TestRotationMatrixToAngleAxis.test_convention_axis_angle_roundtrip_
+ # tolerance_is_1e_6_in_float64), so "the round-trip is exact" is a statement about this
+ # pair only. float64 is hardcoded and the dtype fixture dropped because exactness is a
+ # float64-only claim; MPS is skipped visibly because it has no float64 at all.
+ # Snippet used to generate the inputs (stdlib only):
+ # import math
+ # n = math.sqrt(14.0); axis = (1 / n, 2 / n, 3 / n)
+ # [[theta * a for a in axis] for theta in (0.0, 1e-3, 0.7, math.pi)]
+ # Measured max |roundtrip - input| at those four thetas (torch 2.9.1, cpu float64):
+ # 0.0, 2.168404344971009e-19, 0.0, 0.0 -- so atol 1e-12 is ~7 orders above the worst
+ # observed error and ~6 orders below the 1e-6 the matrix leg would give. 1e-12 rather
+ # than something tighter because this composes two atan2/sqrt chains and no CUDA job
+ # exists to tell us what they cost there.
+ _skip_if_dtype_unavailable(device, torch.float64)
+
+ axis_angle = torch.tensor(
+ [
+ [0.0, 0.0, 0.0],
+ [0.0002672612419124244, 0.0005345224838248488, 0.0008017837257372733],
+ [0.18708286933869706, 0.3741657386773941, 0.5612486080160912],
+ [0.839625954181357, 1.679251908362714, 2.518877862544071],
+ ],
+ device=device,
+ dtype=torch.float64,
+ )
+
+ roundtrip = kornia.geometry.conversions.quaternion_to_axis_angle(
+ kornia.geometry.conversions.axis_angle_to_quaternion(axis_angle)
+ )
+
+ self.assert_close(roundtrip, axis_angle, atol=1e-12, rtol=0.0)
+
+ # Convention pin for the four deprecated aliases (they have no test class and no docstring of
+ # their own; this class is named after one of them). Each still works and is a thin wrapper:
+ # it emits a DeprecationWarning naming both the old and the new symbol, and returns output
+ # that is bit-identical to the replacement's. The replacement, not the alias, is where the
+ # Convention block lives.
+ # The call is wrapped in warnings.catch_warnings() because invoking a kornia deprecated symbol
+ # rewrites the process-global DeprecationWarning filters; pytest.warns alone does not restore
+ # them, so without the wrapper this pin would leak filter state into every later test.
+ # Snippet used to generate expected (torch only):
+ # import warnings, kornia.geometry.conversions as C
+ # with warnings.catch_warnings(record=True) as w:
+ # warnings.simplefilter("always")
+ # out = C.angle_axis_to_quaternion(torch.tensor([0.1, 0.2, 0.3]))
+ # w[0].category, str(w[0].message) -> DeprecationWarning, 'Since kornia 0.7.0 the
+ # `angle_axis_to_quaternion` is deprecated in favor of `axis_angle_to_quaternion`.'
+ # torch.equal(out, C.axis_angle_to_quaternion(torch.tensor([0.1, 0.2, 0.3]))) -> True
+ @pytest.mark.parametrize(
+ ("deprecated_name", "replacement_name", "arg"),
+ [
+ ("angle_axis_to_rotation_matrix", "axis_angle_to_rotation_matrix", [[0.1, 0.2, 0.3]]),
+ (
+ "rotation_matrix_to_angle_axis",
+ "rotation_matrix_to_axis_angle",
+ [
+ [0.5357142857142858, -0.6229365034008422, 0.5700529070291328],
+ [0.765793646257985, 0.6428571428571429, -0.01716931065742361],
+ [-0.3557671927434186, 0.4457407392288521, 0.8214285714285714],
+ ],
+ ),
+ ("quaternion_to_angle_axis", "quaternion_to_axis_angle", [1.0, 2.0, 3.0, 4.0]),
+ ("angle_axis_to_quaternion", "axis_angle_to_quaternion", [0.1, 0.2, 0.3]),
+ ],
+ )
+ def test_convention_deprecated_alias_warns_and_matches_replacement(
+ self, device, dtype, deprecated_name, replacement_name, arg
+ ):
+ deprecated = getattr(kornia.geometry.conversions, deprecated_name)
+ replacement = getattr(kornia.geometry.conversions, replacement_name)
+ tensor = torch.tensor(arg, device=device, dtype=dtype)
+
+ expected = replacement(tensor)
+
+ with warnings.catch_warnings():
+ warnings.simplefilter("always")
+ with pytest.warns(
+ DeprecationWarning, match=f"`{deprecated_name}` is deprecated in favor of `{replacement_name}`"
+ ):
+ actual = deprecated(tensor)
+
+ assert torch.equal(actual, expected)
+
+ def test_wart_integer_input_returns_the_zero_quaternion_3948(self, device):
+ # Wart pin for kornia#3948: axis_angle_to_quaternion allocates its output buffer with
+ # dtype=axis_angle.dtype, so an integer input gets an int64 buffer and every component is
+ # truncated to 0. The function returns tensor([0, 0, 0, 0]) -- not merely a wrong
+ # quaternion but a zero-norm one, with no error and no warning. If this fails, #3948 was
+ # (partly) fixed -- remove this pin. NOT a contract that integer input must keep returning
+ # zeros.
+ # There is deliberately NO companion strict xfail here, unlike every other bug pinned in
+ # this batch: the intended behavior is genuinely undecided. A fix could promote to float
+ # and return the float reference in the snippet below, or it could raise TypeError the way
+ # a dtype guard would; an assertion-shaped xfail can express only the first, so it would
+ # stay silently XFAIL forever if the fix chose to raise. Same reasoning, and same shape, as
+ # TestRadDegConversions.test_wart_integer_input_truncates_pi_to_3_3937.
+ # Snippet used to generate expected (torch + stdlib, executed on cpu):
+ # axis_angle_to_quaternion(torch.tensor([1, 0, 0])) -> tensor([0, 0, 0, 0]), int64
+ # (torch.int32 and torch.int16 inputs give [0, 0, 0, 0] in their own dtype too)
+ # axis_angle_to_quaternion(torch.tensor([1., 0., 0.])) ->
+ # [0.8775825500488281, 0.4794255495071411, 0.0, 0.0] (float32 reference)
+ # math.cos(0.5), math.sin(0.5) -> (0.8775825618903728, 0.479425538604203)
+ out = kornia.geometry.conversions.axis_angle_to_quaternion(torch.tensor([1, 0, 0], device=device))
+
+ assert out.dtype == torch.int64, "kornia#3948: integer input no longer keeps its integer output buffer"
+ assert out.tolist() == [0, 0, 0, 0], "kornia#3948: integer input no longer truncates to the zero quaternion"
+
+ @pytest.mark.xfail(
+ raises=AssertionError,
+ reason="unguarded sqrt(0) in the axis-angle/quaternion pair makes the gradient NaN at the "
+ "identity rotation β€” kornia#3949",
+ strict=True,
+ )
+ @pytest.mark.parametrize(
+ ("op_name", "arg"),
+ [("quaternion_to_axis_angle", [1.0, 0.0, 0.0, 0.0]), ("axis_angle_to_quaternion", [0.0, 0.0, 0.0])],
+ )
+ def test_convention_gradients_at_the_identity_are_finite_3949(self, device, op_name, arg):
+ # Intended behavior: both directions of the axis-angle/quaternion pair are differentiable
+ # at the identity rotation -- the point every optimiser initialises at and converges to.
+ # They are not: each takes an unguarded sqrt of a quantity that is exactly 0 there, so the
+ # backward pass divides by 0 and the gradient is NaN for the whole input
+ # (quaternion_to_axis_angle at q = (1,0,0,0) and axis_angle_to_quaternion at aa = (0,0,0)).
+ # axis_angle_to_rotation_matrix is the in-kornia template for the fix: at the same point it
+ # returns a finite gradient [0, 0, 0] because it clamps theta2 to 1e-12 before the sqrt,
+ # with the comment "clamping to ensure no nan gradients". Away from the identity both
+ # gradients are already finite (measured at q = (0.938, 0.147, 0.196, 0.245):
+ # [-1.1751557857766646, 1.9227726795680562, 1.8829361000064004, 1.8430995204447442]).
+ # Both legs live in this class so the pair stays one edit even though
+ # quaternion_to_axis_angle is exercised by TestQuaternionToAngleAxis. float64 is hardcoded
+ # and the dtype fixture dropped because gradient claims in this file are float64 claims
+ # (see test_rad2deg_gradcheck); the NaN is not float64-specific -- float32 gives NaN too.
+ # Marked xfail(strict=True) so fixing #3949 makes both cases XPASS and forces this mark
+ # out. Companion wart: test_wart_gradients_at_the_identity_are_nan_3949.
+ _skip_if_dtype_unavailable(device, torch.float64)
+
+ op = getattr(kornia.geometry.conversions, op_name)
+ x = torch.tensor(arg, device=device, dtype=torch.float64, requires_grad=True)
+
+ op(x).sum().backward()
+
+ assert torch.isfinite(x.grad).all(), f"kornia#3949: {op_name} has a non-finite gradient at the identity"
+
+ @pytest.mark.parametrize(
+ ("op_name", "arg"),
+ [("quaternion_to_axis_angle", [1.0, 0.0, 0.0, 0.0]), ("axis_angle_to_quaternion", [0.0, 0.0, 0.0])],
+ )
+ def test_wart_gradients_at_the_identity_are_nan_3949(self, device, op_name, arg):
+ # Wart pin for kornia#3949, companion to the strict xfail above: assert that the gradient
+ # is CURRENTLY all-NaN at the identity rotation. Two cells because the two functions have
+ # independent sqrt guards -- clamping inside quaternion_to_axis_angle does nothing for
+ # axis_angle_to_quaternion and vice versa, so a half fix flips exactly one cell while the
+ # xfail's other case stays silently XFAIL. If either fails, #3949 was (partly) fixed --
+ # remove the corresponding case here and flip/remove the strict xfail above. NOT a contract
+ # that these gradients must stay NaN.
+ # Snippet used to generate expected (torch only, executed on cpu at float64 and float32):
+ # q = torch.tensor([1., 0., 0., 0.], dtype=torch.float64, requires_grad=True)
+ # quaternion_to_axis_angle(q).sum().backward(); q.grad -> [nan, nan, nan, nan]
+ # a = torch.zeros(3, dtype=torch.float64, requires_grad=True)
+ # axis_angle_to_quaternion(a).sum().backward(); a.grad -> [nan, nan, nan]
+ # axis_angle_to_rotation_matrix(torch.zeros(1, 3, dtype=torch.float64, requires_grad=True))
+ # .sum().backward() -> [[0.0, 0.0, 0.0]] (finite: the clamped-theta2 reference)
+ _skip_if_dtype_unavailable(device, torch.float64)
+
+ op = getattr(kornia.geometry.conversions, op_name)
+ x = torch.tensor(arg, device=device, dtype=torch.float64, requires_grad=True)
+
+ op(x).sum().backward()
+
+ assert torch.isnan(x.grad).all(), f"kornia#3949: {op_name} no longer has an all-NaN gradient at the identity"
+
class TestQuaternionToAngleAxis(BaseTester):
def test_smoke(self, device, dtype):
@@ -196,6 +468,76 @@ class TestQuaternionToAngleAxis(BaseTester):
# evaluate function gradient
self.gradcheck(partial(kornia.geometry.conversions.quaternion_to_axis_angle), (quaternion,))
+ def test_convention_double_cover_q_and_minus_q_give_the_same_axis_angle(self, device, dtype):
+ # Convention pin: q and -q are the same rotation (the unit quaternions double-cover SO(3)),
+ # and quaternion_to_axis_angle collapses the two onto one bit-identical vector -- it picks
+ # the representative with |theta| <= pi rather than propagating the input's sign. torch.equal
+ # rather than assert_close because the agreement is exact, not approximate: measured max
+ # difference is 0.0 over 500 random float64 quaternions (seeded torch.Generator(6)),
+ # bit-identical in 500/500 of them, and at float32/float16/bfloat16 for the pinned input.
+ # Pinned on a non-unit, non-axis-aligned quaternion so no symmetry can carry the assertion.
+ # Snippet used to generate expected (stdlib only, q = (1, 2, 3, 4) normalised):
+ # import math
+ # u = [v / math.sqrt(30.0) for v in (1.0, 2.0, 3.0, 4.0)]
+ # nv = math.sqrt(u[1] ** 2 + u[2] ** 2 + u[3] ** 2)
+ # theta = 2 * math.atan2(nv, u[0])
+ # [theta * u[i + 1] / nv for i in range(3)]
+ # -> [1.03038058532817, 1.5455708779922552, 2.06076117065634]
+ quaternion = torch.tensor([1.0, 2.0, 3.0, 4.0], device=device, dtype=dtype)
+
+ axis_angle = kornia.geometry.conversions.quaternion_to_axis_angle(quaternion)
+
+ self.assert_close(
+ axis_angle,
+ torch.tensor([1.03038058532817, 1.5455708779922552, 2.06076117065634], device=device, dtype=dtype),
+ )
+ assert torch.equal(kornia.geometry.conversions.quaternion_to_axis_angle(-quaternion), axis_angle)
+
+ # Second cell: at exactly w = 0 the collapse does NOT happen, so the docstring's "w != 0"
+ # qualifier is falsifiable here rather than merely asserted. The branch test is
+ # `cos_theta < 0.0` and `-0.0 < 0.0` is False, so q and -q take the same branch and the
+ # sign of the vector part passes straight through, making the two outputs exact negations.
+ # The first cell cannot catch this: its input has w > 0, and no random sweep can sample
+ # w = 0. Both outputs describe the same rotation (a half turn about +x and about -x):
+ # axis_angle_to_rotation_matrix of [pi, 0, 0] and of [-pi, 0, 0] differ by 2.45e-16 in
+ # float64. The exact negation holds at every dtype: over 400000 random quaternions with the
+ # real part zeroed, cast to float64/float32/float16/bfloat16 and restricted to inputs and
+ # outputs that are finite in that dtype, there are 0 mismatches each.
+ # Snippet used to generate expected (stdlib only, v = (0.6, 0.8, 0.0), |v| = 1, w = 0):
+ # import math
+ # theta = 2 * math.atan2(1.0, 0.0) # pi
+ # [theta * a for a in (0.6, 0.8, 0.0)]
+ # -> [1.8849555921538759, 2.5132741228718345, 0.0]
+ half_turn = torch.tensor([0.0, 0.6, 0.8, 0.0], device=device, dtype=dtype)
+
+ half_turn_axis_angle = kornia.geometry.conversions.quaternion_to_axis_angle(half_turn)
+
+ self.assert_close(
+ half_turn_axis_angle,
+ torch.tensor([1.8849555921538759, 2.5132741228718345, 0.0], device=device, dtype=dtype),
+ )
+ assert torch.equal(kornia.geometry.conversions.quaternion_to_axis_angle(-half_turn), -half_turn_axis_angle), (
+ "quaternion_to_axis_angle no longer returns exact negations at w = 0"
+ )
+
+ def test_convention_quaternion_to_axis_angle_is_scale_invariant(self, device, dtype):
+ # Convention pin (quaternion_to_axis_angle has no test class under its own name; this class
+ # is the one that exercises it): the function does not require -- and does not check -- a
+ # unit quaternion. It is homogeneous in its input, so scaling the whole quaternion leaves
+ # the axis-angle vector bit-identical. The scale factors are powers of two so that the
+ # scaling itself is exact in binary floating point at every dtype; the invariance is a
+ # property of atan2 plus the 2*theta/||v|| factor, not of the particular numbers (verified
+ # bit-identical in 500/500 random float64 quaternions, seeded torch.Generator(7), for both
+ # factors -- a non-power-of-two factor such as 3 is invariant to rounding only, 82/500).
+ # Contrast quaternion_exp_to_log, which does NOT normalise and is silently wrong on a
+ # non-unit input.
+ quaternion = torch.tensor([1.0, 2.0, 3.0, 4.0], device=device, dtype=dtype)
+
+ axis_angle = kornia.geometry.conversions.quaternion_to_axis_angle(quaternion)
+
+ assert torch.equal(kornia.geometry.conversions.quaternion_to_axis_angle(2.0 * quaternion), axis_angle)
+ assert torch.equal(kornia.geometry.conversions.quaternion_to_axis_angle(0.5 * quaternion), axis_angle)
+
class TestRotationMatrixToQuaternion(BaseTester):
@pytest.mark.parametrize("batch_size", (1, 3, 8))
@@ -295,6 +637,165 @@ class TestRotationMatrixToQuaternion(BaseTester):
self.assert_close(actual, expected)
+ def test_convention_w_is_not_canonicalised_to_non_negative(self, device, dtype):
+ # Convention pin: rotation_matrix_to_quaternion picks ONE of the two quaternions that
+ # represent the input rotation, and the rule is NOT "return w >= 0". The branch is selected
+ # by the sign of the trace:
+ # trace > 0 -> the returned w is >= 0 (0/325 negative over random rotations);
+ # trace <= 0 -> the *dominant* of x, y, z is forced >= 0 and w may come back NEGATIVE
+ # (6042 of the 12158 such cases in a sweep of 20000 random float64
+ # rotations -- about half of them, not all).
+ # trace = 1 + 2 * cos(theta), so trace <= 0 is exactly theta >= 120 degrees: a caller that
+ # assumes a non-negative real part is safe below 120 degrees and wrong for about half of the
+ # rotations above it. Both branches are pinned here, each with a rotation whose "natural"
+ # quaternion has the opposite sign of w, which is exactly what a canonicalising
+ # implementation would not reproduce.
+ # Expected values are the true unit quaternions (computed with stdlib below), not the
+ # function's own output: the returned components carry an extra ~1e-9 from the default
+ # eps added inside the sqrt, which bare assert_close absorbs and no pin here asserts.
+ # Snippet used to generate the matrices and the expected quaternions (stdlib only):
+ # import math
+ # n = math.sqrt(14.0)
+ # R = I + sin(theta) * K + (1 - cos(theta)) * K @ K # Rodrigues, K = skew(axis)
+ # axis, theta = (1 / n, 2 / n, -3 / n), math.radians(170.0) # trace -0.9696155060244165
+ # R -> [[-0.8430357706541933, 0.4227722475733091, -0.3324970918358584],
+ # [ 0.14431568185875046, -0.4177198235801487, -0.8970413217671823],
+ # [-0.5181348023122309, -0.8042224665289962, 0.29114008820992554]]
+ # the two representatives are +-[0.08715574274765814, 0.2662442321985726,
+ # 0.5324884643971451, -0.7987326965957178]; |z| dominates, so the one with z >= 0
+ # is returned and its w is negative
+ # axis, theta = (1 / n, 2 / n, 3 / n), math.radians(60.0) # trace 2.0
+ # R -> [[ 0.5357142857142858, -0.6229365034008422, 0.5700529070291328],
+ # [ 0.765793646257985, 0.6428571428571429, -0.01716931065742361],
+ # [-0.3557671927434186, 0.4457407392288521, 0.8214285714285714]]
+ # representatives +-[0.8660254037844387, 0.13363062095621217, 0.26726124191242434,
+ # 0.40089186286863654]; the w >= 0 one is returned
+ rot_trace_negative = torch.tensor(
+ [
+ [-0.8430357706541933, 0.4227722475733091, -0.3324970918358584],
+ [0.14431568185875046, -0.4177198235801487, -0.8970413217671823],
+ [-0.5181348023122309, -0.8042224665289962, 0.29114008820992554],
+ ],
+ device=device,
+ dtype=dtype,
+ )
+ quaternion_trace_negative = kornia.geometry.conversions.rotation_matrix_to_quaternion(rot_trace_negative)
+ self.assert_close(
+ quaternion_trace_negative,
+ torch.tensor(
+ [-0.08715574274765814, -0.2662442321985726, -0.5324884643971451, 0.7987326965957178],
+ device=device,
+ dtype=dtype,
+ ),
+ )
+ assert quaternion_trace_negative[0] < 0.0
+ assert quaternion_trace_negative[3] > 0.0
+
+ rot_trace_positive = torch.tensor(
+ [
+ [0.5357142857142858, -0.6229365034008422, 0.5700529070291328],
+ [0.765793646257985, 0.6428571428571429, -0.01716931065742361],
+ [-0.3557671927434186, 0.4457407392288521, 0.8214285714285714],
+ ],
+ device=device,
+ dtype=dtype,
+ )
+ quaternion_trace_positive = kornia.geometry.conversions.rotation_matrix_to_quaternion(rot_trace_positive)
+ self.assert_close(
+ quaternion_trace_positive,
+ torch.tensor(
+ [0.8660254037844387, 0.13363062095621217, 0.26726124191242434, 0.40089186286863654],
+ device=device,
+ dtype=dtype,
+ ),
+ )
+ assert quaternion_trace_positive[0] > 0.0
+
+ @pytest.mark.xfail(
+ raises=AssertionError,
+ reason="rotation_matrix_to_quaternion adds eps inside the sqrt, so the result is never a "
+ "unit quaternion β€” kornia#3951",
+ strict=True,
+ )
+ def test_convention_returns_a_unit_quaternion_3951(self, device):
+ # Intended behavior: the quaternion returned for an exact rotation matrix is a unit
+ # quaternion to the precision of the input dtype. It never is in float64: the default
+ # eps = 1e-8 is added *inside* the sqrt that builds the components, so every returned
+ # quaternion is inflated -- over 20000 random float64 rotations not one comes back exactly
+ # unit. Measured on the identity in float64 (torch 2.9.1, cpu):
+ # rotation_matrix_to_quaternion(eye(3)) -> [1.0000000012499999, 0.0, 0.0, 0.0]
+ # ||q|| - 1 -> 1.2499998813808588e-09
+ # rotation_matrix_to_quaternion(eye(3), eps=0.0) -> [1.0, 0.0, 0.0, 0.0] (exactly unit)
+ # and the worst |β€–qβ€– - 1| over 200 random exact rotations is 2.212899197218121e-09, so
+ # atol 1e-12 sits three orders below the deviation and eight above the float64 noise floor.
+ # float64 is hardcoded and the dtype fixture dropped because a 1.25e-09 inflation is
+ # invisible at every other dtype -- float32, float16 and bfloat16 all return exactly
+ # [1, 0, 0, 0] for the identity -- so a dtype-fixture version would XPASS three quarters of
+ # the time and blow up the strict mark for the wrong reason. MPS is skipped visibly since
+ # it has no float64 at all. Marked xfail(strict=True) so fixing #3951 makes this XPASS and
+ # forces the mark out. Companion wart: test_wart_eps_inside_the_sqrt_inflates_the_quaternion_3951.
+ _skip_if_dtype_unavailable(device, torch.float64)
+
+ quaternion = kornia.geometry.conversions.rotation_matrix_to_quaternion(
+ torch.eye(3, device=device, dtype=torch.float64)
+ )
+
+ assert abs(quaternion.norm().item() - 1.0) < 1e-12, (
+ "kornia#3951: rotation_matrix_to_quaternion did not return a unit quaternion"
+ )
+
+ def test_wart_eps_inside_the_sqrt_inflates_the_quaternion_3951(self, device):
+ # Wart pin for kornia#3951, companion to the strict xfail above: assert the CURRENT
+ # inflated components. Three cells, each discriminating a different fix shape:
+ # (0) the eps default itself is still 1e-8 -- the other two cells pass eps explicitly
+ # (house rule) so they cannot see a re-tuned default, which would otherwise be an
+ # invisible way to half-fix this;
+ # (1) eps=1e-8 passed explicitly still inflates the identity to 1.0000000012499999 --
+ # flips when eps moves out of the sqrt, or when the output is normalised at the end,
+ # but NOT when only the default is changed;
+ # (2) eps=0.0 returns exactly [1, 0, 0, 0] -- the control that proves eps is the cause;
+ # flips if the formula is restructured so that eps=0 no longer gives the exact
+ # answer (e.g. a clamp- or branch-shaped rewrite).
+ # If any cell fails, #3951 was (partly) fixed -- flip/remove the strict xfail above. NOT a
+ # contract that rotation_matrix_to_quaternion must keep returning a non-unit quaternion.
+ # float64 is hardcoded for the same reason as the xfail: at float32 and below the identity
+ # already comes back as exactly [1, 0, 0, 0] and there is nothing to pin.
+ # Snippet used to generate expected (torch only, executed on cpu float64):
+ # rotation_matrix_to_quaternion(torch.eye(3, dtype=torch.float64), eps=1e-8)
+ # -> [1.0000000012499999, 0.0, 0.0, 0.0]
+ # rotation_matrix_to_quaternion(torch.eye(3, dtype=torch.float64), eps=0.0)
+ # -> [1.0, 0.0, 0.0, 0.0]
+ # atol 1e-11 on the inflated cell sits two orders below the 1.25e-9 inflation being
+ # discriminated (a fix still flips it red) and four above the 2.2e-16 ulp of 1.0, so a
+ # one-ulp reassociation of the trace+1+eps sum (refactor, fusion, fma) cannot. The eps=0.0
+ # cell stays exact: 3+1+0 is 4 in every association.
+ _skip_if_dtype_unavailable(device, torch.float64)
+
+ rotation_matrix_to_quaternion = kornia.geometry.conversions.rotation_matrix_to_quaternion
+ assert inspect.signature(rotation_matrix_to_quaternion).parameters["eps"].default == 1e-8, (
+ "kornia#3951: the eps default moved, so the literals pinned here no longer describe the default call"
+ )
+
+ identity = torch.eye(3, device=device, dtype=torch.float64)
+
+ inflated = rotation_matrix_to_quaternion(identity, eps=1e-8)
+ exact = rotation_matrix_to_quaternion(identity, eps=0.0)
+
+ assert_close(
+ inflated,
+ torch.tensor([1.0000000012499999, 0.0, 0.0, 0.0], device=device, dtype=torch.float64),
+ atol=1e-11,
+ rtol=0.0,
+ msg=_issue_msg("kornia#3951: eps=1e-8 no longer inflates the identity quaternion"),
+ )
+ assert_close(
+ exact,
+ torch.tensor([1.0, 0.0, 0.0, 0.0], device=device, dtype=torch.float64),
+ atol=0.0,
+ rtol=0.0,
+ msg=_issue_msg("kornia#3951: eps=0.0 no longer returns the exact unit quaternion"),
+ )
+
class TestQuaternionToRotationMatrix(BaseTester):
@pytest.mark.parametrize("batch_dims", ((), (1,), (3,), (8,), (1, 1), (5, 6)))
@@ -342,6 +843,301 @@ class TestQuaternionToRotationMatrix(BaseTester):
self.assert_close(actual, expected)
+ def test_convention_quaternion_component_order_is_w_x_y_z(self, device, dtype):
+ # Convention pin -- THE trap of this module: quaternions are (w, x, y, z), real part FIRST.
+ # (1, 0, 0, 0) is the identity. The (x, y, z, w) misreading of the same four numbers,
+ # (0, 0, 0, 1), does not raise and does not return anything obviously wrong -- it returns
+ # diag(-1, -1, 1), a perfectly valid 180-degree rotation about z. That is why the
+ # counter-literal is pinned alongside the identity: an order swap is silent, and only the
+ # second assertion catches it.
+ # Snippet used to generate expected (stdlib only, R = I + 2*w*K + 2*K@K with K = skew(v)):
+ # q = (1, 0, 0, 0) -> v = 0, K = 0 -> R = I
+ # q = (0, 0, 0, 1) -> w = 0, v = (0, 0, 1)
+ # K @ K = diag(-1, -1, 0) -> R = I + 2 * diag(-1, -1, 0) = diag(-1, -1, 1)
+ real_part_first = kornia.geometry.conversions.quaternion_to_rotation_matrix(
+ torch.tensor([1.0, 0.0, 0.0, 0.0], device=device, dtype=dtype)
+ )
+ self.assert_close(_undo_3954_upcast(real_part_first, dtype), torch.eye(3, device=device, dtype=dtype))
+
+ read_as_xyzw = kornia.geometry.conversions.quaternion_to_rotation_matrix(
+ torch.tensor([0.0, 0.0, 0.0, 1.0], device=device, dtype=dtype)
+ )
+ self.assert_close(
+ _undo_3954_upcast(read_as_xyzw, dtype),
+ torch.diag(torch.tensor([-1.0, -1.0, 1.0], device=device, dtype=dtype)),
+ )
+
+ def test_convention_double_cover_q_and_minus_q_give_identical_matrices(self, device, dtype):
+ # Convention pin: the unit quaternions double-cover SO(3), and every term of the rotation
+ # matrix is a product of two quaternion components, so negating the whole quaternion leaves
+ # the matrix BIT-identical -- not merely close. torch.equal, not assert_close: the measured
+ # max difference is exactly 0.0, and the identity held in 500/500 random float64 draws
+ # (seeded torch.Generator(6)) as well as at float32/float16/bfloat16 for the pinned input.
+ # The input is non-unit and non-axis-aligned so the pin cannot pass by symmetry.
+ quaternion = torch.tensor([1.0, 2.0, 3.0, 4.0], device=device, dtype=dtype)
+
+ rot = kornia.geometry.conversions.quaternion_to_rotation_matrix(quaternion)
+
+ assert torch.equal(kornia.geometry.conversions.quaternion_to_rotation_matrix(-quaternion), rot)
+
+ def test_convention_non_unit_quaternion_is_normalized_internally(self, device, dtype):
+ # Convention pin: quaternion_to_rotation_matrix calls normalize_quaternion on its input
+ # first, so a non-unit quaternion is accepted silently and yields the same rotation as its
+ # normalised form -- the docstring never says so. Pinned two ways: the returned matrix
+ # equals the one built from the unit quaternion (stdlib literal below), and rescaling the
+ # input leaves the output bit-identical. The scale factors are powers of two so that the
+ # scaling is exact in binary floating point at every dtype (0.001 is not: at bfloat16
+ # 0.001 * q rounds differently and the matrices then differ by 1.6e-2).
+ # Snippet used to generate expected (stdlib only, q = (1, 2, 3, 4) normalised):
+ # import math
+ # u = [v / math.sqrt(30.0) for v in (1.0, 2.0, 3.0, 4.0)]
+ # nv = math.sqrt(u[1] ** 2 + u[2] ** 2 + u[3] ** 2); theta = 2 * math.atan2(nv, u[0])
+ # Rodrigues([u[i + 1] / nv for i in range(3)], theta) ->
+ # [[-0.666666666666667, 0.13333333333333341, 0.7333333333333334],
+ # [ 0.6666666666666667, -0.3333333333333337, 0.6666666666666669],
+ # [ 0.3333333333333335, 0.9333333333333335, 0.1333333333333333]]
+ quaternion = torch.tensor([1.0, 2.0, 3.0, 4.0], device=device, dtype=dtype)
+
+ rot = kornia.geometry.conversions.quaternion_to_rotation_matrix(quaternion)
+
+ expected = torch.tensor(
+ [
+ [-0.666666666666667, 0.13333333333333341, 0.7333333333333334],
+ [0.6666666666666667, -0.3333333333333337, 0.6666666666666669],
+ [0.3333333333333335, 0.9333333333333335, 0.1333333333333333],
+ ],
+ device=device,
+ dtype=dtype,
+ )
+ self.assert_close(_undo_3954_upcast(rot, dtype), expected)
+
+ assert torch.equal(kornia.geometry.conversions.quaternion_to_rotation_matrix(2.0 * quaternion), rot)
+ assert torch.equal(kornia.geometry.conversions.quaternion_to_rotation_matrix(0.0009765625 * quaternion), rot)
+
+ def test_convention_normalize_quaternion_is_l2_over_the_last_axis(self, device, dtype):
+ # Convention pin (normalize_quaternion has no test class of its own; this is its nearest
+ # sibling -- quaternion_to_rotation_matrix calls it on every input): it is a plain L2
+ # normalisation of the last axis and nothing more. It does NOT reorder, and it does NOT
+ # canonicalise the sign, so the whole vector keeps its sign. That makes it the one symbol
+ # in this file whose "(x, y, z, w) or (w, x, y, z)" docstring phrasing is actually true:
+ # the same four numbers in the other order come back scaled by the same factor, which the
+ # third assertion pins.
+ # Snippet used to generate expected (stdlib only):
+ # import math
+ # [v / math.sqrt(30.0) for v in (1.0, 2.0, 3.0, 4.0)]
+ # -> [0.18257418583505536, 0.3651483716701107, 0.5477225575051661, 0.7302967433402214]
+ expected = torch.tensor(
+ [0.18257418583505536, 0.3651483716701107, 0.5477225575051661, 0.7302967433402214],
+ device=device,
+ dtype=dtype,
+ )
+
+ out = kornia.geometry.conversions.normalize_quaternion(
+ torch.tensor([1.0, 2.0, 3.0, 4.0], device=device, dtype=dtype)
+ )
+ self.assert_close(out, expected)
+
+ out_negated = kornia.geometry.conversions.normalize_quaternion(
+ torch.tensor([-1.0, -2.0, -3.0, -4.0], device=device, dtype=dtype)
+ )
+ self.assert_close(out_negated, -expected)
+
+ out_reversed = kornia.geometry.conversions.normalize_quaternion(
+ torch.tensor([4.0, 3.0, 2.0, 1.0], device=device, dtype=dtype)
+ )
+ self.assert_close(out_reversed, expected.flip(0))
+
+ @pytest.mark.xfail(
+ raises=AssertionError,
+ reason="normalize_quaternion divides by max(β€–qβ€–, eps), so below eps it returns a non-unit "
+ "quaternion β€” kornia#3952",
+ strict=True,
+ )
+ def test_convention_normalize_quaternion_is_unit_below_eps_3952(self, device, dtype):
+ # Intended behavior: normalize_quaternion returns a unit quaternion, or refuses. It does
+ # neither for a small input: it is F.normalize(q, p=2, dim=-1, eps=eps), which divides by
+ # max(β€–qβ€–, eps), so any quaternion with β€–qβ€– < eps comes back scaled by β€–qβ€–/eps instead of
+ # to unit length -- silently, with the docstring saying only "small value to avoid division
+ # by zero". At β€–qβ€– = 1e-13 with the default eps = 1e-12 the output has norm exactly 0.1.
+ # This pin is placed in this class because normalize_quaternion has no test class of its
+ # own and quaternion_to_rotation_matrix is the function that calls it on every input (the
+ # same placement as test_convention_normalize_quaternion_is_l2_over_the_last_axis above);
+ # the consequence for that caller is pinned by
+ # test_wart_zero_quaternion_becomes_the_identity_matrix_3952 below. Marked xfail(strict=True)
+ # 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)"
+ )
+
+ quaternion = torch.tensor([1e-13, 0.0, 0.0, 0.0], device=device, dtype=dtype)
+
+ out = kornia.geometry.conversions.normalize_quaternion(quaternion, eps=1e-12)
+
+ assert abs(out.norm().item() - 1.0) < 1e-2, (
+ "kornia#3952: normalize_quaternion returned a non-unit quaternion below eps"
+ )
+
+ def test_wart_normalize_quaternion_scales_by_norm_over_eps_3952(self, device, dtype):
+ # Wart pin for kornia#3952, companion to the strict xfail above: assert the CURRENT
+ # 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);
+ # (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.
+ # If either fails, #3952 was (partly) fixed -- flip/remove the strict xfail above. NOT a
+ # contract that sub-eps quaternions must keep these values. eps is passed explicitly at
+ # every call site so the literals do not silently track a later change of the default.
+ # Snippet used to generate expected (torch only, executed on cpu at float64):
+ # normalize_quaternion(torch.tensor([1e-13, 0., 0., 0.], dtype=torch.float64), eps=1e-12)
+ # -> [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)"
+ )
+
+ 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"),
+ )
+ assert_close(
+ zero,
+ torch.zeros(4, device=device, dtype=dtype),
+ msg=_issue_msg("kornia#3952: the zero quaternion no longer passes through unchanged"),
+ )
+
+ def test_wart_normalize_quaternion_without_eps_divides_by_zero_3952(self, device, dtype):
+ # Wart pin for kornia#3952, cell (3) and the control for the two cells above: with eps=0
+ # the zero quaternion produces NaN, which pins the *mechanism* (normalize_quaternion is a
+ # plain division by max(β€–qβ€–, eps), nothing more) rather than the symptom. It flips only if
+ # that division is replaced by a clamp- or branch-shaped rewrite, which is how an eps-only
+ # fix is told apart from a restructuring one. If it fails, #3952 was (partly) fixed --
+ # flip/remove the strict xfail above. NOT a contract that eps=0 must keep producing NaN.
+ # It lives in its own test rather than as a third cell of the wart above because on MPS the
+ # two cannot share a process: this torch build caches clamp's scalar min per shape/dtype on
+ # MPS, so an earlier normalize_quaternion(..., eps=1e-12) on a (4,) float32 tensor makes
+ # the later eps=0.0 call reuse 1e-12 and return zeros instead of NaN (executed: cpu gives
+ # [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):
+ # 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)
+
+ assert torch.isnan(out).all(), "kornia#3952: the eps=0 division by the zero norm is no longer NaN"
+
+ def test_wart_zero_quaternion_becomes_the_identity_matrix_3952(self, device, dtype):
+ # Wart pin for the downstream consequence of kornia#3952: because normalize_quaternion
+ # returns the zero vector unchanged for a zero input (cell 2 of the wart above),
+ # quaternion_to_rotation_matrix(zeros(4)) evaluates 1 - 0 on the diagonal and returns the
+ # IDENTITY -- the zero quaternion, which is not a rotation at all, silently becomes "no
+ # rotation". Pinned separately from the normalize_quaternion cells because it flips under
+ # two independent fixes: fixing #3952 in normalize_quaternion, or giving
+ # 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):
+ # 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 = _undo_3954_upcast(
+ kornia.geometry.conversions.quaternion_to_rotation_matrix(torch.zeros(4, device=device, dtype=dtype)), dtype
+ )
+
+ assert_close(
+ out,
+ torch.eye(3, device=device, dtype=dtype),
+ msg=_issue_msg("kornia#3952: the zero quaternion no longer maps to the identity matrix"),
+ )
+
+ @pytest.mark.xfail(
+ raises=AssertionError,
+ reason="quaternion_to_rotation_matrix builds its output around a 0-dim float32 torch.tensor(1.0), "
+ "which upcasts unbatched (4,) half-precision input; batched input keeps its dtype β€” kornia#3954",
+ strict=True,
+ )
+ @pytest.mark.parametrize("half_dtype", [torch.float16, torch.bfloat16])
+ def test_convention_output_dtype_equals_input_dtype_3954(self, device, half_dtype):
+ # Intended behavior: quaternion_to_rotation_matrix returns the dtype it was given, like
+ # every other 3b symbol -- normalize_quaternion, quaternion_to_axis_angle and
+ # quaternion_exp_to_log all preserve float16 and bfloat16 on the very same input. It does
+ # not, for the UNBATCHED (4,) input this pin uses: the literal `one = torch.tensor(1.0)`
+ # inside the function is 0-dim float32, and promotion ranks a dimensioned tensor above a
+ # 0-dim one, so the 0-dim components of a (4,) input tie with the literal and torch.stack
+ # promotes the whole matrix to float32. Batched input is unaffected -- (1,4), (2,4) and
+ # (3,3,4) all come back in the input dtype -- so the sharp form of the defect is that the
+ # same call returns a different dtype for q and for q[None]. Unbatched, a half-precision
+ # pipeline silently doubles its memory here and then fails at the next matmul with
+ # "expected scalar type Float but found Half" (batched, that matmul succeeds).
+ # The dtypes are hardcoded and the dtype fixture dropped so both
+ # legs run in the default float32 configuration; the skip is visible so a backend without
+ # the dtype cannot satisfy the raises=AssertionError mark with a RuntimeError instead.
+ # Marked xfail(strict=True) so fixing #3954 makes both cases XPASS and forces the mark out.
+ # Companion wart: test_wart_half_precision_input_is_upcast_to_float32_3954.
+ _skip_if_dtype_unavailable(device, half_dtype)
+
+ quaternion = torch.tensor([1.0, 0.0, 0.0, 0.0], device=device, dtype=half_dtype)
+
+ out = kornia.geometry.conversions.quaternion_to_rotation_matrix(quaternion)
+
+ assert out.dtype == half_dtype, f"kornia#3954: quaternion_to_rotation_matrix returned {out.dtype}"
+
+ @pytest.mark.parametrize("half_dtype", [torch.float16, torch.bfloat16])
+ def test_wart_half_precision_input_is_upcast_to_float32_3954(self, device, half_dtype):
+ # Wart pin for kornia#3954, companion to the strict xfail above: assert that the output
+ # dtype is CURRENTLY float32 for both half-precision inputs AT THE UNBATCHED (4,) SHAPE
+ # USED HERE -- batched input already preserves the dtype today, so this pin is deliberately
+ # unbatched and is not a claim about (1,4) or larger -- and that normalize_quaternion
+ # -- the very first thing quaternion_to_rotation_matrix calls -- preserves the dtype on the
+ # same tensor, which localises the defect to the float32 literal further down. Two cells
+ # because a fix could plausibly special-case float16 (the common half dtype) and leave
+ # bfloat16 upcast, which would leave one case of the strict xfail silently XFAIL. If either
+ # fails, #3954 was (partly) fixed -- flip/remove the strict xfail above. NOT a contract that
+ # unbatched half-precision input must keep being upcast.
+ # Snippet used to generate expected (torch only, executed on cpu):
+ # q = torch.tensor([1., 0., 0., 0.], dtype=torch.float16)
+ # quaternion_to_rotation_matrix(q).dtype -> torch.float32 (bfloat16 input: also float32)
+ # quaternion_to_rotation_matrix(q[None]).dtype -> torch.float16 (bfloat16 input: bfloat16)
+ # normalize_quaternion(q).dtype -> torch.float16 (bfloat16 input: bfloat16)
+ # quaternion_to_axis_angle(q).dtype -> torch.float16
+ _skip_if_dtype_unavailable(device, half_dtype)
+
+ quaternion = torch.tensor([1.0, 0.0, 0.0, 0.0], device=device, dtype=half_dtype)
+
+ out = kornia.geometry.conversions.quaternion_to_rotation_matrix(quaternion)
+
+ assert out.dtype == torch.float32, f"kornia#3954: the output dtype is no longer float32, it is {out.dtype}"
+ assert kornia.geometry.conversions.normalize_quaternion(quaternion).dtype == half_dtype, (
+ "kornia#3954: normalize_quaternion no longer preserves the input dtype, so the defect is no longer "
+ "localised to quaternion_to_rotation_matrix"
+ )
+
class TestQuaternionLogToExp(BaseTester):
@pytest.mark.parametrize("batch_size", (1, 3, 8))
@@ -406,6 +1202,248 @@ class TestQuaternionLogToExp(BaseTester):
self.assert_close(actual, expected)
+ def test_convention_exp_of_v_equals_axis_angle_to_quaternion_of_twice_v(self, device, dtype):
+ # Convention pin: the log quaternion is (theta / 2) * axis, NOT the axis-angle vector, so
+ # the exponential map is exactly axis_angle_to_quaternion applied to 2 * v. A caller that
+ # feeds an axis-angle vector straight into quaternion_log_to_exp gets a rotation of half
+ # the intended angle, silently. The size contract of the pair is pinned alongside:
+ # (*, 3) -> (*, 4) here, (*, 4) -> (*, 3) in quaternion_exp_to_log.
+ # Snippet used to generate expected (stdlib only, v = (0.15, 0.2, 0.25), theta = 2 * |v|):
+ # import math
+ # th = math.sqrt(0.15 ** 2 + 0.2 ** 2 + 0.25 ** 2) * 2 # 0.7071067811865476
+ # ax = [x / (th / 2) for x in (0.15, 0.2, 0.25)]
+ # [math.cos(th / 2)] + [math.sin(th / 2) * a for a in ax]
+ # -> [0.9381483350397287, 0.14689447322208307, 0.19585929762944412, 0.24482412203680515]
+ # assert_close and not torch.equal: the two routes agree bit-for-bit at float64, float32
+ # and float16 for this input, but that is an accident of the input -- over 500 random
+ # float64 vectors (seeded torch.Generator(4)) only 142/500 are bit-identical (worst
+ # difference 4.440892098500626e-16), and at bfloat16 the pinned input already differs by
+ # 9.765625e-04 because ||2v|| / 2 and ||v|| round apart.
+ log_quaternion = torch.tensor([0.15, 0.2, 0.25], device=device, dtype=dtype)
+
+ out = kornia.geometry.conversions.quaternion_log_to_exp(log_quaternion)
+
+ self.assert_close(
+ out,
+ torch.tensor(
+ [0.9381483350397287, 0.14689447322208307, 0.19585929762944412, 0.24482412203680515],
+ device=device,
+ dtype=dtype,
+ ),
+ )
+ self.assert_close(out, kornia.geometry.conversions.axis_angle_to_quaternion(2.0 * log_quaternion))
+
+ assert kornia.geometry.conversions.quaternion_log_to_exp(
+ torch.zeros(2, 5, 3, device=device, dtype=dtype)
+ ).shape == (2, 5, 4)
+
+ def test_convention_exp_real_part_is_cosine_of_the_norm(self, device, dtype):
+ # Convention pin: the exponential map returns w = cos(||v||) and (x, y, z) = sin(||v||) * v
+ # / ||v||, so it is NOT restricted to the w >= 0 half of the double cover: any ||v|| > pi/2
+ # (i.e. any rotation past 180 degrees, since theta = 2 * ||v||) lands in the w < 0 half.
+ # Pinned at ||v|| = 2 rad, where w is clearly negative; the output is still a unit
+ # quaternion, which the norm assertion states.
+ # Snippet used to generate expected (stdlib only):
+ # import math
+ # math.cos(2.0), math.sin(2.0) -> (-0.4161468365471424, 0.9092974268256817)
+ out = kornia.geometry.conversions.quaternion_log_to_exp(
+ torch.tensor([0.0, 0.0, 2.0], device=device, dtype=dtype)
+ )
+
+ self.assert_close(
+ out,
+ torch.tensor([-0.4161468365471424, 0.0, 0.0, 0.9092974268256817], device=device, dtype=dtype),
+ )
+ self.assert_close(out.norm(), torch.tensor(1.0, device=device, dtype=dtype))
+
+ def test_convention_exp_of_log_is_the_identity_except_at_minus_one(self, device, dtype):
+ # Convention pin (domain fact of the map, not a defect): quaternion_log_to_exp composed
+ # with quaternion_exp_to_log is the identity, with exactly one exception -- the pure-real
+ # quaternion (-1, 0, 0, 0), whose log is genuinely the origin in this parametrisation, so
+ # the round-trip returns the OTHER half of the double cover, (1, 0, 0, 0). The sign of a
+ # non-zero vector part is preserved, which is what the third case pins: (-1, 0, 0, -1)/
+ # sqrt(2) comes back as itself and is not flipped to its positive-w twin.
+ # Snippet used to generate expected (stdlib only):
+ # exp(log(q)) = q for every unit q except q = (-1, 0, 0, 0)
+ # 1 / math.sqrt(2.0) -> 0.7071067811865476
+ # float16 is skipped: quaternion_exp_to_log((-1, 0, 0, 0)) returns NaN there, so the
+ # exception case cannot be evaluated at all (float64/float32/bfloat16 all return the
+ # origin as documented above).
+ if dtype == torch.float16:
+ pytest.skip("quaternion_exp_to_log((-1, 0, 0, 0)) is NaN at float16, so exp(log(.)) is undefined")
+
+ identity = torch.tensor([1.0, 0.0, 0.0, 0.0], device=device, dtype=dtype)
+ exp_to_log = kornia.geometry.conversions.quaternion_exp_to_log
+ log_to_exp = kornia.geometry.conversions.quaternion_log_to_exp
+
+ self.assert_close(log_to_exp(exp_to_log(identity)), identity)
+ self.assert_close(log_to_exp(exp_to_log(-identity)), identity)
+
+ half_turn = torch.tensor([-0.7071067811865476, 0.0, 0.0, -0.7071067811865476], device=device, dtype=dtype)
+ self.assert_close(log_to_exp(exp_to_log(half_turn)), half_turn)
+
+ @pytest.mark.xfail(
+ raises=AssertionError,
+ reason="the default eps=1e-8 is not representable in float16, so the norm clamp becomes a "
+ "no-op and 0/0 gives a NaN vector part β€” kornia#3966",
+ strict=True,
+ )
+ def test_convention_log_to_exp_of_the_origin_is_the_identity_in_float16_3966(self, device):
+ # Intended behavior: the exponential map of the zero vector is the identity quaternion, at
+ # every dtype -- float64, float32 and bfloat16 all return [1, 0, 0, 0]. float16 returns
+ # [1, nan, nan, nan]: the default eps = 1e-8 is below float16's smallest subnormal
+ # (5.960464477539063e-08), so torch.tensor(1e-8, dtype=float16) is exactly 0.0, the
+ # .clamp(min=eps) on the norm is a no-op, and the vector part is sin(0) * 0 / 0. The real
+ # part survives because it is cos(0). This is the same eps-underflow class as the one
+ # kornia#3966 was filed for on quaternion_exp_to_log (pinned in TestQuaternionExpToLog);
+ # bfloat16 escapes both because its exponent range is float32's. float16 is hardcoded and
+ # the dtype fixture dropped so this pin runs in every configuration, with a visible skip
+ # where the device lacks the dtype. Marked xfail(strict=True) so fixing #3966 makes this
+ # XPASS and forces the mark out. Companion wart:
+ # test_wart_float16_eps_underflow_makes_log_to_exp_nan_3966.
+ _skip_if_dtype_unavailable(device, torch.float16)
+
+ out = kornia.geometry.conversions.quaternion_log_to_exp(torch.zeros(3, device=device, dtype=torch.float16))
+
+ assert_close(
+ out,
+ torch.tensor([1.0, 0.0, 0.0, 0.0], device=device, dtype=torch.float16),
+ msg=_issue_msg("kornia#3966: quaternion_log_to_exp of the float16 origin is not the identity"),
+ )
+
+ def test_wart_float16_eps_underflow_makes_log_to_exp_nan_3966(self, device):
+ # Wart pin for kornia#3966 on quaternion_log_to_exp, companion to the strict xfail above:
+ # assert the CURRENT float16 behavior. Three cells, each discriminating a different fix
+ # shape:
+ # (0) the eps default is still 1e-8 -- cell 1 leaves eps at its default on purpose (the
+ # underflow of the *default* is the claim), so a re-tuned default would otherwise be
+ # an invisible half-fix;
+ # (1) the origin returns w = 1 with an all-NaN vector part;
+ # (2) the origin with an explicitly representable eps=1e-3 returns [1, 0, 0, 0] -- the
+ # control that says the arithmetic is fine and only the default underflows, telling an
+ # eps-shaped fix apart from a branch-shaped one;
+ # (3) a v with a representable norm is unaffected and returns
+ # [1.0, 0.0010128021240234375, 0, 0] -- the working case the existing suite exercises,
+ # pinned so a fix cannot regress it.
+ # The affected class is exactly the zero vector, so there is no second broken input to pin:
+ # torch.norm does not underflow at float16, and every positive float16 value below 1e-2 in a
+ # single component (all 8478 of them, the 1023 subnormals included) plus 512 tiny
+ # multi-component combinations all give a non-zero norm and a finite result. A near-zero
+ # literal is no use either -- torch.tensor([1e-9, 0, 0], dtype=float16) IS torch.zeros(3)
+ # bitwise, so it would restate cell (1) rather than discriminate anything.
+ # If any cell fails, #3966 was (partly) fixed on this function -- flip/remove the strict
+ # xfail above. NOT a contract that float16 must keep returning NaN.
+ # Snippet used to generate expected (torch only, executed on cpu):
+ # l2e = kornia.geometry.conversions.quaternion_log_to_exp
+ # l2e(torch.zeros(3, dtype=torch.float16)) -> [1., nan, nan, nan]
+ # l2e(torch.zeros(3, dtype=torch.float16), eps=1e-3) -> [1., 0., 0., 0.]
+ # l2e(torch.tensor([1e-3, 0., 0.], dtype=torch.float16))
+ # -> [1.0, 0.0010128021240234375, 0.0, 0.0]
+ # torch.tensor(1e-8, dtype=torch.float16).item() -> 0.0
+ # (float64/float32/bfloat16 return [1, 0, 0, 0] for the origin)
+ _skip_if_dtype_unavailable(device, torch.float16)
+
+ log_to_exp = kornia.geometry.conversions.quaternion_log_to_exp
+ assert inspect.signature(log_to_exp).parameters["eps"].default == 1e-8, (
+ "kornia#3966: the eps default moved, so the float16 underflow pinned here no longer describes it"
+ )
+
+ origin = torch.zeros(3, device=device, dtype=torch.float16)
+
+ out = log_to_exp(origin)
+ assert out[0].item() == 1.0, "kornia#3966: the float16 origin no longer has a real part of 1"
+ assert torch.isnan(out[1:]).all(), "kornia#3966: the float16 origin no longer gives a NaN vector part"
+ assert_close(
+ log_to_exp(origin, eps=1e-3),
+ torch.tensor([1.0, 0.0, 0.0, 0.0], device=device, dtype=torch.float16),
+ atol=0.0,
+ rtol=0.0,
+ msg=_issue_msg("kornia#3966: a representable eps no longer rescues the float16 origin"),
+ )
+ # rtol 2e-3 is ~two float16 ulps of relative slack: the literal was generated on cpu, and a
+ # cuda/mps run computes the sin/cos chain through different intermediates that can move the
+ # last bit. The pinned fact -- a representable norm stays finite and correct, not NaN --
+ # survives that; the exact zeros are unaffected by rtol and stay exact.
+ assert_close(
+ log_to_exp(torch.tensor([1e-3, 0.0, 0.0], device=device, dtype=torch.float16)),
+ torch.tensor([1.0, 0.0010128021240234375, 0.0, 0.0], device=device, dtype=torch.float16),
+ atol=0.0,
+ rtol=2e-3,
+ msg=_issue_msg("kornia#3966: the float16 case with a representable norm changed"),
+ )
+
+ @pytest.mark.parametrize(
+ ("overflow_dtype", "finite_side", "nan_side"),
+ [
+ ("float32", [1e19, 0.0, 0.0], [1e20, 0.0, 0.0]),
+ ("float64", [1e153, 0.0, 0.0], [1e155, 0.0, 0.0]),
+ ("bfloat16", [1e18, 0.0, 0.0], [1e20, 0.0, 0.0]),
+ ("float16", [32768.0] * 3, [49152.0] * 3),
+ ],
+ ids=["float32", "float64", "bfloat16", "float16_three_components"],
+ )
+ def test_wart_large_finite_input_overflows_log_to_exp_to_nan_3975(
+ self, device, overflow_dtype, finite_side, nan_side
+ ):
+ # Wart pin for kornia#3975: assert that quaternion_log_to_exp CURRENTLY returns all-NaN for
+ # a finite input vector, because torch.norm(p=2) forms the sum of squares and overflows to
+ # inf well below the largest finite input. The exp map of a large finite vector is
+ # mathematically a perfectly good unit quaternion, so this is a defect, not a convention.
+ # Distinct from kornia#3966: that is the float16 eps *underflow* family, this is an
+ # *overflow* in the norm and is independent of eps.
+ # The threshold has two regimes, which is why the cells carry whole vectors and not one
+ # magnitude -- the number of non-zero components is part of the fact being pinned:
+ # - float32 and bfloat16 accumulate the squares in their own dtype, so they turn over at
+ # ||v|| > sqrt(finfo.max): 1.8446744e19 and ~1.841e19. One component is enough.
+ # - float16 accumulates in wider precision, so the squares never overflow; the result
+ # overflows only once the true ||v|| itself exceeds what float16 can hold, i.e. once
+ # the wider-precision norm rounds to inf at ~65520 (the midpoint between float16's max
+ # of 65504 and the next value up). A single component can never do that -- it would
+ # have to exceed 65504 to begin with -- so it takes TWO OR MORE non-zero components.
+ # Hence the three-component float16 cell.
+ # Both sides of the boundary are pinned -- one input that stays a unit quaternion, one
+ # that comes back all-NaN -- and each sits with deliberate margin from the measured
+ # crossover (cpu torch 2.9.1: ||v|| 1.8446744e19 for float32, 1.3407808e154 for float64,
+ # ~1.84e19 for bfloat16, ~65520 true norm for float16) rather than ulp-adjacent to it.
+ # The exact crossover is a property of torch.norm's accumulation strategy, not of kornia
+ # code -- the float16 regime above is that strategy differing by dtype -- so a torch
+ # upgrade or another backend may move it by an ulp; the margin keeps that from flipping a
+ # cell while any real fix (the NaN disappearing from the finite range) still does.
+ # float16's margins are percentage-scale rather than order-of-magnitude because the NaN
+ # side is capped by the dtype -- components must stay below float16's max of 65504, so
+ # three of them cannot push the true norm past ~113000: [49152]*3 has a true norm of
+ # 85134 (30% above the crossover) and [32768]*3 has 56756 (13% below).
+ # The dtypes are hardcoded (the boundary is a per-dtype fact) with a visible skip where
+ # the device lacks the dtype.
+ # If any cell fails, #3975 was (partly) fixed -- drop the pin. NOT a contract that NaN is
+ # the right answer; a fix making the whole finite range return unit quaternions is the
+ # intended outcome and would flip this.
+ # Snippet used to verify both sides (torch only, executed on cpu):
+ # l2e = kornia.geometry.conversions.quaternion_log_to_exp
+ # l2e(torch.tensor([finite_side], dtype=dtype))
+ # -> finite, | ||q|| - 1 | of 1.1e-08 (f32), 0.0 (f64), 4.3e-04 (bf16), 8.1e-05 (f16)
+ # l2e(torch.tensor([nan_side], dtype=dtype)) -> all NaN at every dtype
+ dtype = getattr(torch, overflow_dtype)
+ _skip_if_dtype_unavailable(device, dtype)
+
+ log_to_exp = kornia.geometry.conversions.quaternion_log_to_exp
+
+ finite = log_to_exp(torch.tensor([finite_side], device=device, dtype=dtype))
+ assert torch.isfinite(finite).all(), (
+ f"kornia#3975: {overflow_dtype} input {finite_side} no longer returns a finite quaternion"
+ )
+ # .cpu() before .double(): MPS has no float64, so accumulating the norm on-device raises.
+ # The float16 cell is only unit to its own rounding, hence the dtype-aware tolerance.
+ unit_tol = 8 * torch.finfo(dtype).eps
+ assert abs(finite.cpu().double().norm().item() - 1.0) < unit_tol, (
+ f"kornia#3975: {overflow_dtype} input {finite_side} no longer returns a unit quaternion"
+ )
+
+ overflowed = log_to_exp(torch.tensor([nan_side], device=device, dtype=dtype))
+ assert torch.isnan(overflowed).all(), (
+ f"kornia#3975: {overflow_dtype} input {nan_side} no longer overflows to all-NaN (got {overflowed.tolist()})"
+ )
+
class TestQuaternionExpToLog(BaseTester):
@pytest.mark.parametrize("batch_size", (1, 3, 8))
@@ -467,6 +1505,252 @@ class TestQuaternionExpToLog(BaseTester):
self.assert_close(actual, expected)
+ def test_convention_log_is_half_the_axis_angle_on_the_w_positive_half(self, device, dtype):
+ # Convention pin: the log quaternion is (theta / 2) * axis, i.e. exactly half the
+ # axis-angle vector -- so quaternion_exp_to_log(q) == quaternion_to_axis_angle(q) / 2, but
+ # ONLY on the w >= 0 half. The two functions treat the double cover differently:
+ # quaternion_to_axis_angle collapses q and -q onto the same |theta| <= pi vector, while
+ # quaternion_exp_to_log takes acos(w) at face value and returns (pi - theta/2) along the
+ # negated axis for w < 0. The second half of this pin states that divergence explicitly,
+ # because "log is half the axis-angle" is false without the restriction: over 500 random
+ # float64 unit quaternions (seeded torch.Generator(3)) the two agree to 4.44e-16 on the
+ # 243 with w >= 0 and disagree by up to 3.1367975802888637 on the 257 with w < 0.
+ # The size contract (*, 4) -> (*, 3) is pinned alongside.
+ # Snippet used to generate expected (stdlib only, axis_angle = (0.3, 0.4, 0.5)):
+ # import math
+ # v = [0.15, 0.2, 0.25] # = axis_angle / 2, the expected log
+ # nv = math.sqrt(sum(x * x for x in v)) # 0.3535533905932738
+ # q = [math.cos(nv)] + [math.sin(nv) * x / nv for x in v]
+ # -> [0.9381483350397287, 0.14689447322208307, 0.19585929762944412, 0.24482412203680515]
+ # for -q the log is (nv - pi) * axis:
+ # [-(math.pi - nv) * (x / nv) for x in v]
+ # -> [-1.1828648814475096, -1.5771531752633463, -1.9714414690791828]
+ quaternion = torch.tensor(
+ [0.9381483350397287, 0.14689447322208307, 0.19585929762944412, 0.24482412203680515],
+ device=device,
+ dtype=dtype,
+ )
+
+ out = kornia.geometry.conversions.quaternion_exp_to_log(quaternion)
+
+ self.assert_close(out, torch.tensor([0.15, 0.2, 0.25], device=device, dtype=dtype))
+ self.assert_close(out, kornia.geometry.conversions.quaternion_to_axis_angle(quaternion) / 2.0)
+
+ out_negated = kornia.geometry.conversions.quaternion_exp_to_log(-quaternion)
+ self.assert_close(
+ out_negated,
+ torch.tensor([-1.1828648814475096, -1.5771531752633463, -1.9714414690791828], device=device, dtype=dtype),
+ )
+
+ assert kornia.geometry.conversions.quaternion_exp_to_log(
+ torch.zeros(2, 5, 4, device=device, dtype=dtype)
+ ).shape == (2, 5, 3)
+
+ def test_convention_log_of_exp_is_exact_below_pi_and_wraps_above(self, device, dtype):
+ # Convention pin (domain fact of the map, not a defect): quaternion_exp_to_log composed
+ # with quaternion_log_to_exp reproduces its input only for 0 < ||v|| < pi. Above pi the
+ # rotation has passed a full turn (theta = 2 * ||v||) and the result wraps into
+ # ||v|| - 2*pi, i.e. it comes back with the OPPOSITE sign, which the second case pins:
+ # a caller doing exp/log arithmetic on large vectors must reduce the norm itself.
+ # Snippet used to generate expected (stdlib only):
+ # import math
+ # the round-trip is the identity for ||v|| < pi -> [0.0, 0.0, 1.0]
+ # math.pi + 0.5 - 2 * math.pi -> -2.641592653589793
+ exp_to_log = kornia.geometry.conversions.quaternion_exp_to_log
+ log_to_exp = kornia.geometry.conversions.quaternion_log_to_exp
+
+ below_pi = torch.tensor([0.0, 0.0, 1.0], device=device, dtype=dtype)
+ self.assert_close(exp_to_log(log_to_exp(below_pi)), below_pi)
+
+ above_pi = torch.tensor([0.0, 0.0, 3.641592653589793], device=device, dtype=dtype)
+ self.assert_close(
+ exp_to_log(log_to_exp(above_pi)),
+ torch.tensor([0.0, 0.0, -2.641592653589793], device=device, dtype=dtype),
+ )
+
+ def test_convention_log_of_exp_collapses_to_zero_at_pi_in_float64(self, device):
+ # Convention pin (domain fact of the map): at exactly ||v|| = pi the exponential map lands
+ # on (-1, 0, 0, 0), whose log genuinely IS the origin in this parametrisation, so the
+ # round-trip collapses to ~0 instead of returning pi -- the one interior point where the
+ # log/exp pair is not invertible. float64 is hardcoded and the dtype fixture dropped
+ # because the collapse needs cos(||v||) to round to exactly -1 and the vector part to fall
+ # below the eps clamp, which only happens at float64: at float32 the same input returns
+ # -3.1415927410125732 (no collapse), at float16/bfloat16 3.140625. MPS is skipped visibly
+ # because it has no float64 at all.
+ # Snippet used to generate expected (stdlib only):
+ # math.cos(math.pi), math.sin(math.pi) -> (-1.0, 1.2246467991473532e-16)
+ # Measured round-trip value at float64 (torch 2.9.1, cpu): 3.847341387443579e-08, i.e. an
+ # error of 3.14 against the input, so atol 1e-7 pins the collapse without pinning the
+ # residue itself.
+ _skip_if_dtype_unavailable(device, torch.float64)
+
+ at_pi = torch.tensor([0.0, 0.0, 3.141592653589793], device=device, dtype=torch.float64)
+
+ out = kornia.geometry.conversions.quaternion_exp_to_log(
+ kornia.geometry.conversions.quaternion_log_to_exp(at_pi)
+ )
+
+ self.assert_close(out, torch.zeros(3, device=device, dtype=torch.float64), atol=1e-7, rtol=0.0)
+
+ @pytest.mark.xfail(
+ raises=AssertionError,
+ reason="quaternion_exp_to_log does not normalise its input, so a non-unit quaternion gives "
+ "a silently wrong log β€” kornia#3953",
+ strict=True,
+ )
+ def test_convention_exp_to_log_normalizes_its_input_3953(self, device, dtype):
+ # Intended behavior: the log of a quaternion depends only on the rotation it represents, so
+ # a rescaled quaternion gives the same answer -- which is what its scale-safe siblings do
+ # (quaternion_to_rotation_matrix normalises internally, quaternion_to_axis_angle is
+ # homogeneous by construction; both are pinned above). quaternion_exp_to_log does neither:
+ # it feeds the raw scalar part straight into acos, so q = (0.5, 0.5, 0, 0) -- the 90-degree
+ # rotation about x, scaled by 1/sqrt(2) -- returns 1.0471975511965976 instead of
+ # acos(1/sqrt(2)) = 0.7853981633974484, i.e. 33% too large, with no error and no warning.
+ # Marked xfail(strict=True) so fixing #3953 makes this XPASS and forces the mark out.
+ # Companion wart: test_wart_exp_to_log_ignores_the_quaternion_norm_3953; the
+ # euler_from_quaternion half of the same issue is pinned in TestEulerFromQuaternion.
+ quaternion = torch.tensor([0.5, 0.5, 0.0, 0.0], device=device, dtype=dtype)
+
+ out = kornia.geometry.conversions.quaternion_exp_to_log(quaternion, eps=1e-8)
+
+ assert_close(
+ out,
+ torch.tensor([0.7853981633974484, 0.0, 0.0], device=device, dtype=dtype),
+ msg=_issue_msg("kornia#3953: quaternion_exp_to_log did not normalise its input"),
+ )
+
+ def test_wart_exp_to_log_ignores_the_quaternion_norm_3953(self, device, dtype):
+ # Wart pin for kornia#3953, companion to the strict xfail above: assert the CURRENT
+ # non-unit-input outputs. Two cells that discriminate the two plausible fix shapes:
+ # (1) q = (0.5, 0.5, 0, 0) returns 1.0471975511965976 -- flips under a "normalise the
+ # input" fix and under a "raise on non-unit input" fix alike;
+ # (2) q = (2, 0, 0, 0) returns the origin because the scalar part is clamped into
+ # [-1, 1] before the acos -- this does NOT flip under a normalising fix (the
+ # normalised input is the identity, whose log is the origin), so it is the cell that
+ # tells a normalising fix apart from a validating one.
+ # If either fails, #3953 was (partly) fixed -- flip/remove the strict xfail above. NOT a
+ # contract that non-unit input must keep these values. eps is passed explicitly so the
+ # literals do not silently track a later change of the default.
+ # Snippet used to generate expected (torch + stdlib, executed on cpu float64):
+ # quaternion_exp_to_log(torch.tensor([0.5, 0.5, 0., 0.], dtype=torch.float64), eps=1e-8)
+ # -> [1.0471975511965976, 0.0, 0.0] (float32: 1.0471975803375244;
+ # float16/bfloat16: 1.046875)
+ # math.acos(0.5) -> 1.0471975511965979, and math.acos(1 / math.sqrt(2)) -> 0.7853981633974484
+ # quaternion_exp_to_log(torch.tensor([2., 0., 0., 0.], dtype=torch.float64), eps=1e-8)
+ # -> [0.0, 0.0, 0.0]
+ if dtype == torch.float16:
+ pytest.skip(
+ "at float16 the second cell is NaN rather than the origin, because the default eps underflows and "
+ "the zero vector part is divided by itself -- that is kornia#3966, pinned separately below"
+ )
+
+ exp_to_log = kornia.geometry.conversions.quaternion_exp_to_log
+
+ scaled_down = exp_to_log(torch.tensor([0.5, 0.5, 0.0, 0.0], device=device, dtype=dtype), eps=1e-8)
+ scaled_up = exp_to_log(torch.tensor([2.0, 0.0, 0.0, 0.0], device=device, dtype=dtype), eps=1e-8)
+
+ assert_close(
+ scaled_down,
+ torch.tensor([1.0471975511965976, 0.0, 0.0], device=device, dtype=dtype),
+ msg=_issue_msg("kornia#3953: quaternion_exp_to_log no longer takes the raw scalar part at face value"),
+ )
+ assert_close(
+ scaled_up,
+ torch.zeros(3, device=device, dtype=dtype),
+ msg=_issue_msg("kornia#3953: the scalar-part clamp no longer sends an over-scaled quaternion to zero"),
+ )
+
+ @pytest.mark.xfail(
+ raises=AssertionError,
+ reason="the default eps=1e-8 is not representable in float16, so the vector-norm clamp "
+ "becomes a no-op and 0/0 gives NaN β€” kornia#3966",
+ strict=True,
+ )
+ def test_convention_exp_to_log_of_the_identity_is_the_origin_in_float16_3966(self, device):
+ # Intended behavior: the log of the identity quaternion is the origin, at every dtype --
+ # float32, float64 and bfloat16 all return [0, 0, 0]. float16 returns [nan, nan, nan]:
+ # the default eps = 1e-8 is below float16's smallest subnormal (5.960464477539063e-08), so
+ # torch.tensor(1e-8, dtype=float16) is exactly 0.0, the .clamp(min=eps) on the vector-part
+ # norm is a no-op, and the log is acos(1) * 0 / 0. bfloat16 escapes only because its
+ # exponent range is float32's (1e-8 survives as 1.0011717677116394e-08). float16 is
+ # hardcoded and the dtype fixture dropped so this pin runs in every configuration, with a
+ # visible skip where the device lacks the dtype -- otherwise a RuntimeError would satisfy
+ # the raises=AssertionError mark instead of the assertion. Marked xfail(strict=True) so
+ # fixing #3966 makes this XPASS and forces the mark out. Companion wart:
+ # test_wart_float16_eps_underflow_makes_exp_to_log_nan_3966. Note that 3a's merged
+ # test_wart_float16_underflowed_default_eps_flips_branches pins the same failure class
+ # (a float default eps that float16 cannot represent) at a different site.
+ _skip_if_dtype_unavailable(device, torch.float16)
+
+ identity = torch.tensor([1.0, 0.0, 0.0, 0.0], device=device, dtype=torch.float16)
+
+ out = kornia.geometry.conversions.quaternion_exp_to_log(identity)
+
+ assert_close(
+ out,
+ torch.zeros(3, device=device, dtype=torch.float16),
+ msg=_issue_msg("kornia#3966: quaternion_exp_to_log of the float16 identity is not the origin"),
+ )
+
+ def test_wart_float16_eps_underflow_makes_exp_to_log_nan_3966(self, device):
+ # Wart pin for kornia#3966, companion to the strict xfail above: assert the CURRENT float16
+ # behavior. Four cells, each discriminating a different fix shape:
+ # (1) the identity (1, 0, 0, 0) is NaN;
+ # (2) its double-cover twin (-1, 0, 0, 0) is NaN too -- a branch-shaped fix keyed on the
+ # sign of w (say, "return the origin when w >= 1") would flip (1) and leave (2), so
+ # both halves must be pinned;
+ # (3) the same identity with an explicitly representable eps=1e-3 returns the origin --
+ # the control that says the arithmetic is fine and only the *default* underflows, so
+ # an eps-shaped fix (a dtype-aware default) is told apart from a branch-shaped one;
+ # (4) a quaternion with a non-zero vector part is unaffected at float16 and returns
+ # [3.140625, 0, 0] -- the working case the existing suite exercises, which is why
+ # this bug went unnoticed; pinned so that a fix cannot regress it.
+ # If any cell fails, #3966 was (partly) fixed -- flip/remove the strict xfail above. NOT a
+ # contract that float16 must keep returning NaN. eps is left at its DEFAULT in cells 1, 2
+ # and 4 on purpose: the underflow of the default is the claim (same reasoning as 3a's
+ # test_wart_float16_underflowed_default_eps_flips_branches), so the default is pinned
+ # explicitly here instead.
+ # Snippet used to generate expected (torch only, executed on cpu):
+ # e2l = kornia.geometry.conversions.quaternion_exp_to_log
+ # e2l(torch.tensor([1., 0., 0., 0.], dtype=torch.float16)) -> [nan, nan, nan]
+ # e2l(torch.tensor([-1., 0., 0., 0.], dtype=torch.float16)) -> [nan, nan, nan]
+ # e2l(torch.tensor([1., 0., 0., 0.], dtype=torch.float16), eps=1e-3) -> [0., 0., 0.]
+ # e2l(torch.tensor([-1., 1e-3, 0., 0.], dtype=torch.float16)) -> [3.140625, 0., 0.]
+ # torch.tensor(1e-8, dtype=torch.float16).item() -> 0.0
+ # (float64/float32/bfloat16 return [0, 0, 0] for the first two cells)
+ _skip_if_dtype_unavailable(device, torch.float16)
+
+ exp_to_log = kornia.geometry.conversions.quaternion_exp_to_log
+ assert inspect.signature(exp_to_log).parameters["eps"].default == 1e-8, (
+ "kornia#3966: the eps default moved, so the float16 underflow pinned here no longer describes it"
+ )
+
+ identity = torch.tensor([1.0, 0.0, 0.0, 0.0], device=device, dtype=torch.float16)
+ negated_identity = torch.tensor([-1.0, 0.0, 0.0, 0.0], device=device, dtype=torch.float16)
+ with_vector_part = torch.tensor([-1.0, 1e-3, 0.0, 0.0], device=device, dtype=torch.float16)
+
+ assert torch.isnan(exp_to_log(identity)).all(), "kornia#3966: the float16 identity no longer gives NaN"
+ assert torch.isnan(exp_to_log(negated_identity)).all(), (
+ "kornia#3966: the float16 negated identity no longer gives NaN"
+ )
+ assert_close(
+ exp_to_log(identity, eps=1e-3),
+ torch.zeros(3, device=device, dtype=torch.float16),
+ atol=0.0,
+ rtol=0.0,
+ msg=_issue_msg("kornia#3966: a representable eps no longer rescues the float16 identity"),
+ )
+ # rtol 2e-3 for the same reason as the log_to_exp #3966 pin above: the literal is
+ # cpu-generated and another backend's acos can move the last float16 bit; the pinned fact
+ # (finite and correct, not NaN) survives, and the exact zeros stay exact under rtol.
+ assert_close(
+ exp_to_log(with_vector_part),
+ torch.tensor([3.140625, 0.0, 0.0], device=device, dtype=torch.float16),
+ atol=0.0,
+ rtol=2e-3,
+ msg=_issue_msg("kornia#3966: the float16 case with a non-zero vector part changed"),
+ )
+
class TestAngleAxisToRotationMatrix(BaseTester):
@pytest.mark.parametrize("batch_size", (1, 2, 5))
@@ -512,6 +1796,260 @@ class TestAngleAxisToRotationMatrix(BaseTester):
self.assert_close(kornia.geometry.conversions.axis_angle_to_rotation_matrix(rvec), rmat, atol=atol, rtol=rtol)
+ def test_convention_positive_angle_about_z_maps_x_to_y(self, device, dtype):
+ # Convention pin (covers quaternion_to_rotation_matrix too -- both routes to a rotation
+ # matrix in this module must agree): rotations follow the right-hand rule, so a positive
+ # angle about +z takes x_hat to y_hat and the matrix is
+ # [[cos, -sin, 0], [sin, cos, 0], [0, 0, 1]], NOT its transpose. Pinned at theta = 0.6 rad
+ # rather than a quarter turn so that a transposed or sign-flipped implementation cannot
+ # slip through on symmetry, and the mapped basis vector is asserted as well as the matrix
+ # so the claim is stated the way a reader will use it.
+ # Snippet used to generate expected (stdlib only):
+ # import math
+ # math.cos(0.6), math.sin(0.6) -> (0.8253356149096783, 0.5646424733950354)
+ # the same rotation as a quaternion, (cos(0.3), 0, 0, sin(0.3))
+ # -> (0.955336489125606, 0.0, 0.0, 0.29552020666133955)
+ expected = torch.tensor(
+ [
+ [0.8253356149096783, -0.5646424733950354, 0.0],
+ [0.5646424733950354, 0.8253356149096783, 0.0],
+ [0.0, 0.0, 1.0],
+ ],
+ device=device,
+ dtype=dtype,
+ )
+ expected_x_maps_to = torch.tensor([0.8253356149096783, 0.5646424733950354, 0.0], device=device, dtype=dtype)
+ x_hat = torch.tensor([1.0, 0.0, 0.0], device=device, dtype=dtype)
+
+ rot_from_axis_angle = kornia.geometry.conversions.axis_angle_to_rotation_matrix(
+ torch.tensor([[0.0, 0.0, 0.6]], device=device, dtype=dtype)
+ )[0]
+ self.assert_close(rot_from_axis_angle, expected)
+ self.assert_close(rot_from_axis_angle @ x_hat, expected_x_maps_to)
+
+ rot_from_quaternion = _undo_3954_upcast(
+ kornia.geometry.conversions.quaternion_to_rotation_matrix(
+ torch.tensor([0.955336489125606, 0.0, 0.0, 0.29552020666133955], device=device, dtype=dtype)
+ ),
+ dtype,
+ )
+ self.assert_close(rot_from_quaternion, expected)
+ self.assert_close(rot_from_quaternion @ x_hat, expected_x_maps_to)
+
+ def test_convention_axis_angle_is_in_radians(self, device, dtype):
+ # Convention pin: the axis-angle vector's magnitude is an angle in RADIANS. This is the
+ # trap that separates this family from angle_to_rotation_matrix in the same module, which
+ # reads DEGREES (see TestRadDegConversions.test_convention_angle_to_rotation_matrix_takes_
+ # degrees) -- the two live a few hundred lines apart and neither says so in its signature.
+ # pi/2 gives the quarter turn; feeding 90 in the belief that it is degrees gives cos/sin of
+ # 90 radians instead, a rotation of roughly 152 degrees that is nowhere near a quarter turn.
+ # Snippet used to generate expected (stdlib only):
+ # import math
+ # math.cos(math.pi / 2), math.sin(math.pi / 2) -> (6.123233995736766e-17, 1.0)
+ # math.cos(90.0), math.sin(90.0) -> (-0.4480736161291702, 0.8939966636005579)
+ quarter_turn = kornia.geometry.conversions.axis_angle_to_rotation_matrix(
+ torch.tensor([[0.0, 0.0, torch.pi / 2]], device=device, dtype=dtype)
+ )[0]
+ self.assert_close(
+ quarter_turn,
+ torch.tensor(
+ [[0.0, -1.0, 0.0], [1.0, 0.0, 0.0], [0.0, 0.0, 1.0]],
+ device=device,
+ dtype=dtype,
+ ),
+ )
+
+ read_as_degrees = kornia.geometry.conversions.axis_angle_to_rotation_matrix(
+ torch.tensor([[0.0, 0.0, 90.0]], device=device, dtype=dtype)
+ )[0]
+ self.assert_close(
+ read_as_degrees,
+ torch.tensor(
+ [
+ [-0.4480736161291702, -0.8939966636005579, 0.0],
+ [0.8939966636005579, -0.4480736161291702, 0.0],
+ [0.0, 0.0, 1.0],
+ ],
+ device=device,
+ dtype=dtype,
+ ),
+ )
+
+ @pytest.mark.xfail(
+ raises=AssertionError,
+ reason="axis_angle_to_rotation_matrix adds eps=1e-6 to theta when normalising the axis, so "
+ "the result is not orthogonal and det != 1 β€” kornia#3947",
+ strict=True,
+ )
+ def test_convention_returns_an_orthogonal_matrix_3947(self, device):
+ # Intended behavior: axis_angle_to_rotation_matrix returns a rotation matrix, i.e.
+ # R @ R.T == I and det(R) == 1 to the precision of the input dtype. It does not: the axis
+ # is normalised by (theta + eps) with eps = 1e-6 hardcoded inside the function, so the axis
+ # is shrunk by eps/theta and what comes back is a slightly scaled rotation. Measured at
+ # theta = pi/2 about +z in float64 (torch 2.9.1, cpu):
+ # det(R) = 0.9999974535249636 (should be 1.0)
+ # max|R @ R.T - I| = 2.5464750363912714e-06 (should be ~1e-16)
+ # and the error does not shrink with dtype -- float32 gives 2.5033950805664062e-06.
+ # kornia's own quaternion route is the independent reference for the intended value:
+ # quaternion_to_rotation_matrix(axis_angle_to_quaternion(v)) has det exactly 1.0 and
+ # max|R @ R.T - I| exactly 0.0 on this input, and differs from axis_angle_to_rotation_matrix
+ # by 1.273238328769466e-06 -- so the defect is in this function, not in the angle.
+ # float64 is hardcoded and the dtype fixture dropped so the literals mean one thing; the
+ # skip is visible so that on MPS, which has no float64, a raw TypeError cannot satisfy the
+ # raises=AssertionError mark instead of the assertion this pin documents. Marked
+ # xfail(strict=True) so fixing #3947 makes this XPASS and forces the mark out. Companion
+ # wart: test_wart_axis_normalisation_eps_breaks_orthogonality_3947.
+ _skip_if_dtype_unavailable(device, torch.float64)
+
+ axis_angle = torch.tensor([[0.0, 0.0, torch.pi / 2]], device=device, dtype=torch.float64)
+
+ rot = kornia.geometry.conversions.axis_angle_to_rotation_matrix(axis_angle)[0]
+
+ identity = torch.eye(3, device=device, dtype=torch.float64)
+ assert (rot @ rot.T - identity).abs().max().item() < 1e-12, (
+ "kornia#3947: axis_angle_to_rotation_matrix did not return an orthogonal matrix"
+ )
+ assert abs(torch.linalg.det(rot).item() - 1.0) < 1e-12, (
+ "kornia#3947: axis_angle_to_rotation_matrix returned a matrix whose determinant is not 1"
+ )
+
+ def test_wart_axis_normalisation_eps_breaks_orthogonality_3947(self, device):
+ # Wart pin for kornia#3947, companion to the strict xfail above: assert the CURRENT
+ # non-rotation output on BOTH branches of the function. Two cells, because the function
+ # switches at theta**2 > 1e-6 and each branch is broken for its own reason, so a fix that
+ # touches only one of them must still flip a cell here:
+ # (1) theta = pi/2 takes the general branch and the eps in the axis normalisation gives
+ # det = 0.9999974535249636 and max|R @ R.T - I| = 2.5464750363912714e-06;
+ # (2) theta = 1e-3 takes the undocumented first-order Taylor branch, which returns
+ # exactly [[1, -rz, ry], [rz, 1, -rx], [-ry, rx, 1]] -- no eps involved, but its
+ # determinant is 1 + theta**2 = 1.000001, so it is not a rotation either. The matrix
+ # is pinned at atol=rtol=0 and the determinant follows from it, so the determinant is
+ # recorded in the snippet below rather than asserted as a cell of its own.
+ # If either fails, #3947 was (partly) fixed -- flip/remove the strict xfail above. NOT a
+ # contract that these matrices must stay non-orthogonal. The eps is a hardcoded local in
+ # _compute_rotation_matrix rather than a parameter, so unlike the other wart pins in this
+ # file there is no eps to pass explicitly; cell (1) would flip if it were exposed and
+ # re-tuned, which is the point.
+ # float64 is hardcoded and the dtype fixture dropped because both literals are float64
+ # facts: at float32 the same theta = 1e-3 input has theta**2 = 1.0000001111620804e-06 and
+ # falls into the *other* branch, so cell (2) would be pinning a different code path.
+ # Snippet used to generate expected (torch only, executed on cpu float64):
+ # v = torch.tensor([[0., 0., math.pi / 2]], dtype=torch.float64)
+ # R = axis_angle_to_rotation_matrix(v)[0]
+ # torch.linalg.det(R).item() -> 0.9999974535249636
+ # (R @ R.T - torch.eye(3, dtype=torch.float64)).abs().max() -> 2.5464750363912714e-06
+ # t = torch.tensor([[0., 0., 1e-3]], dtype=torch.float64) # theta**2 == 1e-06 exactly
+ # axis_angle_to_rotation_matrix(t)[0].tolist()
+ # -> [[1.0, -0.001, 0.0], [0.001, 1.0, 0.0], [0.0, 0.0, 1.0]]
+ # torch.linalg.det(that).item() -> 1.000001
+ _skip_if_dtype_unavailable(device, torch.float64)
+
+ axis_angle_to_rotation_matrix = kornia.geometry.conversions.axis_angle_to_rotation_matrix
+ identity = torch.eye(3, device=device, dtype=torch.float64)
+
+ general = axis_angle_to_rotation_matrix(
+ torch.tensor([[0.0, 0.0, torch.pi / 2]], device=device, dtype=torch.float64)
+ )[0]
+ taylor = axis_angle_to_rotation_matrix(torch.tensor([[0.0, 0.0, 1e-3]], device=device, dtype=torch.float64))[0]
+
+ assert_close(
+ torch.linalg.det(general),
+ torch.tensor(0.9999974535249636, device=device, dtype=torch.float64),
+ atol=1e-12,
+ rtol=0.0,
+ msg=_issue_msg("kornia#3947: the general branch determinant changed"),
+ )
+ assert_close(
+ (general @ general.T - identity).abs().max(),
+ torch.tensor(2.5464750363912714e-06, device=device, dtype=torch.float64),
+ atol=1e-12,
+ rtol=0.0,
+ msg=_issue_msg("kornia#3947: the general branch orthogonality error changed"),
+ )
+ assert_close(
+ taylor,
+ torch.tensor([[1.0, -1e-3, 0.0], [1e-3, 1.0, 0.0], [0.0, 0.0, 1.0]], device=device, dtype=torch.float64),
+ atol=0.0,
+ rtol=0.0,
+ msg=_issue_msg("kornia#3947: the low-angle branch no longer returns the first-order Taylor matrix"),
+ )
+
+ @pytest.mark.xfail(
+ raises=AssertionError,
+ reason="axis_angle_to_rotation_matrix accepts only rank-2 (N, 3) input despite its own "
+ "guard message saying (*, 3) β€” kornia#3955",
+ strict=True,
+ )
+ def test_convention_accepts_any_leading_batch_dimensions_3955(self, device, dtype):
+ # Intended behavior: axis_angle_to_rotation_matrix accepts (*, 3) -- which is what its own
+ # shape guard says in the message it raises ("Input size must be a (*, 3) tensor") and what
+ # every sibling in this module does, including rotation_matrix_to_axis_angle (pinned by
+ # TestRotationMatrixToAngleAxis.test_convention_accepts_any_leading_batch_dimensions).
+ # It accepts only rank 2: the body does wxyz.unbind(dim=1) and .view(-1, 3, 3), so an
+ # unbatched (3,) raises IndexError and any extra batch dimension raises ValueError from the
+ # unbind. The asymmetry breaks composition -- aa2R(R2aa(R)) works for a (N, 3, 3) input and
+ # for nothing else, which the last two assertions pin. Written through the shared
+ # _runs_without_raising helper because the current behavior is a *raise*: a bare call would
+ # let IndexError/ValueError escape, and the mark (raises=AssertionError) would then not
+ # match, so the failure would be reported as an error rather than an XFAIL. Marked
+ # xfail(strict=True) so fixing #3955 makes this XPASS and forces the mark out. Companion
+ # wart: test_wart_only_rank_2_input_is_accepted_3955.
+ axis_angle_to_rotation_matrix = kornia.geometry.conversions.axis_angle_to_rotation_matrix
+ rotation_matrix_to_axis_angle = kornia.geometry.conversions.rotation_matrix_to_axis_angle
+
+ unbatched = torch.tensor([0.0, 0.0, 0.6], device=device, dtype=dtype)
+ rot = axis_angle_to_rotation_matrix(unbatched.reshape(1, 3))[0]
+
+ assert _runs_without_raising(axis_angle_to_rotation_matrix, unbatched), (
+ "kornia#3955: axis_angle_to_rotation_matrix rejects an unbatched (3,) input"
+ )
+ assert _runs_without_raising(axis_angle_to_rotation_matrix, unbatched.expand(2, 5, 3)), (
+ "kornia#3955: axis_angle_to_rotation_matrix rejects a (2, 5, 3) input"
+ )
+ assert _runs_without_raising(axis_angle_to_rotation_matrix, rotation_matrix_to_axis_angle(rot)), (
+ "kornia#3955: aa2R(R2aa(R)) fails for a (3, 3) rotation matrix"
+ )
+ assert _runs_without_raising(
+ axis_angle_to_rotation_matrix, rotation_matrix_to_axis_angle(rot.expand(2, 5, 3, 3))
+ ), "kornia#3955: aa2R(R2aa(R)) fails for a (2, 5, 3, 3) stack of rotation matrices"
+
+ @pytest.mark.parametrize(
+ ("shape", "error", "message"),
+ [
+ ((3,), IndexError, r"Dimension out of range"),
+ ((2, 5, 3), ValueError, r"too many values to unpack"),
+ ((1, 1, 3), ValueError, r"not enough values to unpack"),
+ ],
+ ids=["unbatched", "extra_batch_dim", "singleton_extra_batch_dim"],
+ )
+ def test_wart_only_rank_2_input_is_accepted_3955(self, device, dtype, shape, error, message):
+ # Wart pin for kornia#3955, companion to the strict xfail above: assert the CURRENT failure
+ # modes, matching on the message and not merely on the type, because the message is the
+ # evidence that these are raw Python unpacking errors leaking out of the implementation
+ # rather than kornia's own shape guard (whose message says "(*, 3)" and never fires here).
+ # Matched on the distinguishing phrase only, not the full parenthesised detail: that detail
+ # is PyTorch's and CPython's wording, so a reword upstream would flip these cells and be
+ # misread as "#3955 was partly fixed". The phrase alone still separates the three failure
+ # modes from each other and from kornia's own guard, which is all the evidence needs.
+ # Three cells: the unbatched case fails in a different place from the two over-batched ones
+ # (an indexing error inside the theta reduction, not the unbind), so a fix that only
+ # flattens the leading dimensions flips the last two and leaves the first. The (1, 1, 3)
+ # and (2, 5, 3) cells do flip together under every fix shape I could construct, but they
+ # are kept apart because they report *different* messages today, and pinning only one of
+ # them would let the other change unnoticed.
+ # If any cell fails, #3955 was (partly) fixed -- flip/remove the strict xfail above. NOT a
+ # contract that these ranks must keep raising.
+ # Snippet used to generate expected (torch only, executed on cpu float64):
+ # axis_angle_to_rotation_matrix(torch.zeros(3, dtype=torch.float64))
+ # -> IndexError: Dimension out of range (expected to be in range of [-1, 0], but got 1)
+ # axis_angle_to_rotation_matrix(torch.zeros(2, 5, 3, dtype=torch.float64))
+ # -> ValueError: too many values to unpack (expected 3)
+ # axis_angle_to_rotation_matrix(torch.zeros(1, 1, 3, dtype=torch.float64))
+ # -> ValueError: not enough values to unpack (expected 3, got 1)
+ # (the accepted ranks (1, 3) and (2, 3) return (1, 3, 3) and (2, 3, 3))
+ with pytest.raises(error, match=message):
+ kornia.geometry.conversions.axis_angle_to_rotation_matrix(torch.zeros(shape, device=device, dtype=dtype))
+
class TestRotationMatrixToAngleAxis(BaseTester):
@pytest.mark.parametrize("batch_size", (1, 2, 5))
@@ -562,6 +2100,76 @@ class TestRotationMatrixToAngleAxis(BaseTester):
self.assert_close(kornia.geometry.conversions.rotation_matrix_to_axis_angle(rmat), rvec, atol=atol, rtol=rtol)
+ def test_convention_accepts_any_leading_batch_dimensions(self, device, dtype):
+ # Convention pin (rotation_matrix_to_axis_angle has no test class under its own name; this
+ # class is the one that exercises it): the shape contract is the full (*, 3, 3) -> (*, 3),
+ # not the (N, 3, 3) -> (N, 3) its docstring states. An unbatched (3, 3) works -- that is
+ # what its own doctest passes -- and so does any number of leading batch dimensions.
+ # Expected is the true axis-angle vector computed with stdlib, not the function's output.
+ # Snippet used to generate the matrix and expected (stdlib only):
+ # import math
+ # n = math.sqrt(14.0); axis = (1 / n, 2 / n, -3 / n); theta = math.radians(170.0)
+ # R = I + sin(theta) * K + (1 - cos(theta)) * K @ K # Rodrigues, K = skew(axis)
+ # [theta * a for a in axis]
+ # -> [0.7929800678379483, 1.5859601356758966, -2.378940203513845]
+ rot = torch.tensor(
+ [
+ [-0.8430357706541933, 0.4227722475733091, -0.3324970918358584],
+ [0.14431568185875046, -0.4177198235801487, -0.8970413217671823],
+ [-0.5181348023122309, -0.8042224665289962, 0.29114008820992554],
+ ],
+ device=device,
+ dtype=dtype,
+ )
+ expected = torch.tensor(
+ [0.7929800678379483, 1.5859601356758966, -2.378940203513845], device=device, dtype=dtype
+ )
+
+ unbatched = kornia.geometry.conversions.rotation_matrix_to_axis_angle(rot)
+ assert unbatched.shape == (3,)
+ self.assert_close(unbatched, expected)
+
+ multi_batched = kornia.geometry.conversions.rotation_matrix_to_axis_angle(rot.expand(2, 5, 3, 3))
+ assert multi_batched.shape == (2, 5, 3)
+ self.assert_close(multi_batched[1, 4], expected)
+
+ def test_convention_axis_angle_roundtrip_tolerance_is_1e_6_in_float64(self, device):
+ # Convention pin: rotation_matrix_to_axis_angle composed with
+ # axis_angle_to_rotation_matrix recovers the vector only to ~1e-6, and that floor does not
+ # move with the dtype -- it is still ~1e-6 in float64, six orders worse than the machine
+ # epsilon a reader would expect from a "round-trip" and eleven orders worse than the
+ # quaternion leg (see TestAngleAxisToQuaternion.test_convention_axis_angle_quaternion_
+ # roundtrip_is_exact_in_float64, which is exact at the same angles). Anyone comparing
+ # rotations through this pair must budget 1e-6. float64 is hardcoded and the dtype fixture
+ # dropped because the claim is precisely that float64 does NOT help; MPS is skipped visibly
+ # because it has no float64 at all. The tolerance is the observed one and must not be
+ # tightened.
+ # Snippet used to generate the inputs (stdlib only):
+ # import math
+ # n = math.sqrt(14.0); axis = (1 / n, 2 / n, 3 / n)
+ # [[theta * a for a in axis] for theta in (1e-3, 0.7, 2.0, math.pi)]
+ # Measured max |roundtrip - input| at those four thetas (torch 2.9.1, cpu float64):
+ # 8.009844122083441e-07, 6.410323137862051e-07, 5.134006499929455e-07,
+ # 5.387205765927661e-07 -- so atol 1e-6 clears the worst of them by 20%.
+ _skip_if_dtype_unavailable(device, torch.float64)
+
+ axis_angle = torch.tensor(
+ [
+ [0.0002672612419124244, 0.0005345224838248488, 0.0008017837257372733],
+ [0.18708286933869706, 0.3741657386773941, 0.5612486080160912],
+ [0.5345224838248488, 1.0690449676496976, 1.6035674514745464],
+ [0.839625954181357, 1.679251908362714, 2.518877862544071],
+ ],
+ device=device,
+ dtype=torch.float64,
+ )
+
+ roundtrip = kornia.geometry.conversions.rotation_matrix_to_axis_angle(
+ kornia.geometry.conversions.axis_angle_to_rotation_matrix(axis_angle)
+ )
+
+ self.assert_close(roundtrip, axis_angle, atol=1e-6, rtol=0.0)
+
class TestRadDegConversions(BaseTester):
def test_pi(self):
@@ -1933,6 +3541,284 @@ class TestEulerFromQuaternion(BaseTester):
self.assert_close(q.y.abs(), qy.abs())
self.assert_close(q.z.abs(), qz.abs())
+ def test_convention_roll_is_x_pitch_is_y_yaw_is_z(self, device, dtype):
+ # Convention pin: the three returned angles are (roll, pitch, yaw) in that order, and they
+ # are rotations about x, y and z respectively -- a rotation about a single axis puts its
+ # angle in exactly one slot and leaves the other two at zero, which no permutation of the
+ # naming could reproduce. The return is a TUPLE of three separate tensors, not a stacked
+ # (*, 3) tensor, so it cannot be indexed or sliced like one; that is pinned first.
+ # The angle is 0.6 rad rather than a quarter turn so the pin stays far from the pitch =
+ # +-pi/2 gimbal lock where this function does not recover the input at all.
+ # Snippet used to generate the inputs (stdlib only):
+ # import math
+ # for each axis: q = (cos(0.3), sin(0.3) * axis) with 0.3 = theta / 2
+ # cos(0.3), sin(0.3) -> (0.955336489125606, 0.29552020666133955)
+ w = torch.tensor(0.955336489125606, device=device, dtype=dtype)
+ s = torch.tensor(0.29552020666133955, device=device, dtype=dtype)
+ zero = torch.tensor(0.0, device=device, dtype=dtype)
+ expected_angle = torch.tensor(0.6, device=device, dtype=dtype)
+
+ about_x = euler_from_quaternion(w, s, zero, zero)
+ assert isinstance(about_x, tuple)
+ assert len(about_x) == 3
+ self.assert_close(about_x[0], expected_angle)
+ self.assert_close(about_x[1], zero)
+ self.assert_close(about_x[2], zero)
+
+ about_y = euler_from_quaternion(w, zero, s, zero)
+ self.assert_close(about_y[0], zero)
+ self.assert_close(about_y[1], expected_angle)
+ self.assert_close(about_y[2], zero)
+
+ about_z = euler_from_quaternion(w, zero, zero, s)
+ self.assert_close(about_z[0], zero)
+ self.assert_close(about_z[1], zero)
+ self.assert_close(about_z[2], expected_angle)
+
+ def test_convention_euler_and_quaternion_are_mutual_inverses(self, device, dtype):
+ # Convention pin: away from gimbal lock, euler_from_quaternion and quaternion_from_euler
+ # invert each other exactly -- the same three angles come back, with their signs, and so
+ # do the same four quaternion coefficients. Pinned at |pitch| = 0.7 < pi/4-ish and three
+ # distinct non-symmetric angles so neither a permutation nor a sign flip survives. (At
+ # pitch = +-pi/2 the pair is NOT a mutual inverse; that failure is out of scope here.)
+ # Snippet used to generate expected (stdlib only):
+ # the round-trip is the identity on (roll, pitch, yaw) = (0.3, 0.7, 1.1)
+ # quaternion_from_euler(0.3, 0.7, 1.1) at float64 ->
+ # [0.8186292656554958, -0.057539988180335386, 0.3624200943552256, 0.44179967222724353]
+ # which is qz (x) qy (x) qx with qa = (cos(a/2), sin(a/2) * axis) -- see
+ # TestQuaternionFromEuler.test_convention_composition_is_rz_ry_rx
+ roll = torch.tensor(0.3, device=device, dtype=dtype)
+ pitch = torch.tensor(0.7, device=device, dtype=dtype)
+ yaw = torch.tensor(1.1, device=device, dtype=dtype)
+
+ quaternion = quaternion_from_euler(roll, pitch, yaw)
+ roll_back, pitch_back, yaw_back = euler_from_quaternion(*quaternion)
+
+ self.assert_close(roll_back, roll)
+ self.assert_close(pitch_back, pitch)
+ self.assert_close(yaw_back, yaw)
+
+ quaternion_back = quaternion_from_euler(roll_back, pitch_back, yaw_back)
+ for component, component_back in zip(quaternion, quaternion_back):
+ self.assert_close(component_back, component)
+
+ @pytest.mark.parametrize(
+ ("zero_sign", "expected_roll"),
+ [(-0.0, -torch.pi), (0.0, torch.pi)],
+ ids=["negative_zero_gives_minus_pi", "positive_zero_gives_plus_pi"],
+ )
+ def test_convention_roll_range_is_closed_with_signed_zero_endpoint(self, device, zero_sign, expected_roll):
+ # Convention pin for the CLOSED [-pi, pi] range documented on euler_from_quaternion: roll
+ # comes from atan2, which returns the +-pi endpoint EXACTLY, its sign taken from the
+ # signed zero of the first argument. The input is the half-turn about x, where that
+ # argument is 2 * (w*x + y*z) = +-0.0 tracking the sign of w, and the second argument is
+ # 1 - 2 * (x**2 + y**2) = -1 exactly, so IEEE 754 atan2(+-0.0, -1.0) mandates the result:
+ # a bitwise fact, not a rounding accident. A range check written from the half-open
+ # (-pi, pi] form (roll > -pi) fails on the negative-zero input. float64 is hardcoded and
+ # the dtype fixture dropped because the docstring quotes the float64 endpoints; the
+ # signed-zero sign rule itself is dtype-independent.
+ # Snippet used to generate expected (torch only, executed on cpu float64):
+ # euler_from_quaternion(w=-0.0, x=1.0, y=0.0, z=-0.0)[0] -> -3.141592653589793 == -pi
+ # euler_from_quaternion(w=0.0, x=1.0, y=0.0, z=0.0)[0] -> 3.141592653589793 == +pi
+ _skip_if_dtype_unavailable(device, torch.float64)
+
+ w = torch.tensor([zero_sign], device=device, dtype=torch.float64)
+ x = torch.tensor([1.0], device=device, dtype=torch.float64)
+ y = torch.tensor([0.0], device=device, dtype=torch.float64)
+ z = torch.tensor([zero_sign], device=device, dtype=torch.float64)
+
+ roll, _, _ = euler_from_quaternion(w, x, y, z)
+
+ assert roll.item() == expected_roll, (
+ f"roll for the w = {zero_sign} half-turn is {roll.item()}, not the exact {expected_roll} endpoint"
+ )
+
+ @pytest.mark.xfail(
+ raises=AssertionError,
+ reason="euler_from_quaternion has no gimbal-lock branch, so at pitch = Β±pi/2 the returned "
+ "triple does not represent the input rotation β€” kornia#3950",
+ strict=True,
+ )
+ def test_convention_roundtrip_holds_at_gimbal_lock_3950(self, device):
+ # Intended behavior: euler_from_quaternion returns *a* triple representing the input
+ # rotation. At pitch = Β±pi/2 (gimbal lock) roll and yaw are individually undetermined --
+ # only their sum or difference is -- so no library can return the input triple back, but a
+ # correct implementation still returns a triple whose rotation matrix is the input's, which
+ # is what this pin asserts. There is no gimbal-lock branch at all: roll and yaw come from
+ # atan2 of two quantities that both cancel there, and the result is simply wrong. For
+ # (roll, pitch, yaw) = (0.1, pi/2, 0.2) in float64 the reconstructed rotation is far from
+ # the input -- by a margin that varies with rounding, so no figure is quoted here -- and
+ # random (roll, yaw) at pitch = +pi/2 fail the same way, while |pitch| < pi/4 round trips
+ # to rounding. float64 is hardcoded and the dtype fixture
+ # dropped because the returned triple is wildly dtype-dependent here (see the companion
+ # wart), and the skip is visible so a raw TypeError on MPS, which has no float64, cannot
+ # satisfy the raises=AssertionError mark instead of the assertion. Marked xfail(strict=True)
+ # so fixing #3950 makes this XPASS and forces the mark out. Companion wart:
+ # test_wart_gimbal_lock_returns_a_wrong_triple_3950.
+ _skip_if_dtype_unavailable(device, torch.float64)
+
+ roll = torch.tensor(0.1, device=device, dtype=torch.float64)
+ pitch = torch.tensor(torch.pi / 2, device=device, dtype=torch.float64)
+ yaw = torch.tensor(0.2, device=device, dtype=torch.float64)
+
+ quaternion = quaternion_from_euler(roll, pitch, yaw)
+ roundtrip = quaternion_from_euler(*euler_from_quaternion(*quaternion))
+
+ rot_in = kornia.geometry.conversions.quaternion_to_rotation_matrix(torch.stack(quaternion))
+ rot_back = kornia.geometry.conversions.quaternion_to_rotation_matrix(torch.stack(roundtrip))
+ assert (rot_in - rot_back).abs().max().item() < 1e-12, (
+ "kornia#3950: the euler triple returned at pitch = pi/2 does not represent the input rotation"
+ )
+
+ @pytest.mark.parametrize("sign", [1.0, -1.0], ids=["pitch_plus_pi_over_2", "pitch_minus_pi_over_2"])
+ def test_wart_gimbal_lock_returns_a_wrong_triple_3950(self, device, sign):
+ # Wart pin for kornia#3950, companion to the strict xfail above. It pins the two facts about
+ # gimbal lock that are STABLE, and deliberately pins no exact triple.
+ #
+ # Pinning the returned triples themselves ((pi/2, pi/2, pi/2) at +pi/2 and (0, -pi/2, pi/2)
+ # at -pi/2 on this build) is not an option: those values are not reproducible. roll and yaw
+ # come from atan2 of two quantities that cancel to ~1e-17 there, so which way they
+ # cancel is decided by rounding. Perturbing the input pitch by a single ulp on this very
+ # build changes the +pi/2 triple to (0.15500, pi/2, 0.35877) at -2 ulp and to
+ # (-3.12597, pi/2, -3.07917) at +1 ulp; a review on torch 2.12.0 saw different triples again
+ # on the unperturbed input. Kornia declares torch>=2.0.0, so pinning any one of them makes
+ # the suite red on builds the pin was never measured against, for a value that is not the
+ # defect being tracked.
+ #
+ # What this pin asserts instead:
+ # 1. pitch_back is +-pi/2 to a tolerance -- the asin saturates. Note this fact SURVIVES a
+ # fix to #3950 (a correct gimbal-lock branch still reports pitch = +-pi/2); it is
+ # pinned as the structural claim the strict xfail above does not make, not as a defect
+ # indicator.
+ # 2. the round-tripped rotation is far from the input -- this is the defect, and the half
+ # of this pin that flips when #3950 is fixed.
+ #
+ # Assertion 1 is a TOLERANCE and not exact equality, which matters. At gimbal lock the asin
+ # argument is 1 - O(eps), and asin(1 - d) ~= pi/2 - sqrt(2d), so one ulp of slack in the
+ # argument amplifies to a sqrt-scale error in the output: sqrt(2 * eps_f64) = 2.107e-08.
+ # Whether the argument rounds to exactly 1.0 or to one ulp below is decided by the last bit
+ # of the sin/cos computation upstream, so it moves between torch builds, backends and
+ # vectorisation paths. torch 2.12.0 reports -1.5707963057214724 for the -pi/2 cell, which is
+ # pi/2 - 2.1073424116835326e-08 -- agreeing with sqrt(2 * eps) to eight significant figures.
+ # Exact equality here is therefore red on 2.12; the tolerance is what keeps the cell green.
+ # Reproducing the 2.12 value locally needs the right probe: perturbing the input pitch, or any component
+ # by a single ulp, does NOT move pitch_back at all (a +-1 ulp sweep over all four quaternion
+ # components returns one distinct value, as does a +-200 ulp input-pitch sweep). Perturbing
+ # w -- the component the saturation actually depends on -- by two or more ulps walks up the
+ # same sqrt-scale family and reproduces the 2.12.0 figure bit-for-bit: w - 2 ulp gives
+ # -1.5707963057214724 on the -pi/2 cell, and w - 3 ulp gives +1.5707963057214724 on the
+ # +pi/2 cell. The rule for the next pin here is therefore to perturb the intermediate the
+ # branch depends on, and to go wider than one ulp -- not to assume the input is the probe.
+ # Tolerance sizing stays mechanism-based rather than sampled: dev = sqrt(2 * k * eps) for an
+ # argument k ulps below 1.0, so 1e-6 is only reached at k ~ 2250, far beyond the one-to-few
+ # ulps a cross-build rounding difference can move it, and far below any real defect, which
+ # would move pitch by O(1). Note the deviation is NOT bounded by the values above: pushing w
+ # to -20000 ulp reaches 2.5e-06 and does cross the tolerance. That is not a realistic
+ # rounding difference, but it is why the sizing argument is the mechanism and the measured
+ # figures here (2.1e-08 at w - 2 ulp, 5.4e-08 at w - 10 ulp) are sample points, not bounds.
+ #
+ # The 1e-9 floor in 2 is likewise a chosen threshold with margin, NOT a measured bound:
+ # a correct gimbal-lock branch round trips to ~1e-16, and widening the probe drives the
+ # sample minimum steadily toward 0, which is why no sampled extremum is quoted as a bound.
+ #
+ # Two cells, one per sign, because a fix could plausibly add a gimbal-lock branch for one
+ # sign only or get the roll/yaw split sign wrong; the strict xfail above only covers +pi/2,
+ # so the -pi/2 cell here is the only coverage of that sign. If either cell fails, #3950 was
+ # (partly) fixed -- flip/remove the strict xfail above. NOT a contract that the current
+ # output is correct: any triple whose rotation matrix matches the input is an acceptable
+ # replacement, and such a triple would fail assertion 2 as intended.
+ # float64 is hardcoded and the dtype fixture dropped because the round-trip margin is a
+ # float64 fact; the skip is visible so a raw TypeError on MPS, which has no float64, cannot
+ # pass for the assertion.
+ _skip_if_dtype_unavailable(device, torch.float64)
+
+ pitch_in = sign * torch.pi / 2
+ quaternion = quaternion_from_euler(
+ torch.tensor(0.1, device=device, dtype=torch.float64),
+ torch.tensor(pitch_in, device=device, dtype=torch.float64),
+ torch.tensor(0.2, device=device, dtype=torch.float64),
+ )
+
+ roll_back, pitch_back, yaw_back = euler_from_quaternion(*quaternion)
+
+ assert abs(pitch_back.item() - pitch_in) < 1e-6, (
+ f"kornia#3950: pitch no longer saturates to {pitch_in} at gimbal lock (got {pitch_back.item()!r})"
+ )
+
+ roundtrip = quaternion_from_euler(roll_back, pitch_back, yaw_back)
+ rot_in = kornia.geometry.conversions.quaternion_to_rotation_matrix(torch.stack(quaternion))
+ rot_back = kornia.geometry.conversions.quaternion_to_rotation_matrix(torch.stack(roundtrip))
+ error = (rot_in - rot_back).abs().max().item()
+
+ assert error > 1e-9, (
+ f"kornia#3950: the triple returned at pitch = {pitch_in} now reproduces the input "
+ f"rotation to {error} -- the gimbal-lock defect looks fixed"
+ )
+
+ @pytest.mark.xfail(
+ raises=AssertionError,
+ reason="euler_from_quaternion does not normalise its input, so a non-unit quaternion gives "
+ "a silently wrong triple β€” kornia#3953",
+ strict=True,
+ )
+ def test_convention_euler_from_quaternion_normalizes_its_input_3953(self, device, dtype):
+ # Intended behavior: the euler angles of a quaternion depend only on the rotation it
+ # represents, so rescaling the quaternion must not change them -- which is what the
+ # scale-safe siblings do (quaternion_to_rotation_matrix normalises internally and returns a
+ # bit-identical matrix for 2q; quaternion_to_axis_angle is homogeneous by construction).
+ # euler_from_quaternion does not normalise and does not check: feeding 2q returns
+ # [1.6560585860248003, 1.5707963267948966, 2.1048169977173687] instead of the (0.3, 0.7,
+ # 1.1) the unit quaternion gives -- and note the middle component, which is exactly pi/2:
+ # the unnormalised argument saturates the asin, so a merely-scaled input is reported as
+ # gimbal-locked. Marked xfail(strict=True) so fixing #3953 makes this XPASS and forces the
+ # mark out. Companion wart: test_wart_euler_from_quaternion_ignores_the_norm_3953; the
+ # quaternion_exp_to_log half of the same issue is pinned in TestQuaternionExpToLog.
+ roll = torch.tensor(0.3, device=device, dtype=dtype)
+ pitch = torch.tensor(0.7, device=device, dtype=dtype)
+ yaw = torch.tensor(1.1, device=device, dtype=dtype)
+ quaternion = quaternion_from_euler(roll, pitch, yaw)
+
+ out = torch.stack(euler_from_quaternion(*[2.0 * component for component in quaternion]))
+
+ assert_close(
+ out,
+ torch.stack((roll, pitch, yaw)),
+ msg=_issue_msg("kornia#3953: euler_from_quaternion did not normalise its input"),
+ )
+
+ def test_wart_euler_from_quaternion_ignores_the_norm_3953(self, device, dtype):
+ # Wart pin for kornia#3953, companion to the strict xfail above: assert the CURRENT triple
+ # for a scaled-up quaternion. This is a separate cell from the quaternion_exp_to_log cells
+ # in TestQuaternionExpToLog because the two functions are independent code paths and a fix
+ # to one leaves the other broken, which would leave the other strict xfail silently XFAIL.
+ # If it fails, the euler half of #3953 was fixed -- flip/remove the strict xfail above.
+ # NOT a contract that a scaled quaternion must keep producing this triple.
+ # Snippet used to generate expected (torch only, executed on cpu float64):
+ # t = lambda x: torch.tensor(x, dtype=torch.float64)
+ # q = quaternion_from_euler(t(0.3), t(0.7), t(1.1))
+ # -> [0.8186292656554958, -0.057539988180335386, 0.3624200943552256, 0.44179967222724353]
+ # [x.item() for x in euler_from_quaternion(*q)]
+ # -> [0.2999999999999999, 0.6999999999999998, 1.0999999999999999] (the unit input)
+ # [x.item() for x in euler_from_quaternion(*[2 * c for c in q])]
+ # -> [1.6560585860248003, 1.5707963267948966, 2.1048169977173687]
+ # (float32: [1.656058430671692, 1.5707963705062866, 2.1048169136047363];
+ # float16: [1.6572265625, 1.5703125, 2.10546875];
+ # bfloat16: [1.6484375, 1.5703125, 2.109375] -- all within the dtype's default tolerance
+ # of the float64 literals below)
+ quaternion = quaternion_from_euler(
+ torch.tensor(0.3, device=device, dtype=dtype),
+ torch.tensor(0.7, device=device, dtype=dtype),
+ torch.tensor(1.1, device=device, dtype=dtype),
+ )
+
+ out = torch.stack(euler_from_quaternion(*[2.0 * component for component in quaternion]))
+
+ assert_close(
+ out,
+ torch.tensor([1.6560585860248003, 1.5707963267948966, 2.1048169977173687], device=device, dtype=dtype),
+ msg=_issue_msg("kornia#3953: euler_from_quaternion no longer ignores the quaternion norm"),
+ )
+
class TestQuaternionFromEuler(BaseTester):
def test_smoke(self, device, dtype):
@@ -2024,6 +3910,72 @@ class TestQuaternionFromEuler(BaseTester):
# out = [tf3.euler.quat2euler((qw[i], qx[i], qy[i], qz[i])) for i in range(num_samples)]
# out = torch.tensor(out, device=device, dtype=dtype)
+ def test_convention_composition_is_rz_ry_rx(self, device, dtype):
+ # Convention pin: "XYZ convention" in the docstring does not say whether the three
+ # rotations are applied about the fixed axes or about the axes carried along by the body,
+ # and the four candidate products differ enormously. The actual composition is
+ # R = Rz(yaw) @ Ry(pitch) @ Rx(roll)
+ # i.e. extrinsic X -> Y -> Z about the FIXED axes (equivalently intrinsic Z-Y'-X''), with
+ # roll about x, pitch about y and yaw about z. Three distinct non-symmetric angles are
+ # required: a symmetric or single-axis input cannot separate the four candidates. Measured
+ # max |R - candidate| at (0.3, 0.7, 1.1) in float64:
+ # Rz@Ry@Rx 0.0 (1.11e-16 when the product is built from math.cos/math.sin literals),
+ # Rx@Ry@Rz 0.6404683155788216, Ry@Rz@Rx 0.5484888138736672, Rx@Rz@Ry 0.2503184512807922.
+ # The three rejected products are asserted to stay above 0.2 so the discrimination itself
+ # is executable rather than a claim in a comment; at bfloat16, the coarsest dtype run, the
+ # accepted product is still within 3.90625e-03 and the nearest rejected one at 0.25.
+ # The return is a TUPLE of four separate tensors, not a stacked (*, 4) tensor; pinned first.
+ # Snippet used to generate the elementary matrices (stdlib only):
+ # import math
+ # math.cos(0.3), math.sin(0.3) -> (0.955336489125606, 0.29552020666133955)
+ # math.cos(0.7), math.sin(0.7) -> (0.7648421872844885, 0.644217687237691)
+ # math.cos(1.1), math.sin(1.1) -> (0.4535961214255773, 0.8912073600614354)
+ rot_x = torch.tensor(
+ [
+ [1.0, 0.0, 0.0],
+ [0.0, 0.955336489125606, -0.29552020666133955],
+ [0.0, 0.29552020666133955, 0.955336489125606],
+ ],
+ device=device,
+ dtype=dtype,
+ )
+ rot_y = torch.tensor(
+ [
+ [0.7648421872844885, 0.0, 0.644217687237691],
+ [0.0, 1.0, 0.0],
+ [-0.644217687237691, 0.0, 0.7648421872844885],
+ ],
+ device=device,
+ dtype=dtype,
+ )
+ rot_z = torch.tensor(
+ [
+ [0.4535961214255773, -0.8912073600614354, 0.0],
+ [0.8912073600614354, 0.4535961214255773, 0.0],
+ [0.0, 0.0, 1.0],
+ ],
+ device=device,
+ dtype=dtype,
+ )
+
+ quaternion = quaternion_from_euler(
+ torch.tensor(0.3, device=device, dtype=dtype),
+ torch.tensor(0.7, device=device, dtype=dtype),
+ torch.tensor(1.1, device=device, dtype=dtype),
+ )
+ assert isinstance(quaternion, tuple)
+ assert len(quaternion) == 4
+
+ rot = _undo_3954_upcast(
+ kornia.geometry.conversions.quaternion_to_rotation_matrix(torch.stack(quaternion)), dtype
+ )
+
+ self.assert_close(rot, rot_z @ rot_y @ rot_x)
+
+ assert (rot - rot_x @ rot_y @ rot_z).abs().max() > 0.2
+ assert (rot - rot_y @ rot_z @ rot_x).abs().max() > 0.2
+ assert (rot - rot_x @ rot_z @ rot_y).abs().max() > 0.2
+
@pytest.mark.parametrize("batch_size", (None, 1, 2, 5))
def test_vector_to_skew_symmetric_matrix(batch_size, device, dtype):
@@ -2101,3 +4053,95 @@ class TestAxisAngleToRotationMatrix:
)
R = axis_angle_to_rotation_matrix(aa)
assert R.shape == (3, 3, 3)
+
+
+# Module-level pins for kornia#3956: the four deprecated aliases of this module
+# (angle_axis_to_rotation_matrix, rotation_matrix_to_angle_axis, quaternion_to_angle_axis,
+# angle_axis_to_quaternion) are not the site of the defect -- the root cause is
+# _emit_deprecation_warning in kornia/core/_compat.py, which wraps its warnings.warn call in
+# warnings.simplefilter("always", DeprecationWarning) / simplefilter("default", DeprecationWarning)
+# and so rewrites the PROCESS-GLOBAL filter list on every call. Every deprecated symbol in kornia
+# is therefore affected, which is why these live at module level rather than in one symbol's class,
+# following the module-level wart precedent above. Both pins run inside warnings.catch_warnings()
+# so that the filter mutation they provoke cannot leak into the rest of the suite: this bug is
+# contagious across tests, and an unisolated pin would silently disarm every other test's warning
+# discipline.
+_DEPRECATED_ALIASES = [
+ ("angle_axis_to_rotation_matrix", [[0.0, 0.0, 0.6]]),
+ ("rotation_matrix_to_angle_axis", [[1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0]]),
+ ("quaternion_to_angle_axis", [1.0, 0.0, 0.0, 0.0]),
+ ("angle_axis_to_quaternion", [0.1, 0.2, 0.3]),
+]
+
+
+ raises=AssertionError,
+ reason="_emit_deprecation_warning forces the DeprecationWarning filter to 'always', so "
+ "-W error::DeprecationWarning cannot escalate it β€” kornia#3956",
+ strict=True,
+)
[email protected](("alias_name", "arg"), _DEPRECATED_ALIASES, ids=[name for name, _ in _DEPRECATED_ALIASES])
+def test_convention_deprecated_alias_warning_can_be_escalated_to_an_error_3956(alias_name, arg):
+ # Intended behavior: a DeprecationWarning emitted by kornia obeys the caller's warning filters,
+ # so a project that runs under -W error::DeprecationWarning (or pytest's filterwarnings =
+ # error) sees the call fail and can find its deprecated usages. It does not:
+ # _emit_deprecation_warning installs simplefilter("always", DeprecationWarning) immediately
+ # before warnings.warn, which overrides the caller's "error" entry, so the warning is printed
+ # and execution continues. The escalated DeprecationWarning is caught by type rather than
+ # through the shared _runs_without_raising helper: that helper treats *any* exception as the
+ # awaited raise, so an unrelated TypeError from the alias would set escalated=True, pass the
+ # body, and -- under xfail(strict=True) -- be reported as XPASS(strict) on a test named
+ # ..._can_be_escalated_to_an_error_3956, which reads as "#3956 is fixed, drop the mark".
+ # Catching DeprecationWarning specifically lets any other exception propagate and be reported
+ # as an error instead. (The #3955 call sites keep the broad helper on purpose: there an
+ # unrelated exception makes the assertion *fail*, which is already the correct report.)
+ # Marked xfail(strict=True) so fixing #3956 makes all four cases XPASS and forces the mark out.
+ # Companion wart: test_wart_deprecated_alias_rewrites_the_global_warning_filters_3956.
+ alias = getattr(kornia.geometry.conversions, alias_name)
+ tensor = torch.tensor(arg)
+
+ with warnings.catch_warnings():
+ warnings.simplefilter("error", DeprecationWarning)
+ try:
+ alias(tensor)
+ except DeprecationWarning:
+ escalated = True
+ else:
+ escalated = False
+
+ assert escalated, f"kornia#3956: {alias_name} did not raise under simplefilter('error', DeprecationWarning)"
+
+
[email protected](("alias_name", "arg"), _DEPRECATED_ALIASES, ids=[name for name, _ in _DEPRECATED_ALIASES])
+def test_wart_deprecated_alias_rewrites_the_global_warning_filters_3956(alias_name, arg):
+ # Wart pin for kornia#3956, companion to the strict xfail above: assert that a single alias
+ # call CURRENTLY leaves two entries of its own at the head of the process-global filter list,
+ # starting from an empty one. Four cells, one per alias, because all four are separate
+ # @deprecated call sites and a fix could plausibly be applied per decorator rather than in
+ # _emit_deprecation_warning; the 'default' entry (pushed by the finally clause) and the
+ # 'always' entry (pushed before the warn) are both asserted, since a half fix that drops only
+ # the "always" would leave the caller's filters just as clobbered.
+ # If any cell fails, #3956 was (partly) fixed in kornia/core/_compat.py -- flip/remove the
+ # strict xfail above. NOT a contract that calling a deprecated alias must mutate global state.
+ # Snippet used to generate expected (stdlib + torch, executed on cpu):
+ # with warnings.catch_warnings():
+ # warnings.resetwarnings()
+ # kornia.geometry.conversions.angle_axis_to_quaternion(torch.tensor([0., 0., 0.6]))
+ # warnings.filters[:2]
+ # -> [('default', None, <class 'DeprecationWarning'>, None, 0),
+ # ('always', None, <class 'DeprecationWarning'>, None, 0)]
+ alias = getattr(kornia.geometry.conversions, alias_name)
+ tensor = torch.tensor(arg)
+
+ with warnings.catch_warnings():
+ warnings.resetwarnings()
+ assert warnings.filters == [], "the filter list was not empty before the call, so the pin below is not clean"
+
+ alias(tensor)
+
+ head = warnings.filters[:2]
+
+ assert head == [
+ ("default", None, DeprecationWarning, None, 0),
+ ("always", None, DeprecationWarning, None, 0),
+ ], f"kornia#3956: {alias_name} no longer rewrites the global DeprecationWarning filters; got {head}"