π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
fix(geometry): evaluate So3.exp below 0.5 rad as series in theta**2 so its Hessian is finite at the identity (#4972)
εΊζ’η614561ea002d
diff --git a/changelog.d/4972.fixed.md b/changelog.d/4972.fixed.mdnew file mode 100644index 000000000..b34a0bba7--- /dev/null+++ b/changelog.d/4972.fixed.md@@ -0,0 +1,4 @@+`So3.exp` now evaluates `cos(theta / 2)` and `sin(theta / 2) / theta` below the 0.5 rad switch as series in+`theta**2 = v . v` instead of on `theta = |v|`, which has no second derivative at `v = 0`, so the Hessian of `exp` at+the identity is finite (`-I / 4` for the real part) instead of `nan` and `gradgradcheck` passes there (#4966). Above+the switch the output is bitwise unchanged in every dtype; below it the quaternion moves by at most 1 ulp.diff --git a/kornia/geometry/liegroup/so3.py b/kornia/geometry/liegroup/so3.pyindex cde47ee4f..454549b72 100644--- a/kornia/geometry/liegroup/so3.py+++ b/kornia/geometry/liegroup/so3.py@@ -180,19 +180,26 @@ class So3(nn.Module):"""KORNIA_CHECK_SHAPE(v, ["*", "3"])- theta = v.norm(dim=-1, keepdim=True)- 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+ # cos(theta / 2) and sin(theta / 2) / theta are even in theta, so below 0.5 rad both are evaluated as+ # series in theta**2 = v . v, a polynomial in v. theta = |v| itself has no second derivative at v = 0,+ # so the Hessian of exp at the identity, the standard initialisation for pose optimisation, was nan+ # (#4966), and sin(theta / 2) / theta is a 0/0 there. The series run through theta**12 and theta**10;+ # their truncation error at the switch 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 series on 0 above the switch (on theta**2 itself their powers overflow+ # float16 above about 90 rad and 0 * inf = nan), and the closed forms on the norm of the unit vector+ # e_x below it, which keeps |v| out of the graph where it is not differentiable.+ theta_sq = (v * v).sum(-1, keepdim=True)+ small = theta_sq < 0.25+ t2 = torch.where(small, theta_sq, torch.zeros_like(theta_sq))+ w_series = 1 + t2 * (+ -1 / 8+ + t2 * (1 / 384 + t2 * (-1 / 46080 + t2 * (1 / 10321920 + t2 * (-1 / 3715891200 + t2 / 1961990553600))))+ )b_series = 0.5 + t2 * (-1 / 48 + t2 * (1 / 3840 + t2 * (-1 / 645120 + t2 * (1 / 185794560 - t2 / 81749606400))))+ unit_x = torch.cat((torch.ones_like(theta_sq), torch.zeros_like(v[..., 1:])), dim=-1)+ safe_theta = torch.where(small, unit_x, v).norm(dim=-1, keepdim=True)+ w = torch.where(small, w_series, torch.cos(0.5 * safe_theta))b = torch.where(small, b_series, torch.sin(0.5 * safe_theta) / safe_theta)return So3(Quaternion(torch.cat((w, b * v), dim=-1)))diff --git a/tests/geometry/liegroup/test_so3.py b/tests/geometry/liegroup/test_so3.pyindex f8fea194b..89fb76f76 100644--- a/tests/geometry/liegroup/test_so3.py+++ b/tests/geometry/liegroup/test_so3.py@@ -243,11 +243,33 @@ class TestSo3(BaseTester):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.+ # At 1000 rad theta**2 = v . v itself overflows float16, so the closed forms must take their+ # angle from |v| and not from sqrt(theta**2).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()+ angles = torch.tensor([[0.0], [0.3], [3.0], [120.0], [1000.0]], device=device, dtype=dtype)+ v = (angles * axis).requires_grad_(True)+ q = So3.exp(v).q.data+ assert bool(torch.isfinite(q).all()), q+ q.sum().backward()assert bool(torch.isfinite(v.grad).all()), v.grad+ def test_exp_hessian_gradgradcheck_at_the_identity_4966(self, device):+ # #4966: exp evaluated cos(theta / 2) on theta = |v|, which has no second derivative at v = 0, so the+ # Hessian of exp at the identity was nan although its value and gradient there were finite. Both+ # quaternion coefficients are even in theta, so below the switch they are now series in theta**2 = v . v:+ # cos(|v| / 2) = 1 - v . v / 8 + ... has Hessian -I / 4 at v = 0, and the vector part sin(|v| / 2) / |v| * v+ # is odd in v, so its Hessian there is 0.+ zero = torch.zeros(3, device=device, dtype=torch.float64)+ hessian = torch.autograd.functional.hessian(lambda x: So3.exp(x).q.data[0], zero)+ self.assert_close(hessian, -0.25 * torch.eye(3, device=device, dtype=torch.float64))+ for i in range(1, 4):+ hessian = torch.autograd.functional.hessian(lambda x, i=i: So3.exp(x).q.data[i], zero)+ self.assert_close(hessian, torch.zeros(3, 3, device=device, dtype=torch.float64))+ axis = torch.tensor([0.48, 0.6, 0.64], device=device, dtype=torch.float64)+ for theta in (0.0, 0.3, 2.0):+ v = (theta * axis).requires_grad_(True)+ assert torch.autograd.gradgradcheck(lambda x: So3.exp(x).q.data, (v,))+# TODO: implement medef test_jit(self, device, dtype):pass