Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

fix(geometry): correct quaternion_to_axis_angle's identity gradient for negative and non-unit quaternions (#4246)

Mohansree Vijayakumar3d0fb4dac8e6
diff --git a/CHANGELOG.md b/CHANGELOG.md
index c8142844b..be43283d1 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -698,6 +698,42 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
so identical inputs can differ at the ulp level between calls unless
`torch.use_deterministic_algorithms(True)` is set. (#4254)
+* `quaternion_to_axis_angle` returns the correct gradient at every identity-like quaternion, not only the
+ positive unit identity `(1, 0, 0, 0)` (#4237). Its zero-vector-part branch used the constant `k = 2.0`,
+ which is only the `w = 1` case of the true analytic limit `k = 2 / w` (`w` = the real component); every
+ other identity-like input got a wrong gradient. That included the negative unit identity `(-1, 0, 0, 0)`
+ -- the same physical rotation as `(1, 0, 0, 0)` under the double cover -- which got the **wrong sign**
+ (`+2` instead of `-2`), and any non-unit "identity" such as `(2, 0, 0, 0)` (a scale this function
+ explicitly permits), which got the **wrong magnitude** (`+2` instead of `+1`). This was a genuine
+ backward-correctness defect, not a missing edge case: a valid unit quaternion could produce the opposite
+ gradient direction in pose optimization depending purely on which sign of the identity it started from.
+ The prior regression test for the `#3949` NaN-gradient fix only exercised `w = 1`, the one point where
+ the wrong constant and the correct formula happen to agree, and so could not have caught this. The
+ division needed for `2 / w` is guarded at `w = 0` the same way the function's existing `sin_theta`
+ division already is. That gate is `~pos` -- the mask that actually selects the branch -- and not merely
+ `w != 0`: `2.0 / t` lowers to `t.reciprocal() * 2`, whose backward is `-grad * result**2`, and for a
+ rotation just short of a half turn `w` is small but non-zero, so `(1 / w)**2` overflows to `inf` and
+ meets the exact `0.0` that the unselected branch receives as `0 * inf` -> `nan`. In `float16` that
+ would have been every rotation within ~0.45 degrees of 180 -- ordinary inputs, not degenerate ones.
+ The `2 / w` coefficient is also detached, because on the branch that selects it the vector part is
+ zero, so `d(out)/dw` is exactly zero there and computing it through `-2 / w**2` only reintroduces the
+ same overflow.
+
+ The fully degenerate all-zero quaternion `(0, 0, 0, 0)` -- not a valid rotation -- keeps its
+ `(0, 0, 0)` forward value. Its gradient there changes, and improves: it was `(0, 2, 2, 2)` on torch
+ 2.14 but already `(nan, 2, 2, 2)` on torch <= 2.9.1, where `atan2(0, 0)`'s derivative with respect to
+ its second argument -- a `0 / 0` -- returns `nan`. `atan2` is now shielded across that whole masked
+ branch, which also clears a pre-existing `nan` for a zero vector part whose `w**2` underflows
+ (`w = 1e-30` in `float32`, `|w| < 2.4e-4` in `float16`). No gradient is analytically correct at a point
+ with no well-defined limit, so the changed value is not a regression.
+
+ The forward value is unaffected everywhere: the `atan2` shield deliberately takes its value from the
+ unshielded expression, because routing `cos_theta` through `torch.where` hands `atan2` a contiguous
+ tensor instead of a stride-4 view and can select a different kernel. Verified byte-identical against
+ the previous implementation over 2000 random inputs in `float64`, `float32`, `float16` and `bfloat16`,
+ including forced unit, negative-unit, scaled, all-zero and near-half-turn quaternions, with no
+ non-finite gradient row remaining at any of those dtypes.
+
* Non-maxima suppression with a window larger than `(7, 7)` no longer builds a `(k*k, 1, k, k)` one-hot
convolution to gather each neighbour into its own channel. On CPU in half precision that convolution
has no vectorized kernel and falls back to `_slow_conv2d_forward`, where it accounted for 99% of a
diff --git a/kornia/geometry/conversions.py b/kornia/geometry/conversions.py
index 0c7b05806..7cf88d882 100644
--- a/kornia/geometry/conversions.py
+++ b/kornia/geometry/conversions.py
@@ -948,12 +948,51 @@ def quaternion_to_axis_angle(quaternion: torch.Tensor) -> torch.Tensor:
pos: torch.Tensor = sin_squared_theta > 0.0
safe_sin_squared_theta: torch.Tensor = torch.where(pos, sin_squared_theta, torch.ones_like(sin_squared_theta))
sin_theta: torch.Tensor = torch.where(pos, torch.sqrt(safe_sin_squared_theta), torch.zeros_like(sin_squared_theta))
- two_theta: torch.Tensor = 2.0 * torch.where(
+ # `two_theta` only reaches the output through `k_pos`, which `k`'s final `where` selects on
+ # `pos` -- so every element with a zero vector part gets an exact 0.0 gradient here. That is
+ # not enough to make the backward safe: `atan2`'s backward multiplies by
+ # `1 / (sin_theta**2 + cos_theta**2)`, and where that reciprocal is `inf` the masked 0.0
+ # meets it as `0 * inf` -> `nan`, which propagates into the caller's gradient. The reciprocal
+ # is `inf` for the exact-zero quaternion (0/0, `nan` on torch <= 2.9.1 and 0 on 2.14) and
+ # also whenever `w**2` underflows -- `w = 1e-30` in float32, `|w| < 2.4e-4` in float16. So
+ # substitute a 1 into `atan2` across the whole masked branch, not just at `w == 0`; don't
+ # simplify the shield away. The substitution goes through `torch.where`, which hands `atan2`
+ # a contiguous tensor instead of the stride-4 view of the input and can therefore select a
+ # different kernel and move the forward by one ulp -- so the value comes from the unshielded
+ # expression and only the gradient flows through the shielded one.
+ safe_cos_for_atan2: torch.Tensor = torch.where(pos, cos_theta, torch.ones_like(cos_theta))
+ two_theta_shielded: torch.Tensor = 2.0 * torch.where(
+ cos_theta < 0.0, torch.atan2(-sin_theta, -safe_cos_for_atan2), torch.atan2(sin_theta, safe_cos_for_atan2)
+ )
+ two_theta_value: torch.Tensor = 2.0 * torch.where(
cos_theta < 0.0, torch.atan2(-sin_theta, -cos_theta), torch.atan2(sin_theta, cos_theta)
)
+ two_theta: torch.Tensor = two_theta_shielded + (two_theta_value.detach() - two_theta_shielded.detach())
k_pos: torch.Tensor = two_theta / torch.where(pos, sin_theta, torch.ones_like(sin_theta))
- k_neg: torch.Tensor = 2.0 * torch.ones_like(sin_theta)
+ # The zero-vector-part branch's analytic limit is 2/w (w = cos_theta), not the constant 2.0
+ # that implicitly assumed w=1 -- see #4237. That constant gave the wrong sign at the negative
+ # unit identity (-1,0,0,0), which is the same rotation as (1,0,0,0), and the wrong magnitude
+ # at any non-unit "identity" (e.g. w=2), which this function explicitly allows. The division
+ # is gated on the branch that actually selects it, `~pos`, and not merely on `w != 0`: for a
+ # rotation near a half turn `w` is small but non-zero, `(1/w)**2` overflows in the reciprocal
+ # backward, and the 0.0 that this masked branch receives would meet that `inf` as `0 * inf`.
+ # In float16 that is every rotation within ~0.45 degrees of 180. The exact-zero quaternion,
+ # which is not a valid rotation, is left at 0 with a zero gradient; it previously had 2 in
+ # each vector slot and, on torch <= 2.9.1, `nan` in w's.
+ #
+ # `safe_cos_theta` is detached because `k_neg` is only ever multiplied by a vector component
+ # that this branch has already established is zero, so `d(out)/dw = q_i * -2/w**2` is exactly
+ # zero here -- but computing it that way evaluates `-2/w**2`, which overflows to `inf` for
+ # small `w` and turns the exact zero into `0 * inf` -> `nan` (`w = 1e-30` in float32, and
+ # `|w| < 0.0055` in float16, both of which already produce a `nan` here on main). Detaching
+ # returns that exact zero without the intermediate overflow. The only term it discards is
+ # from the corner where a vector component is non-zero but its square underflows to zero, in
+ # which case the discarded value is of order `|v| / w**2` in a regime the forward has already
+ # flushed. The `2 / w` coefficient itself, which is what #4237 is about, is untouched.
+ neg_branch: torch.Tensor = ~pos & (cos_theta != 0.0)
+ safe_cos_theta: torch.Tensor = torch.where(neg_branch, cos_theta, torch.ones_like(cos_theta))
+ k_neg: torch.Tensor = torch.where(neg_branch, 2.0 / safe_cos_theta.detach(), torch.zeros_like(cos_theta))
k: torch.Tensor = torch.where(pos, k_pos, k_neg)
axis_angle: torch.Tensor = torch.zeros_like(quaternion)[..., :3]
diff --git a/tests/geometry/test_conversions.py b/tests/geometry/test_conversions.py
index eda843bdd..a64c14eed 100644
--- a/tests/geometry/test_conversions.py
+++ b/tests/geometry/test_conversions.py
@@ -877,9 +877,19 @@ class TestAngleAxisToQuaternion(BaseTester):
# Pinning the VALUES and not just finiteness is what separates "the NaN is gone" from "the NaN
# was replaced by the right number": a guard that clamped the radicand to 1e-12 the way
# axis_angle_to_rotation_matrix does would also be finite here, and wrong by a factor of the
- # clamp. One table, two cells, because the two functions have independent sqrt guards.
+ # clamp.
+ #
+ # The three quaternion_to_axis_angle rows below w=1 are #4237, not #3949: the #3949 fix's
+ # zero-vector-part branch used the constant 2.0, which is only the w=1 case of the true limit
+ # 2/w (w = cos_theta). w=1 alone could not have caught this -- it is the one point where the
+ # wrong constant and the right formula agree. (-1,0,0,0) is the same rotation as (1,0,0,0) (the
+ # double cover) and used to get the wrong SIGN; w=2 and w=-2 are non-unit "identities", which
+ # this function explicitly permits, and used to get the wrong MAGNITUDE.
_IDENTITY_GRADIENT_CASES = [
("quaternion_to_axis_angle", [1.0, 0.0, 0.0, 0.0], [0.0, 2.0, 2.0, 2.0]),
+ ("quaternion_to_axis_angle", [-1.0, 0.0, 0.0, 0.0], [0.0, -2.0, -2.0, -2.0]),
+ ("quaternion_to_axis_angle", [2.0, 0.0, 0.0, 0.0], [0.0, 1.0, 1.0, 1.0]),
+ ("quaternion_to_axis_angle", [-2.0, 0.0, 0.0, 0.0], [0.0, -1.0, -1.0, -1.0]),
("axis_angle_to_quaternion", [0.0, 0.0, 0.0], [0.5, 0.5, 0.5]),
]
@@ -936,6 +946,54 @@ class TestAngleAxisToQuaternion(BaseTester):
self.assert_close(batch.grad[0], torch.tensor(expected_grad, device=device, dtype=torch.float64))
self.assert_close(batch.grad[1], alone.grad, atol=0.0, rtol=0.0)
+ def test_convention_quaternion_to_axis_angle_zero_quaternion_gradient_is_finite_4237(self, device):
+ # #4237's fix replaced the constant k=2.0 at the zero-vector-part branch with the analytic
+ # limit 2/w (w = cos_theta), which introduces a real division that a genuinely-degenerate
+ # all-zero quaternion (0,0,0,0) -- not a valid rotation, w=0 too -- would divide by zero
+ # through. That division is guarded the same way the sin_theta one already is, and `atan2`
+ # is shielded at the same input (atan2(0, 0) has a `nan` backward on torch <= 2.9.1), so
+ # this input keeps returning the same harmless (0,0,0) value and now has a finite gradient
+ # on every supported torch version. The gradient value itself (all-zero) is not claimed to be the
+ # unique "correct" one -- the function has no limit at this point, approached along
+ # different paths -- only that it stays finite and does not regress from before this fix.
+ _skip_if_dtype_unavailable(device, torch.float64)
+ q = torch.tensor([0.0, 0.0, 0.0, 0.0], device=device, dtype=torch.float64, requires_grad=True)
+
+ out = kornia.geometry.conversions.quaternion_to_axis_angle(q)
+ self.assert_close(out, torch.zeros(3, device=device, dtype=torch.float64))
+
+ out.sum().backward()
+ assert q.grad is not None
+ assert torch.isfinite(q.grad).all(), f"kornia#4237: zero quaternion has a non-finite gradient: {q.grad}"
+
+ @pytest.mark.parametrize("grad_dtype_name", ["float16", "float32", "float64"])
+ def test_convention_quaternion_to_axis_angle_near_half_turn_gradient_is_finite_4237(self, device, grad_dtype_name):
+ # The 2/w limit introduced for #4237 is only ever selected on the zero-vector-part branch,
+ # but the division was evaluated for every element, and `2.0 / t` lowers to
+ # `t.reciprocal() * 2`, whose backward is `-grad * result**2`. For a rotation just short of
+ # a half turn `w` is small and non-zero, so `(1/w)**2` overflows to `inf`, and the exact
+ # 0.0 that the unselected branch receives from `torch.where` meets it as `0 * inf` -> nan.
+ # In float16 that is every rotation within ~0.45 degrees of 180 -- ordinary inputs, not
+ # degenerate ones -- so the division is gated on `~pos`, the mask that actually selects it.
+ # The mirror case is a zero vector part with a small `w`, where the branch *is* selected
+ # and `d(2/w)/dw` overflows against an exactly-zero vector component; `2 / w` is detached
+ # for that reason. Both directions are swept here.
+ dtype = getattr(torch, grad_dtype_name)
+ _skip_if_dtype_unavailable(device, dtype)
+ ws = [0.5, 0.05, 3e-3, 1e-4, 0.0]
+ quaternions = [[w, 1.0, 0.0, 0.0] for w in ws] + [[w, 0.0, 0.0, 0.0] for w in ws]
+ quaternions += [[-w, 1.0, 0.0, 0.0] for w in ws] + [[-w, 0.0, 0.0, 0.0] for w in ws]
+
+ q = torch.tensor(quaternions, device=device, dtype=dtype, requires_grad=True)
+ kornia.geometry.conversions.quaternion_to_axis_angle(q).sum().backward()
+
+ assert q.grad is not None
+ finite = torch.isfinite(q.grad).all(dim=-1)
+ assert finite.all(), (
+ f"kornia#4237: non-finite gradient at {[quaternions[i] for i in (~finite).nonzero().flatten().tolist()]}"
+ f" in {grad_dtype_name}: {q.grad[~finite]}"
+ )
+
class TestQuaternionToAngleAxis(BaseTester):
def test_smoke(self, device, dtype):