Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

fix(geometry): accept (*, 3) in axis_angle_to_rotation_matrix (#4342)

abhijeet sharma6bf99173a564
diff --git a/CHANGELOG.md b/CHANGELOG.md
index c604c597b..d19bdb0dd 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -369,6 +369,14 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
### Bug fixes
+* `axis_angle_to_rotation_matrix` accepts the `(*, 3)` shape its own guard message promises, instead of
+ only `(N, 3)`. The body did `wxyz.unbind(dim=1)` and `.view(-1, 3, 3)`, so an unbatched `(3,)` raised
+ `IndexError: Dimension out of range` and any extra batch dimension raised `ValueError` out of the unbind,
+ three frames below kornia's own shape guard. Every sibling conversion in the module already accepted
+ `(*, 3)`, so `axis_angle_to_rotation_matrix(rotation_matrix_to_axis_angle(R))` composed for an `(N, 3, 3)`
+ rotation matrix and for nothing else, including for the shape `rotation_matrix_to_axis_angle`'s own
+ doctest returns. This is additive: `(N, 3)` output and gradients are byte-identical, and only shapes that
+ used to raise now return (closes #3955). (#4342)
* Make calibration `distort_points` and `undistort_points` tilt checks compatible with
`torch.compile(fullgraph=True)`, preserving eager behavior. (#4391)
* Canny hysteresis preserves the input dtype, avoiding a convolution dtype mismatch for half-precision images. (#4393)
diff --git a/kornia/geometry/conversions.py b/kornia/geometry/conversions.py
index a1a06d05d..0c7b05806 100644
--- a/kornia/geometry/conversions.py
+++ b/kornia/geometry/conversions.py
@@ -386,9 +386,10 @@ 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``,
+ - any number of leading batch dimensions is accepted: :math:`(3,)`
+ gives :math:`(3, 3)` and :math:`(2, 5, 3)` gives :math:`(2, 5, 3, 3)`
+ - the input is the rotation axis scaled by the angle, in **radians**:
+ ``[[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
@@ -403,15 +404,6 @@ def axis_angle_to_rotation_matrix(axis_angle: torch.Tensor) -> torch.Tensor:
to this function, returning an equal result β€” see the alias warning
below
- .. 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``,
@@ -423,10 +415,10 @@ def axis_angle_to_rotation_matrix(axis_angle: torch.Tensor) -> torch.Tensor:
`#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)`.
+ axis_angle: tensor of 3d vector of axis-angle rotations in radians with shape :math:`(*, 3)`.
Returns:
- tensor of rotation matrices of shape :math:`(N, 3, 3)`.
+ tensor of rotation matrices of shape :math:`(*, 3, 3)`.
Example:
>>> input = torch.tensor([[0., 0., 0.]])
@@ -450,8 +442,8 @@ def axis_angle_to_rotation_matrix(axis_angle: torch.Tensor) -> 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) # (B, 3)
- wx, wy, wz = wxyz.unbind(dim=1) # (B,)
+ wxyz = axis_angle / theta.unsqueeze(-1) # (*, 3)
+ wx, wy, wz = wxyz.unbind(dim=-1) # (*,)
cos_theta = torch.cos(theta)
sin_theta = torch.sin(theta)
@@ -479,7 +471,7 @@ def axis_angle_to_rotation_matrix(axis_angle: torch.Tensor) -> torch.Tensor:
torch.stack([r10, r11, r12], dim=-1),
torch.stack([r20, r21, r22], dim=-1),
],
- dim=1,
+ dim=-2,
)
return rot
@@ -510,16 +502,16 @@ def axis_angle_to_rotation_matrix(axis_angle: torch.Tensor) -> torch.Tensor:
k_one - k_half * (rx2 + ry2),
],
dim=-1,
- ).view(-1, 3, 3)
+ ).reshape(list(axis_angle.shape[:-1]) + [3, 3])
return rot
theta2 = (axis_angle * axis_angle).sum(dim=-1)
- rot_normal = _compute_rotation_matrix(axis_angle, theta2) # (N,3,3)
- rot_taylor = _compute_rotation_matrix_taylor(axis_angle) # (N,3,3)
+ rot_normal = _compute_rotation_matrix(axis_angle, theta2) # (*,3,3)
+ rot_taylor = _compute_rotation_matrix_taylor(axis_angle) # (*,3,3)
- mask = (theta2 > 1e-6).view(-1, 1, 1) # shape (N,1,1)
+ mask = (theta2 > 1e-6)[..., None, None] # shape (*,1,1)
rotation_matrix = torch.where(mask, rot_normal, rot_taylor)
@@ -540,9 +532,8 @@ def rotation_matrix_to_axis_angle(rotation_matrix: torch.Tensor) -> torch.Tensor
- 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)
+ consumes, at every rank: the :math:`(3,)` and :math:`(2, 5, 3)`
+ results above can be fed straight back
- the round trip through
:func:`~kornia.geometry.conversions.axis_angle_to_rotation_matrix`
is accurate to about ``5e-09`` in ``float64`` β€” measured
diff --git a/tests/geometry/test_conversions.py b/tests/geometry/test_conversions.py
index c3d5340de..eda843bdd 100644
--- a/tests/geometry/test_conversions.py
+++ b/tests/geometry/test_conversions.py
@@ -81,20 +81,6 @@ 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
@@ -2293,94 +2279,85 @@ class TestAngleAxisToRotationMatrix(BaseTester):
"kornia#3947: axis_angle_to_rotation_matrix disagrees with the quaternion route"
)
- @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):
- # 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.
- # float32 is hardcoded and the dtype fixture dropped: all three rank errors come out of the
- # same shape-driven `wxyz.unbind(dim=1)` inside _compute_rotation_matrix, which no dtype can
- # change. NOT "before any arithmetic runs" -- theta2 = (aa * aa).sum(-1), the sqrt and the
- # axis division all execute first and succeed at every float dtype; it is that the
- # arithmetic ahead of the unbind is dtype-safe, so which ranks are accepted still cannot
- # depend on the dtype and the fixture only multiplied the cell count.
+ # Convention: axis_angle_to_rotation_matrix accepts (*, 3) and returns (*, 3, 3) -- what its
+ # own shape guard promises 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).
+ # Until kornia#3955 was fixed the body did wxyz.unbind(dim=1) and .view(-1, 3, 3), so an
+ # unbatched (3,) raised IndexError and any extra batch dimension raised ValueError out of
+ # the unbind; the asymmetry broke composition, since aa2R(R2aa(R)) worked for an (N, 3, 3)
+ # input and for nothing else. The last two assertions are that composition.
+ # A shape assertion alone would not catch a fix that flattens the leading dimensions and
+ # reshapes at the end but unbinds the wrong axis, so each rank is also compared against the
+ # same data run through the rank-2 path, which is the shape that always worked.
+ # float32 is hardcoded and the dtype fixture dropped: the ranks a shape-driven unbind
+ # accepts cannot depend on the dtype, so the fixture only multiplied the cell count.
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=torch.float32)
- rot = axis_angle_to_rotation_matrix(unbatched.reshape(1, 3))[0]
+ flat = axis_angle_to_rotation_matrix(unbatched.reshape(1, 3))
+ rot = flat[0]
+
+ assert axis_angle_to_rotation_matrix(unbatched).shape == (3, 3)
+ assert torch.equal(axis_angle_to_rotation_matrix(unbatched), rot)
+
+ stacked = unbatched.expand(2, 5, 3)
+ assert axis_angle_to_rotation_matrix(stacked).shape == (2, 5, 3, 3)
+ assert torch.equal(
+ axis_angle_to_rotation_matrix(stacked),
+ axis_angle_to_rotation_matrix(stacked.reshape(-1, 3)).reshape(2, 5, 3, 3),
+ )
+
+ # aa2R(R2aa(R)) now composes at every rank
+ assert axis_angle_to_rotation_matrix(rotation_matrix_to_axis_angle(rot)).shape == (3, 3)
+ assert axis_angle_to_rotation_matrix(rotation_matrix_to_axis_angle(rot.expand(2, 5, 3, 3))).shape == (
+ 2,
+ 5,
+ 3,
+ 3,
+ )
+
+ def test_convention_low_angle_taylor_branch_is_rank_agnostic_3955(self, device, dtype):
+ # The two branches of axis_angle_to_rotation_matrix are selected by a mask built from
+ # theta2, and the Taylor branch reshapes separately from the general one, so a rank fix has
+ # to hold on both sides of the theta2 > 1e-6 boundary and on a batch that straddles it.
+ # The dtype fixture is taken rather than hardcoding float64, which MPS cannot represent.
+ # 1e-9 keeps theta2 (~3e-18) under the 1e-6 boundary in every supported dtype, so the
+ # Taylor branch is the one exercised at each of them.
+ aa2R = kornia.geometry.conversions.axis_angle_to_rotation_matrix
+
+ for value in (1e-9, 1.0): # Taylor branch, then the general branch
+ nested = torch.full((2, 5, 3), value, device=device, dtype=dtype)
+ assert torch.equal(aa2R(nested), aa2R(nested.reshape(-1, 3)).reshape(2, 5, 3, 3))
+
+ straddling = torch.cat(
+ [
+ torch.full((5, 3), 1e-9, device=device, dtype=dtype),
+ torch.full((5, 3), 1.0, device=device, dtype=dtype),
+ ]
+ ).reshape(2, 5, 3)
+ assert torch.equal(aa2R(straddling), aa2R(straddling.reshape(-1, 3)).reshape(2, 5, 3, 3))
- 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"
+ def test_dynamo(self, device, dtype, torch_optimizer):
+ # Compile coverage for the rank path specifically: the body now reshapes the Taylor branch
+ # with reshape(list(axis_angle.shape[:-1]) + [3, 3]) and broadcasts the branch mask with
+ # [..., None, None], both of which read the input's own rank. The input straddles the
+ # theta2 > 1e-6 boundary so both branches are traced.
+ axis_angle = torch.cat(
+ [
+ torch.full((5, 3), 1e-9, device=device, dtype=dtype),
+ torch.full((5, 3), 1.0, device=device, dtype=dtype),
+ ]
+ ).reshape(2, 5, 3)
+ op = kornia.geometry.conversions.axis_angle_to_rotation_matrix
+ op_optimized = torch_optimizer(op)
- @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, 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: all three raise at the SAME line -- wxyz.unbind(dim=1) in
- # _compute_rotation_matrix -- but with different error kinds, because
- # the rank differs: the unbatched (3,) case has no dim=1 to unbind and gets an IndexError,
- # while the two over-batched cases unbind successfully and fail on the 3-way assignment
- # with a ValueError. 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.
- # float32 is hardcoded and the dtype fixture dropped for the same reason as the xfail above:
- # every one of these errors comes from the same shape-driven unbind, and the arithmetic that
- # precedes it succeeds at every float dtype, so the dtype cannot change which ranks raise.
- # 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=torch.float32)
- )
+ actual = op_optimized(axis_angle)
+ expected = op(axis_angle)
+
+ self.assert_close(actual, expected)
class TestRotationMatrixToAngleAxis(BaseTester):
@@ -6397,13 +6374,10 @@ def test_convention_deprecated_alias_warning_can_be_escalated_to_an_error_3956(a
# _emit_deprecation_warning installed simplefilter("always", DeprecationWarning) immediately
# before warnings.warn, which overrode the caller's "error" entry, so the warning was printed
# and execution continued.
- # 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 and pass the body under a name
- # that reads as "escalation works". 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.)
+ # The escalated DeprecationWarning is caught by type rather than by treating any exception as
+ # the awaited raise: an unrelated TypeError from the alias would otherwise set escalated=True
+ # and pass the body under a name that reads as "escalation works". Catching DeprecationWarning
+ # specifically lets any other exception propagate and be reported as an error instead.
# Four cells, one per alias, because all four are separate @deprecated call sites: the fix is
# in _emit_deprecation_warning, but a future decorator that emits its own warning would have to
# honor this too.