Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

fix(geometry): switch So3.exp to its series below 0.5 rad instead of below eps * 1e3 (#4962)

εŒΊζ’“ηe393e4973068
diff --git a/changelog.d/4962.fixed.md b/changelog.d/4962.fixed.md
new file mode 100644
index 000000000..3157338b2
--- /dev/null
+++ b/changelog.d/4962.fixed.md
@@ -0,0 +1,7 @@
+`So3.exp`, and with it `Se3.exp`, now switches to its small-angle series below a fixed 0.5 rad instead of below
+`finfo(dtype).eps * 1e3`, which is 7.8 rad in bfloat16 and 0.98 rad in float16 (#4928). Every bfloat16 `exp` used the
+two-term series `0.5 - theta**2 / 48` for `sin(theta / 2) / theta`, so at `theta = 3` the quaternion had norm 0.94 and
+the rotation matrix was off by 0.23 in an entry; the quaternion is now within about one bfloat16 ulp (at most 5.5e-3
+for angles up to pi), and in float16 at `theta = 0.97` its error drops from 2.8e-4 to 9.1e-5. The series now runs
+through `theta**10`, so the float32 and float64 outputs move by at most 1.5e-8 and 2.8e-17 below 0.5 rad, a rounding
+difference, and do not change above it.
diff --git a/kornia/geometry/liegroup/so3.py b/kornia/geometry/liegroup/so3.py
index 642022a64..683fa4d6e 100644
--- a/kornia/geometry/liegroup/so3.py
+++ b/kornia/geometry/liegroup/so3.py
@@ -156,22 +156,20 @@ class So3(nn.Module):
"""
KORNIA_CHECK_SHAPE(v, ["*", "3"])
theta = v.norm(dim=-1, keepdim=True)
- theta_half = 0.5 * theta
- w = torch.cos(theta_half)
- eps = torch.finfo(v.dtype).eps * 1e3
- small_mask = theta <= eps
- # 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
- q = torch.cat((w, xyz), dim=-1)
- return So3(Quaternion(q))
+ w = torch.cos(0.5 * theta)
+ # sin(theta / 2) / theta is a 0/0 at theta = 0 (the identity, and the standard initialisation
+ # for pose optimisation), so below 0.5 rad its series through theta**10 is used instead; the
+ # truncation error there is under 1e-17, below the resolution of every dtype. torch.where
+ # differentiates the branch it does not select, so each branch is evaluated on an input that
+ # keeps it finite: the closed form on 1.0 below the switch, and the series on 0.0 above it
+ # (on theta itself its powers overflow float16 above about 90 rad and 0 * inf = nan).
+ small = theta < 0.5
+ safe_theta = torch.where(small, torch.ones_like(theta), theta)
+ series_theta = torch.where(small, theta, torch.zeros_like(theta))
+ t2 = series_theta * series_theta
+ b_series = 0.5 + t2 * (-1 / 48 + t2 * (1 / 3840 + t2 * (-1 / 645120 + t2 * (1 / 185794560 - t2 / 81749606400))))
+ b = torch.where(small, b_series, torch.sin(0.5 * safe_theta) / safe_theta)
+ return So3(Quaternion(torch.cat((w, b * v), dim=-1)))
def log(self) -> torch.Tensor:
"""Convert elements of lie group to elements of lie algebra.
diff --git a/tests/geometry/liegroup/test_so3.py b/tests/geometry/liegroup/test_so3.py
index 6e216ba9b..6f55d5af6 100644
--- a/tests/geometry/liegroup/test_so3.py
+++ b/tests/geometry/liegroup/test_so3.py
@@ -162,6 +162,49 @@ class TestSo3(BaseTester):
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))
+ def test_exp_matches_float64_at_large_angles_4928(self, device, dtype):
+ # #4928: exp took the Taylor branch 0.5 - theta**2 / 48 for sin(theta / 2) / theta below
+ # finfo(dtype).eps * 1e3, which is 7.8 rad in bfloat16, so every bfloat16 exp used the two
+ # terms: at theta = 3 the quaternion had norm 0.94 and the rotation matrix was off by 0.23.
+ axis = torch.tensor([[1.0, 0.0, 0.0], [0.48, 0.6, 0.64]], dtype=torch.float64)
+ for theta in (0.97, 3.0):
+ v = theta * axis
+ q_ref = So3.exp(v).q.data.to(device=device, dtype=dtype)
+ q = So3.exp(v.to(device=device, dtype=dtype)).q.data
+ self.assert_close(q, q_ref)
+ self.assert_close(q.norm(dim=-1), torch.ones(2, device=device, dtype=dtype))
+
+ def test_exp_across_the_series_switch_4928(self, device, dtype):
+ # exp about z is (cos(t / 2), 0, 0, sin(t / 2)) on both sides of the 0.5 rad switch, against
+ # 50-digit references. Generated with mpmath (mp.dps = 50): cos(t / 2), sin(t / 2).
+ if dtype not in (torch.float32, torch.float64):
+ pytest.skip("half precision keeps too few bits to see the series coefficients")
+ ref = torch.tensor(
+ [
+ (1e-3, 0.9999998750000026, 0.0004999999791666669),
+ (0.3, 0.9887710779360422, 0.14943813247359922),
+ (0.49, 0.9701373249726354, 0.24255632478857206),
+ (0.51, 0.9676632956885756, 0.25224540863437805),
+ (1.9, 0.5816830894638836, 0.8134155047893737),
+ (3.0, 0.0707372016677029, 0.9974949866040544),
+ (6.0, -0.9899924966004454, 0.1411200080598672),
+ ],
+ device=device,
+ dtype=dtype,
+ )
+ zero = torch.zeros_like(ref[:, :1])
+ q = So3.exp(torch.cat((zero, zero, ref[:, :1]), -1)).q.data
+ rtol = 1e-15 if dtype == torch.float64 else 1e-6
+ self.assert_close(q, torch.cat((ref[:, 1:2], zero, zero, ref[:, 2:]), -1), rtol=rtol, atol=0.0)
+
+ def test_exp_gradient_is_finite_at_large_angles(self, device, dtype):
+ # The series branch is differentiated even where the closed form is selected; evaluated on the
+ # raw angle its powers overflow float16 above about 90 rad and 0 * inf = nan reached v.grad.
+ axis = torch.tensor([0.48, 0.6, 0.64], device=device, dtype=dtype)
+ v = (torch.tensor([[0.0], [0.3], [3.0], [120.0]], device=device, dtype=dtype) * axis).requires_grad_(True)
+ So3.exp(v).q.data.sum().backward()
+ assert bool(torch.isfinite(v.grad).all()), v.grad
+
# TODO: implement me
def test_jit(self, device, dtype):
pass