π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
fix(geometry): finite gradients for quaternion_exp_to_log and euler_from_quaternion at their rotation singularities (#4228)
Mohansree Vijayakumar70506c13bacb
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 8e58f2244..e7389b272 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -816,6 +816,20 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0instead of `view`, so a non-contiguous leading-dimension stride (a transpose, a slice that drops boxes, an`expand`) returns a boolean as documented instead of raising `RuntimeError`. (#4174)+* `quaternion_exp_to_log` and `euler_from_quaternion` no longer return `nan`/`inf` gradients at their+ respective rotation singularities (#4007). Both differentiate an inverse trig function (`acos`, `asin`)+ whose own derivative is unbounded at its domain boundary (`w = +-1`, `sinp = +-1`); `quaternion_exp_to_log`+ hits that boundary exactly at the identity quaternion `(1, 0, 0, 0)` -- the standard initialization for+ pose optimization -- where the unbounded derivative used to multiply the identity's exactly-zero vector+ part into `0 * inf = nan`, and `euler_from_quaternion`'s `pitch` hits it at gimbal lock. Both now guard the+ argument fed to the differentiated `acos`/`asin` call away from the boundary while taking the returned+ *value* from a detached copy of the real (possibly boundary) argument, so the forward result is unchanged+ -- verified byte-identical against the previous implementation over 500 random inputs including several+ forced onto the exact boundary -- while the gradient no longer depends on what a given torch version or+ backend's own `acos`/`asin` derivative happens to return there. `quaternion_exp_to_log`'s antipode+ `(-1, 0, 0, 0)` still returns a large but finite gradient (`~pi/eps`) from an unrelated, pre-existing+ division by its clamped (zero) norm; that is unchanged and out of scope here.+* `infer_bbox_shape` and `bbox_to_mask` now reject rank-4 `(B, N, 4, 2)` inputs with `ShapeError`. Previously,`N < 3` raised an incidental `IndexError`, while `N >= 3` silently returned `(B, 2)` extents computed from thewrong vertices. (#4218)diff --git a/kornia/geometry/conversions.py b/kornia/geometry/conversions.pyindex 7cf88d882..7edc7a626 100644--- a/kornia/geometry/conversions.py+++ b/kornia/geometry/conversions.py@@ -1135,6 +1135,18 @@ def quaternion_exp_to_log(quaternion: torch.Tensor, eps: float = 1.0e-8) -> torc``0`` and the identity came back ``[nan, nan, nan]``. Tracked in`#3966 <https://github.com/kornia/kornia/issues/3966>`_.+ .. note::+ The backward pass is finite at ``w = +-1`` (``w = 1`` is the identity quaternion, the+ standard initialisation for pose optimisation), where the forward already returns a+ correct value: ``acos``'s own derivative is unbounded there -- ``-inf`` on every+ supported torch version -- and is now guarded before it is differentiated. This used to+ return ``nan`` for the gradient at the identity, since it multiplied that unbounded+ derivative by the identity's exactly-zero vector part. On torch 2.14 the defect is masked+ rather than absent: ``clamp``'s backward returns ``0`` at the closed boundary there+ instead of passing the gradient through, so the ``-inf`` is killed before it reaches the+ multiply. That is ``clamp``'s behaviour changing, not ``acos``'s, and this guard does not+ depend on it. Delivered in `#4228 <https://github.com/kornia/kornia/pull/4228>`_.+Args:quaternion: a tensor containing a quaternion to be converted.The tensor can be of shape :math:`(*, 4)`.@@ -1164,9 +1176,23 @@ def quaternion_exp_to_log(quaternion: torch.Tensor, eps: float = 1.0e-8) -> torcnorm_q: torch.Tensor = torch.norm(quaternion_vector, p=2, dim=-1, keepdim=True).clamp(min=eps)- quaternion_log: torch.Tensor = (- quaternion_vector * torch.acos(torch.clamp(quaternion_scalar, min=-1.0, max=1.0)) / norm_q- ).to(orig_dtype)+ # d(acos)/dw = -1/sqrt(1-w^2) is unbounded at w = +-1, and torch returns exactly -inf there+ # on every supported version -- that has not changed. At w = +-1 the vector part need not be+ # zero (a non-unit quaternion), so this is not always multiplied away -- w = 1 at the identity+ # quaternion is the common case where it is, and 0 * inf = nan there, killing every gradient+ # through this function from its most ordinary input. torch 2.14 masks that: its clamp+ # backward returns 0 at the closed boundary instead of the pass-through 1.0 of earlier+ # versions, killing the -inf before it can multiply anything. That is clamp's behaviour+ # changing, not acos's, and nothing here may depend on it. Route the boundary through .acos()+ # on a *detached* copy for the value (identical to the unguarded call: acos is continuous at+ # +-1, only its derivative diverges) and through .acos() on a substituted safe argument for+ # the gradient, so autograd never differentiates acos at +-1 at all.+ w_clamped = torch.clamp(quaternion_scalar, min=-1.0, max=1.0)+ at_boundary = w_clamped.abs() >= 1.0+ safe_w = torch.where(at_boundary, torch.zeros_like(w_clamped), w_clamped)+ acos_w = torch.where(at_boundary, w_clamped.detach().acos(), safe_w.acos())++ quaternion_log: torch.Tensor = (quaternion_vector * acos_w / norm_q).to(orig_dtype)return quaternion_log@@ -1328,6 +1354,17 @@ def euler_from_quaternion(gimbal-locked. Tracked in`#3953 <https://github.com/kornia/kornia/issues/3953>`_.+ .. note::+ ``pitch``'s gradient is finite at gimbal lock, including exactly at ``pitch = +-pi/2``.+ This is a separate concern from the two warnings above, which are about the *value*:+ ``asin``'s own derivative is unbounded at its domain boundary (``inf`` on every supported+ torch version), and used to return ``nan`` or ``inf`` there for every quaternion+ coefficient once anything downstream differentiated through ``pitch``, independent of+ whether the returned triple itself represented the input rotation. The ``clamp`` above+ bounds only the *value*; on torch < 2.14 it passes the gradient straight through, while+ 2.14 zeroes it at the boundary and masks the defect.+ Delivered in `#4228 <https://github.com/kornia/kornia/pull/4228>`_.+Args:w: quaternion :math:`q_w` coefficient.x: quaternion :math:`q_x` coefficient.@@ -1350,7 +1387,16 @@ def euler_from_quaternion(sinp = 2.0 * (w * y - z * x)sinp = sinp.clamp(min=-1.0, max=1.0)- pitch = sinp.asin()+ # d(asin)/dx = 1/sqrt(1-x^2) is unbounded at x = +-1 (gimbal lock), returning inf there on+ # every supported torch version; the clamp above bounds the value only, and passes the+ # gradient through on torch < 2.14 (2.14 zeroes it at the boundary, masking the defect).+ # Guard the gradient the same way quaternion_exp_to_log guards its own acos boundary+ # (delivered in kornia#4228) -- differentiate asin on a substituted safe argument, but take the+ # value from a detached copy at the real (possibly +-1) argument, so the returned pitch is+ # unchanged and only the gradient is finite.+ at_boundary = sinp.abs() >= 1.0+ safe_sinp = torch.where(at_boundary, torch.zeros_like(sinp), sinp)+ pitch = torch.where(at_boundary, sinp.detach().asin(), safe_sinp.asin())siny_cosp = 2.0 * (w * z + x * y)cosy_cosp = 1.0 - 2.0 * (yy + z * z)diff --git a/kornia/geometry/solvers/polynomial_solver.py b/kornia/geometry/solvers/polynomial_solver.pyindex f2160cb7b..94cabe2fb 100644--- a/kornia/geometry/solvers/polynomial_solver.py+++ b/kornia/geometry/solvers/polynomial_solver.py@@ -189,7 +189,7 @@ def solve_cubic(coeffs: torch.Tensor) -> torch.Tensor:# guarantees |ratio_D_zero| <= 1 (D = Q3 + R^2 <= 0 implies R^2 <= -Q3), but a repeated# or near-repeated real root pushes the ratio to exactly that boundary, where the# *value* is fine but the *derivative* diverges -- same shape as the acos/asin boundary- # in quaternion_exp_to_log/euler_from_quaternion (#4007, fixed in #4228). A plain+ # in quaternion_exp_to_log/euler_from_quaternion (fixed in #4228). A plain# `.clamp(-1, 1)` does not help here: it only guards the value, not the diverging# derivative of a value already inside the domain. Route the boundary through `.acos()`# on a detached copy for the value and through `.acos()` on a substituted safe argumentdiff --git a/tests/geometry/test_conversions.py b/tests/geometry/test_conversions.pyindex a64c14eed..35f49585e 100644--- a/tests/geometry/test_conversions.py+++ b/tests/geometry/test_conversions.py@@ -1937,6 +1937,49 @@ class TestQuaternionExpToLog(BaseTester):# evaluate function gradientself.gradcheck(partial(kornia.geometry.conversions.quaternion_exp_to_log, eps=eps), (quaternion,))+ def test_convention_gradient_is_finite_at_the_acos_boundary_4007(self, device, dtype):+ # #4007: d(acos)/dw = -1/sqrt(1-w^2) is unbounded at w = +-1, which the identity+ # quaternion (1,0,0,0) hits exactly; multiplied by its exactly-zero vector part, that+ # used to give 0 * inf = nan on every backward pass through the single most common+ # optimization starting point. acos returns -inf at the boundary on every supported torch+ # version; what differs is clamp's backward -- pass-through on <= 2.9.1, zero on 2.14 --+ # so it is the torch 2.5.1 leg of the CI matrix that discriminates. Run on base, this+ # fails under 2.5.1 and passes under 2.14, where clamp already zeroes the -inf before it+ # reaches the multiply.+ eps = torch.finfo(dtype).eps+ fn = partial(kornia.geometry.conversions.quaternion_exp_to_log, eps=eps)++ identity = torch.tensor((1.0, 0.0, 0.0, 0.0), device=device, dtype=dtype, requires_grad=True)+ fn(identity).sum().backward()+ assert bool(torch.isfinite(identity.grad).all()), identity.grad++ antipode = torch.tensor((-1.0, 0.0, 0.0, 0.0), device=device, dtype=dtype, requires_grad=True)+ fn(antipode).sum().backward()+ assert bool(torch.isfinite(antipode.grad).all()), antipode.grad++ # non-unit input at the same boundary, with a nonzero vector part: not a rotation, so no+ # limit argument makes its gradient meaningful, but it must still not be nan/inf.+ non_unit = torch.tensor((1.0, 0.1, 0.0, 0.0), device=device, dtype=dtype, requires_grad=True)+ fn(non_unit).sum().backward()+ assert bool(torch.isfinite(non_unit.grad).all()), non_unit.grad++ # the guard changes no forward value. At the boundary the identity's log is all zeros;+ # off it the other branch of the torch.where runs and must equal the unguarded expression+ # exactly -- that is the branch proving the guard is inert away from w = +-1, which an+ # on-boundary input cannot exercise.+ expected_identity = torch.tensor((0.0, 0.0, 0.0), device=device, dtype=dtype)+ self.assert_close(fn(identity.detach()), expected_identity)++ near_boundary = torch.tensor((1.0 - eps, 0.1, 0.0, 0.0), device=device, dtype=dtype)+ work_dtype = torch.float32 if dtype in (torch.float16, torch.bfloat16) else dtype+ work = near_boundary.to(work_dtype)+ unguarded = (+ work[1:4]+ * work[0:1].clamp(min=-1.0, max=1.0).acos()+ / work[1:4].norm(p=2, dim=-1, keepdim=True).clamp(min=eps)+ ).to(dtype)+ self.assert_close(fn(near_boundary), unguarded)+def test_dynamo(self, device, dtype, torch_optimizer):quaternion = torch.tensor((0.0, 0.0, 1.0, 0.0), device=device, dtype=dtype)op = kornia.geometry.conversions.quaternion_exp_to_log@@ -5870,6 +5913,24 @@ class TestEulerFromQuaternion(BaseTester):q = Quaternion.random(batch_size=1).to(device, torch.float64)self.gradcheck(euler_from_quaternion, (q.w, q.x, q.y, q.z))+ def test_convention_pitch_gradient_is_finite_at_gimbal_lock_4007(self, device, dtype):+ # #4007: d(asin)/dx = 1/sqrt(1-x^2) is unbounded at x = +-1, which sinp hits exactly at+ # gimbal lock (pitch = +-pi/2); the guard mirrors quaternion_exp_to_log's own acos+ # boundary fix. As there, asin's boundary derivative is inf on every supported torch+ # version and it is clamp's backward that differs, so the torch 2.5.1 leg is the one that+ # fails on base. w=1, x=0, y=0.5, z=0 gives sinp = 2*(w*y - z*x) = 1.0 exactly.+ w = torch.tensor(1.0, device=device, dtype=dtype, requires_grad=True)+ x = torch.tensor(0.0, device=device, dtype=dtype, requires_grad=True)+ y = torch.tensor(0.5, device=device, dtype=dtype, requires_grad=True)+ z = torch.tensor(0.0, device=device, dtype=dtype, requires_grad=True)++ _, pitch, _ = euler_from_quaternion(w, x, y, z)+ self.assert_close(pitch, (kornia.pi / 2.0).to(device=device, dtype=dtype))++ pitch.backward()+ for name, t in (("w", w), ("x", x), ("y", y), ("z", z)):+ assert bool(torch.isfinite(t.grad)), f"pitch grad wrt {name} is not finite: {t.grad}"+@pytest.mark.skipif(torch_version() in {"2.0.1", "2.1.2", "2.2.2", "2.3.1"} and sys.version_info.minor == 8,reason="Not working on 2.0",