π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
fix(geometry): make axis_angle_to_rotation_matrix return orthogonal matrices (kornia#3947) (#3989)
lawliet6fa75d648b44
diff --git a/kornia/geometry/conversions.py b/kornia/geometry/conversions.pyindex 636909105..a147f62f9 100644--- a/kornia/geometry/conversions.py+++ b/kornia/geometry/conversions.py@@ -424,29 +424,7 @@ def axis_angle_to_rotation_matrix(axis_angle: torch.Tensor) -> torch.Tensor:to this function, returning an equal result β see the alias warningbelow- .. 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`` (torch 2.9.1, cpu β the trailing digits are- backend-dependent; the magnitude is the point); 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:+ .. 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``.@@ -491,9 +469,9 @@ def axis_angle_to_rotation_matrix(axis_angle: torch.Tensor) -> torch.Tensor:if not axis_angle.shape[-1] == 3:raise ValueError(f"Input size must be a (*, 3) tensor. Got {axis_angle.shape}")- def _compute_rotation_matrix(axis_angle: torch.Tensor, theta2: torch.Tensor, eps: float = 1e-6) -> torch.Tensor:+ def _compute_rotation_matrix(axis_angle: torch.Tensor, theta2: torch.Tensor) -> torch.Tensor:theta = torch.sqrt(theta2.clamp(min=1e-12)) # clamping to ensure no nan gradients- wxyz = axis_angle / (theta.unsqueeze(-1) + eps) # (B, 3)+ wxyz = axis_angle / theta.unsqueeze(-1) # (B, 3)wx, wy, wz = wxyz.unbind(dim=1) # (B,)cos_theta = torch.cos(theta)@@ -530,18 +508,27 @@ def axis_angle_to_rotation_matrix(axis_angle: torch.Tensor) -> torch.Tensor:def _compute_rotation_matrix_taylor(axis_angle: torch.Tensor) -> torch.Tensor:rx, ry, rz = axis_angle.unbind(-1)k_one = torch.ones_like(rx)+ k_half = 0.5 * k_one+ rx2, ry2, rz2 = rx * rx, ry * ry, rz * rz+ rxry, rxrz, ryrz = rx * ry, rx * rz, ry * rz++ # second-order Taylor expansion of Rodrigues' formula:+ # R = I + [v]x + [v]x^2 / 2+ # the first-order truncation had det = 1 + theta^2; the second-order+ # truncation has det = 1 + theta^4 / 4, so the matrix is a rotation to+ # the working precision across the whole low-angle branchrot = torch.stack([- k_one,- -rz,- ry,- rz,- k_one,- -rx,- -ry,- rx,- k_one,+ k_one - k_half * (ry2 + rz2),+ -rz + k_half * rxry,+ ry + k_half * rxrz,+ rz + k_half * rxry,+ k_one - k_half * (rx2 + rz2),+ -rx + k_half * ryrz,+ -ry + k_half * rxrz,+ rx + k_half * ryrz,+ k_one - k_half * (rx2 + ry2),],dim=-1,).view(-1, 3, 3)@@ -578,11 +565,12 @@ def rotation_matrix_to_axis_angle(rotation_matrix: torch.Tensor) -> torch.Tensor:math:`(3,)` and :math:`(2, 5, 3)` results above cannot be fedstraight 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>`_+ :func:`~kornia.geometry.conversions.axis_angle_to_rotation_matrix`+ is accurate to about ``5e-09`` in ``float64`` β measured+ ``2.0e-12`` at ``theta = 1e-3`` and ``4.2e-09`` at ``theta = pi``+ about ``(1, 2, 3)/sqrt(14)`` β the latter is+ :func:`~kornia.geometry.conversions.rotation_matrix_to_axis_angle`'s+ own conditioning near the ``pi`` singularity- 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)``@@ -2840,11 +2828,9 @@ def camtoworld_to_worldtocam_Rt(R: torch.Tensor, t: torch.Tensor) -> tuple[torchand ``1e-15`` in ``float64``, over 64 unit-normalized randomquaternions turned into rotations via:func:`~kornia.geometry.conversions.quaternion_to_rotation_matrix`- β an orthogonality-preserving route; contrast- :func:`~kornia.geometry.conversions.axis_angle_to_rotation_matrix`,- whose own non-orthogonality (`#3947- <https://github.com/kornia/kornia/issues/3947>`_) inflates this- figure to ``3.16e-06`` β with matching random translations, both+ β an orthogonality-preserving route, as is+ :func:`~kornia.geometry.conversions.axis_angle_to_rotation_matrix`+ β with matching random translations, bothdrawn from ``torch.Generator().manual_seed(seed)``, ``seed=0`` β afew ulps of the entries. Read the exponent, not the digits: themaximum moves with the draw (``4.77e-07`` to ``8.34e-07``, anddiff --git a/tests/geometry/test_conversions.py b/tests/geometry/test_conversions.pyindex acf87e814..dab05d69f 100644--- a/tests/geometry/test_conversions.py+++ b/tests/geometry/test_conversions.py@@ -2198,29 +2198,21 @@ class TestAngleAxisToRotationMatrix(BaseTester):),)- @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. The measured- # determinant and orthogonality error at theta = pi/2 about +z are asserted executably by- # the companion wart named at the end of this comment, and are not restated here so that- # they cannot drift apart from it.+ # Regression test for kornia#3947. The function used to normalise the axis by+ # (theta + eps) with eps = 1e-6 hardcoded inside _compute_rotation_matrix, so the axis+ # was shrunk by eps/theta and what came back was a slightly scaled rotation. Measured at+ # theta = pi/2 about +z in float64 (torch 2.9.1, cpu) before the fix:+ # det(R) = 0.9999974535249636 (should be 1.0)+ # max|R @ R.T - I| = 2.5464750363912714e-06 (should be ~1e-16)+ # and the error did not shrink with dtype -- float32 gave 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 that figure means 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.+ # max|R @ R.T - I| exactly 0.0 on this input -- so the defect was 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 assertions this test documents._skip_if_dtype_unavailable(device, torch.float64)axis_angle = torch.tensor([[0.0, 0.0, torch.pi / 2]], device=device, dtype=torch.float64)@@ -2235,60 +2227,35 @@ class TestAngleAxisToRotationMatrix(BaseTester):"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+ def test_convention_both_branches_are_orthogonal_3947(self, device):+ # Regression test for kornia#3947 covering BOTH branches of the function, which switch at+ # theta**2 > 1e-6 and were each broken for its own reason before the fix:+ # (1) theta = pi/2 takes the general branch and the eps in the axis normalisation gave# 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.- # A third, float32 cell backs the docstring's "float32 is no better" figure- # (2.5033950805664062e-06 on the same general-branch input), which was otherwise asserted- # nowhere: an eps scaled to the input dtype's machine epsilon could fix float32 while- # leaving float64, flipping no test but falsifying the docstring. Its atol is 1e-6, sized- # to backend variance rather than to cpu jitter: float32 trig/matmul kernels differ by a- # few ulp per entry across backends, and a 2-ulp move of one entry of R already shifts- # max|R R^T - I| by 2.4e-07, so a dot-product-jitter budget would flip on a kernel change- # with no kornia change. 1e-6 still discriminates: a #3947 fix drives the error to a few- # eps_float32 (~2.4e-07), well outside [2.5e-06 - 1e-6, 2.5e-06 + 1e-6].+ # (2) theta = 1e-3 takes the low-angle branch, which returned the first-order Taylor+ # matrix [[1, -rz, ry], [rz, 1, -rx], [-ry, rx, 1]] with det = 1 + theta**2 = 1.000001.+ # The low-angle branch now returns the second-order Taylor expansion R = I + [v]x + [v]x^2/2,+ # whose determinant is 1 + theta**4 / 4 -- at theta = 1e-3 that is 1 + 2.5e-13, a rotation+ # to the working precision -- so both branches must now pass the same orthogonality checks.+ # The general branch must also agree with the quaternion route on a generic (non-axis+ # aligned) rotation, which is where the eps defect showed up as an axis-dependent error.+ # float64 is hardcoded and the dtype fixture dropped because both cells 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 exercising 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+ # torch.linalg.det(R).item() -> 1.0+ # (R @ R.T - torch.eye(3, dtype=torch.float64)).abs().max() -> 0.0# 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- axis_angle_to_rotation_matrix = kornia.geometry.conversions.axis_angle_to_rotation_matrix-- # The float32 cell runs BEFORE the float64 gate so a float64-less device (MPS) still- # asserts the docstring's "float32 is no better" figure instead of skipping it away --- # skipping it would re-open the dtype-scoped half-fix this cell exists to catch.- general_f32 = axis_angle_to_rotation_matrix(- torch.tensor([[0.0, 0.0, torch.pi / 2]], device=device, dtype=torch.float32)- )[0]- assert_close(- (general_f32 @ general_f32.T - torch.eye(3, device=device, dtype=torch.float32)).abs().max(),- torch.tensor(2.5033950805664062e-06, device=device, dtype=torch.float32),- atol=1e-6,- rtol=0.0,- msg=_issue_msg("kornia#3947: the float32 general-branch orthogonality error changed"),- )-+ # -> [[0.9999995, -0.001, 0.0], [0.001, 0.9999995, 0.0], [0.0, 0.0, 1.0]]+ # torch.linalg.det(that).item() -> 1.00000000000025+ # g = torch.tensor([[1., 2., 3.]], dtype=torch.float64) * 0.6 / math.sqrt(14.0) # generic axis+ # Rg = axis_angle_to_rotation_matrix(g)[0]+ # torch.linalg.det(Rg).item() -> 1.0+ # Rq = quaternion_to_rotation_matrix(axis_angle_to_quaternion(g))[0]+ # (Rg - Rq).abs().max().item() -> 4.440892098500626e-16_skip_if_dtype_unavailable(device, torch.float64)identity = torch.eye(3, device=device, dtype=torch.float64)@@ -2297,27 +2264,26 @@ class TestAngleAxisToRotationMatrix(BaseTester):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]+ generic = axis_angle_to_rotation_matrix(+ torch.tensor([[1.0, 2.0, 3.0]], device=device, dtype=torch.float64) * 0.6 / 14.0**0.5+ )[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"),+ for rot in (general, taylor, generic):+ 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"+ )++ # the general branch must agree with the independent quaternion route (machine precision)+ quat_route = kornia.geometry.conversions.quaternion_to_rotation_matrix(+ kornia.geometry.conversions.axis_angle_to_quaternion(+ torch.tensor([[1.0, 2.0, 3.0]], device=device, dtype=torch.float64) * 0.6 / 14.0**0.5+ )+ )[0]+ assert (generic - quat_route).abs().max().item() < 1e-12, (+ "kornia#3947: axis_angle_to_rotation_matrix disagrees with the quaternion route")@pytest.mark.xfail(