Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

fix(liegroup): finite gradients at the identity for every exp and log (#4405)

Mohansree Vijayakumar738122f9eee9
diff --git a/CHANGELOG.md b/CHANGELOG.md
index c5df5a7d9..e8db3a354 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -404,6 +404,9 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
### Bug fixes
+* `So3.exp`, `So3.log`, `Se3.exp`, `Se3.log` and `Se2.exp` return finite gradients at the identity,
+ and `So3.log` also at a half turn, instead of `nan` on every dtype. The forward values are unchanged;
+ `torch.where` was differentiating the singular branch it does not select. (#4405)
* `ycbcr_to_rgb` now uses the exact inverse of the `rgb_to_ycbcr` coefficients, so an
`rgb -> ycbcr -> rgb` round trip is lossless to floating-point precision instead of drifting
by ~2.7e-4. The forward transform is unchanged. (#4378)
diff --git a/kornia/geometry/liegroup/se2.py b/kornia/geometry/liegroup/se2.py
index e8c4eff87..f4230eb0a 100644
--- a/kornia/geometry/liegroup/se2.py
+++ b/kornia/geometry/liegroup/se2.py
@@ -188,8 +188,12 @@ class Se2(nn.Module):
so2 = So2.exp(theta)
z = torch.tensor(0.0, device=v.device, dtype=v.dtype)
theta_nonzeros = theta != 0.0
- a = torch.where(theta_nonzeros, so2.z.imag / theta, z)
- b = torch.where(theta_nonzeros, (1.0 - so2.z.real) / theta, z)
+ # both quotients are 0/0 at theta = 0, and torch.where differentiates the branch it does
+ # not select, so 0 * nan = nan used to reach v.grad at the identity. Divide by a
+ # substituted 1.0 there; the where discards that value.
+ safe_theta = torch.where(theta_nonzeros, theta, torch.ones_like(theta))
+ a = torch.where(theta_nonzeros, so2.z.imag / safe_theta, z)
+ b = torch.where(theta_nonzeros, (1.0 - so2.z.real) / safe_theta, z)
x = v[..., 0]
y = v[..., 1]
t = torch.stack((a * x - b * y, b * x + a * y), -1)
diff --git a/kornia/geometry/liegroup/se3.py b/kornia/geometry/liegroup/se3.py
index 15a43ec6c..e2f48afe2 100644
--- a/kornia/geometry/liegroup/se3.py
+++ b/kornia/geometry/liegroup/se3.py
@@ -177,14 +177,22 @@ class Se3(nn.Module):
omega = v[..., 3:]
omega_hat = So3.hat(omega)
omega_hat_sq = omega_hat @ omega_hat
- theta = batched_dot_product(omega, omega).sqrt()
+ theta_sq = batched_dot_product(omega, omega)
+ nonzero = theta_sq > 0
+ # V is a 0/0 at omega = 0 and its sqrt has an unbounded derivative there, so although the
+ # where below already returns upsilon at the identity, autograd walked V anyway and
+ # 0 * nan = nan reached v.grad. Evaluate both on a substituted theta of 1 there; the
+ # where discards the value, only the gradient changes (kornia#4229's shape).
+ safe_theta_sq = torch.where(nonzero, theta_sq, torch.ones_like(theta_sq))
+ theta = torch.where(nonzero, safe_theta_sq.sqrt(), torch.zeros_like(theta_sq))
+ safe_theta = torch.where(nonzero, theta, torch.ones_like(theta))
R = So3.exp(omega)
V = (
torch.eye(3, device=v.device, dtype=v.dtype)
- + ((1 - torch.cos(theta)) / (theta**2))[..., None, None] * omega_hat
- + ((theta - torch.sin(theta)) / (theta**3))[..., None, None] * omega_hat_sq
+ + ((1 - torch.cos(theta)) / (safe_theta**2))[..., None, None] * omega_hat
+ + ((theta - torch.sin(theta)) / (safe_theta**3))[..., None, None] * omega_hat_sq
)
- U = torch.where(theta[..., None] != 0.0, (upsilon[..., None, :] * V).sum(-1), upsilon)
+ U = torch.where(nonzero[..., None], (upsilon[..., None, :] * V).sum(-1), upsilon)
return Se3(R, U)
def log(self) -> torch.Tensor:
@@ -198,17 +206,29 @@ class Se3(nn.Module):
"""
omega = self.r.log()
- theta = batched_dot_product(omega, omega).clamp_min(1e-12).sqrt()
+ theta_sq = batched_dot_product(omega, omega)
+ nonzero = theta_sq > 0
+ # clamp_min(1e-12) bounds the value, not the gradient: on torch < 2.14 clamp passes the
+ # incoming gradient straight through at its bound, and 1e-12 underflows to 0 in float16
+ # anyway, so sqrt's unbounded derivative at 0 reached v.grad as nan (kornia#4229). Keep
+ # the floor on the branch that is selected -- byte-identical for every theta_sq > 0 --
+ # and take the exact zero elsewhere, where V_inv is the identity and both branches of
+ # the where below agree.
+ safe_theta_sq = torch.where(nonzero, theta_sq.clamp_min(1e-12), torch.ones_like(theta_sq))
+ theta = torch.where(nonzero, safe_theta_sq.sqrt(), torch.zeros_like(theta_sq))
+ safe_theta = torch.where(nonzero, theta, torch.ones_like(theta))
t = _unwrap(self.t)
omega_hat = So3.hat(omega)
omega_hat_sq = omega_hat @ omega_hat
V_inv = (
torch.eye(3, device=omega.device, dtype=omega.dtype)
- 0.5 * omega_hat
- + ((1 - theta * torch.cos(theta / 2) / (2 * torch.sin(theta / 2))) / theta.pow(2))[..., None, None]
+ + ((1 - safe_theta * torch.cos(safe_theta / 2) / (2 * torch.sin(safe_theta / 2))) / safe_theta.pow(2))[
+ ..., None, None
+ ]
* omega_hat_sq
)
- t = torch.where(theta[..., None] != 0.0, (t[..., None, :] * V_inv).sum(-1), t)
+ t = torch.where(nonzero[..., None], (t[..., None, :] * V_inv).sum(-1), t)
return torch.cat((t, omega), -1)
@staticmethod
diff --git a/kornia/geometry/liegroup/so3.py b/kornia/geometry/liegroup/so3.py
index c528bd1f8..1d8fbfa85 100644
--- a/kornia/geometry/liegroup/so3.py
+++ b/kornia/geometry/liegroup/so3.py
@@ -129,7 +129,13 @@ class So3(nn.Module):
w = torch.cos(theta_half)
eps = torch.finfo(v.dtype).eps * 1e3
small_mask = theta <= eps
- b_large = torch.sin(theta_half) / theta
+ # theta = 0 (the identity, and the standard initialisation for pose optimisation) makes
+ # b_large a 0/0. torch.where differentiates the branch it does not select, so 0 * nan =
+ # nan used to reach every component of v.grad even though the value came from b_small.
+ # Divide by a substituted 1.0 there: the where discards that value, only the gradient
+ # changes.
+ safe_theta = torch.where(small_mask, torch.ones_like(theta), theta)
+ b_large = torch.sin(theta_half) / safe_theta
b_small = 0.5 - (theta * theta) / 48.0
b = torch.where(small_mask, b_small, b_large)
xyz = b * v
@@ -147,12 +153,25 @@ class So3(nn.Module):
[0., 0., 0.]])
"""
- theta = batched_dot_product(self.q.vec, self.q.vec).sqrt()
+ vec, real = self.q.vec, self.q.real
+ vec_sq = batched_dot_product(vec, vec)
+ nonzero = vec_sq > 0
+ # Each branch below is singular exactly where the other one is selected, and torch.where
+ # differentiates both: at the identity (vec = 0) sqrt and the division by theta diverge,
+ # and at a half turn (real = 0) the small-angle branch divides by zero. Either way
+ # 0 * inf = nan used to reach every coefficient of a gradient whose value was finite.
+ # Substitute a safe argument into each branch -- the where discards those values, so only
+ # the gradients change.
+ safe_vec_sq = torch.where(nonzero, vec_sq, torch.ones_like(vec_sq))
+ theta = torch.where(nonzero, safe_vec_sq.sqrt(), torch.zeros_like(vec_sq))
+ safe_theta = torch.where(nonzero, theta, torch.ones_like(theta))
+ safe_real = torch.where(nonzero, real, torch.zeros_like(real))
+ safe_real_recip = torch.where(nonzero, torch.ones_like(real), real)
# NOTE: this differs from https://github.com/strasdat/Sophus/blob/master/sympy/sophus/so3.py#L33
omega = torch.where(
- theta[..., None] != 0,
- 2 * self.q.real[..., None].acos() * self.q.vec / theta[..., None],
- 2 * self.q.vec / self.q.real[..., None],
+ nonzero[..., None],
+ 2 * safe_real[..., None].acos() * vec / safe_theta[..., None],
+ 2 * vec / safe_real_recip[..., None],
)
return omega
diff --git a/tests/geometry/liegroup/test_se2.py b/tests/geometry/liegroup/test_se2.py
index b031077bd..3c55f3c86 100644
--- a/tests/geometry/liegroup/test_se2.py
+++ b/tests/geometry/liegroup/test_se2.py
@@ -93,9 +93,21 @@ class TestSe2(BaseTester):
y = torch.rand(3, dtype=dtype, device=device)
Se2.trans(x, y)
- # TODO: implement me
def test_gradcheck(self, device):
- pass
+ v = torch.tensor([[1.0, 2.0, 0.4]], device=device, dtype=torch.float64)
+ self.gradcheck(lambda x: Se2.exp(x).matrix(), (v,))
+
+ def test_gradient_is_finite_at_the_identity_4404(self, device, dtype):
+ # #4404: both quotients that build the translation block are 0/0 at theta = 0, and the
+ # torch.where that discards them still differentiates them, so 0 * nan = nan reached the
+ # gradient at the identity even though the forward returned the correct zero translation.
+ if dtype == torch.bfloat16:
+ # Se2 holds its rotation as a complex So2, and torch.complex has no bfloat16 overload,
+ # so most of this class already cannot run at that dtype -- unrelated to the guard.
+ pytest.skip("torch.complex has no bfloat16 overload, so So2 cannot be built at all")
+ v = torch.zeros(1, 3, device=device, dtype=dtype, requires_grad=True)
+ Se2.exp(v).matrix().sum().backward()
+ assert bool(torch.isfinite(v.grad).all()), v.grad
# TODO: implement me
def test_jit(self, device, dtype):
diff --git a/tests/geometry/liegroup/test_se3.py b/tests/geometry/liegroup/test_se3.py
index 852d391f8..0198377ea 100644
--- a/tests/geometry/liegroup/test_se3.py
+++ b/tests/geometry/liegroup/test_se3.py
@@ -64,9 +64,22 @@ class TestSe3(BaseTester):
def test_exception(self, device, dtype):
pass
- # TODO: implement me
def test_gradcheck(self, device):
- pass
+ v = torch.tensor([[1.0, 2.0, 3.0, 0.3, -0.4, 0.5]], device=device, dtype=torch.float64)
+ self.gradcheck(lambda x: Se3.exp(x).matrix(), (v,))
+
+ def test_gradient_is_finite_at_the_identity_4404(self, device, dtype):
+ # #4404: at omega = 0 the where below returns upsilon, but autograd still walks V, whose
+ # sqrt has an unbounded derivative there and whose terms divide by theta**2 and theta**3.
+ # log has the same defect through its own theta, where clamp_min(1e-12) guards the value
+ # and not the gradient (#4229) and underflows to 0 in float16 besides.
+ v = torch.zeros(1, 6, device=device, dtype=dtype, requires_grad=True)
+ Se3.exp(v).matrix().sum().backward()
+ assert bool(torch.isfinite(v.grad).all()), v.grad
+
+ data = torch.tensor([[1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]], device=device, dtype=dtype, requires_grad=True)
+ Se3(So3(Quaternion(data[:, :4])), data[:, 4:]).log().sum().backward()
+ assert bool(torch.isfinite(data.grad).all()), data.grad
# TODO: implement me
def test_jit(self, device, dtype):
diff --git a/tests/geometry/liegroup/test_so3.py b/tests/geometry/liegroup/test_so3.py
index 3368125e0..78f7fb191 100644
--- a/tests/geometry/liegroup/test_so3.py
+++ b/tests/geometry/liegroup/test_so3.py
@@ -46,9 +46,46 @@ class TestSo3(BaseTester):
def test_exception(self, device, dtype):
pass
- # TODO: implement me
def test_gradcheck(self, device):
- pass
+ v = torch.tensor([[0.3, -0.4, 0.5]], device=device, dtype=torch.float64)
+ self.gradcheck(lambda x: So3.exp(x).matrix(), (v,))
+ q = torch.tensor([[0.8, 0.2, -0.4, 0.4]], device=device, dtype=torch.float64)
+ q = q / q.norm(dim=-1, keepdim=True)
+ self.gradcheck(lambda x: So3(Quaternion(x)).log(), (q,))
+
+ def test_gradient_is_finite_at_the_identity_4404(self, device, dtype):
+ # #4404: exp's small-angle branch is selected at theta = 0, but torch.where differentiates
+ # the branch it does not select too, and sin(theta / 2) / theta is a 0/0 there -- so
+ # 0 * nan = nan used to reach every component of the gradient at the single most common
+ # input, the identity that pose optimisation starts from. The forward was always correct.
+ v = torch.zeros(1, 3, device=device, dtype=dtype, requires_grad=True)
+ So3.exp(v).matrix().sum().backward()
+ assert bool(torch.isfinite(v.grad).all()), v.grad
+
+ # log is singular the same way at both ends: at the identity through sqrt, the division by
+ # theta and acos(+-1), and at a half turn (real = 0) through the small-angle branch's own
+ # division. Each is in the branch the other case selects.
+ identity = torch.tensor([[1.0, 0.0, 0.0, 0.0]], device=device, dtype=dtype, requires_grad=True)
+ So3(Quaternion(identity)).log().sum().backward()
+ assert bool(torch.isfinite(identity.grad).all()), identity.grad
+
+ half_turn = torch.tensor([[0.0, 1.0, 0.0, 0.0]], device=device, dtype=dtype, requires_grad=True)
+ So3(Quaternion(half_turn)).log().sum().backward()
+ assert bool(torch.isfinite(half_turn.grad).all()), half_turn.grad
+
+ def test_convention_log_identity_gradient_is_the_on_manifold_limit_4404(self, device, dtype):
+ # The value the guard leaves in place, pinned rather than merely asserted finite: at the
+ # identity log evaluates 2 * vec / real, so d(omega_x)/dq_x = 2 -- exact in every dtype,
+ # which is why this runs on the dtype fixture rather than pinning float64 (MPS cannot hold
+ # float64 at all, and this test's name does not carry the "gradcheck" that conftest skips
+ # on that device). Central differences taken through the ambient 4-space disagree (they
+ # return 0) because a perturbed (1, h, 0, 0) is not a unit quaternion and lands in the
+ # other branch, where acos(1) = 0 kills the result. Along the unit sphere --
+ # q(h) = (sqrt(1 - h^2), h, 0, 0), the only path that stays a rotation -- the difference
+ # quotient is 2.000000017 at h = 1e-4 in float64, which is this value.
+ q = torch.tensor([[1.0, 0.0, 0.0, 0.0]], device=device, dtype=dtype, requires_grad=True)
+ So3(Quaternion(q)).log()[0, 0].backward()
+ self.assert_close(q.grad, torch.tensor([[0.0, 2.0, 0.0, 0.0]], device=device, dtype=dtype))
# TODO: implement me
def test_jit(self, device, dtype):