🐍 Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
fix(geometry): make So3.log principal and keep the small-angle terms of the So3 Jacobians and Se3.exp/log (#4941)
区梓灏0eb19691c970
diff --git a/README.md b/README.mdindex cbde48b9a..2a7ca3cb0 100644--- a/README.md+++ b/README.md@@ -102,7 +102,7 @@ covers CUDA or MPS half precision.| `kornia.geometry.calibration` | ⚠️ | ⚠️ | 13 / 12 | `solve_pnp_dlt` rejects half inputs (float32/float64 only); `undistort_points` misses its OpenCV reference values || `kornia.geometry.epipolar` | ⚠️ | ⚠️ | 58 / 56 | `find_fundamental`, `find_essential`, `decompose_essential_matrix`, `motion_from_essential*` and `KRt_from_projection` raise `NotImplementedError`: CPU `lu`, `eigh` and QR have no half kernels || `kornia.geometry.homography` | ⚠️ | ⚠️ | 11 / 16 | The DLT solvers run (SVD is cast to float32) but miss the clean-point accuracy checks |-| `kornia.geometry.liegroup` | ⚠️ | ⚠️ | 36 / 130 | `So2`/`Se2` use complex tensors: float16 hits missing `ComplexHalf` kernels, and most bfloat16 `So2`/`Se2` tests raise (119 entries); `So3`/`Se3` nearly all pass |+| `kornia.geometry.liegroup` | ⚠️ | ⚠️ | 35 / 129 | `So2`/`Se2` use complex tensors: float16 hits missing `ComplexHalf` kernels, and most bfloat16 `So2`/`Se2` tests raise (119 entries); `So3`/`Se3` nearly all pass || `kornia.geometry.solvers` | ⚠️ | ⚠️ | 1 / 1 | `solve_quartic` accuracy on random quartics || `kornia.geometry.subpix` | ⚠️ | ⚠️ | 14 / 12 | `ConvSoftArgmax3d` raises (CPU `avg_pool3d` has no half kernel); the rest are accuracy || `kornia.geometry.conversions` | ⚠️ | ⚠️ | 72 / 60 | Angle-axis, quaternion and rotation-matrix round trips lose accuracy |diff --git a/changelog.d/4941.breaking.md b/changelog.d/4941.breaking.mdnew file mode 100644index 000000000..c3fe174bf--- /dev/null+++ b/changelog.d/4941.breaking.md@@ -0,0 +1,11 @@+`So3.log`, and with it `Se3.log`, now returns the principal logarithm, the rotation vector with `|omega| <= pi`, for+every element (#4925). Before, an element stored with quaternion real part `w < 0`, which includes every `exp(v)` with+`|v| > pi` and half of `Se3.random`, returned the vector of length `2 pi - theta` about the negated axis:+`So3.from_wxyz(-q).log()` differed from `So3.from_wxyz(q).log()` for the same rotation, `|So3.exp(4 * axis).log()|` was+`4.0` and is now `2 pi - 4 = 2.2832`, and `Se3.log` of a 1e-6 rad rotation stored with `w < 0` returned a translation+part of size `6.4e6` where the right one is `3.74`.+`So3.log` is now also invariant to the scale of the stored quaternion: a non-unit `q` logs to the rotation of+`q / |q|` (`So3(Quaternion(torch.ones(1, 4))).log()` was `[0, 0, 0]` and is now `[1.2092, 1.2092, 1.2092]`, the+120-degree rotation about `(1, 1, 1) / sqrt(3)`; #4942 tracks the rest of `So3` for non-unit input), and its gradient+with respect to the raw quaternion no longer has a component along `q`. The component tangent to the unit sphere, which+is all that reaches a caller who goes through `So3.exp`, is unchanged.diff --git a/changelog.d/4941.fixed.md b/changelog.d/4941.fixed.mdnew file mode 100644index 000000000..b29a51912--- /dev/null+++ b/changelog.d/4941.fixed.md@@ -0,0 +1,7 @@+`So3.log`, `So3.right_jacobian`, `So3.left_jacobian`, `Se3.exp` and `Se3.log` now keep their digits for small+rotations (#4897). `So3.log` measures the angle with `atan2` instead of `2 * acos(w)`, which in float32 returned exactly+`[0, 0, 0]` for every rotation below 1e-4 rad and was 2% short at 1e-3 rad. The Jacobians and the `Se3` `V` and `V^-1`+matrices evaluate `(1 - cos theta) / theta**2`, `(theta - sin theta) / theta**3` and `(1 - (theta / 2) cot(theta / 2)) /+theta**2` from their series below 0.5 rad (0.2 rad in float64), so they are the identity instead of `nan` at+`theta = 0` and `Se3.exp(v).log()` returns `v` for rotations below 1e-4 rad in float32 (1e-8 rad in float64) instead of+dropping the rotation-coupled part of the translation.diff --git a/kornia/geometry/liegroup/se3.py b/kornia/geometry/liegroup/se3.pyindex 4b481c7e1..0b4890682 100644--- a/kornia/geometry/liegroup/se3.py+++ b/kornia/geometry/liegroup/se3.py@@ -28,7 +28,7 @@ from torch import nnfrom kornia.core.check import KORNIA_CHECK, KORNIA_CHECK_SAME_DEVICES, KORNIA_CHECK_SHAPEfrom kornia.core.tensor_wrapper import _unwrapfrom kornia.core.utils import register_module_state-from kornia.geometry.liegroup.so3 import So3+from kornia.geometry.liegroup.so3 import So3, _so3_small_angle_coefficientsfrom kornia.geometry.linalg import batched_dot_productfrom kornia.geometry.quaternion import Quaternionfrom kornia.geometry.vector import Vector3@@ -186,10 +186,11 @@ class Se3(nn.Module):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)+ a, b, _ = _so3_small_angle_coefficients(safe_theta)V = (torch.eye(3, device=v.device, dtype=v.dtype)- + ((1 - torch.cos(theta)) / (safe_theta**2))[..., None, None] * omega_hat- + ((theta - torch.sin(theta)) / (safe_theta**3))[..., None, None] * omega_hat_sq+ + a[..., None, None] * omega_hat+ + b[..., None, None] * omega_hat_sq)U = torch.where(nonzero[..., None], (upsilon[..., None, :] * V).sum(-1), upsilon)return Se3(R, U)@@ -219,13 +220,9 @@ class Se3(nn.Module):t = _unwrap(self.t)omega_hat = So3.hat(omega)omega_hat_sq = omega_hat @ omega_hat+ _, _, c = _so3_small_angle_coefficients(safe_theta)V_inv = (- torch.eye(3, device=omega.device, dtype=omega.dtype)- - 0.5 * omega_hat- + ((1 - safe_theta * torch.cos(safe_theta / 2) / (2 * torch.sin(safe_theta / 2))) / safe_theta.pow(2))[- ..., None, None- ]- * omega_hat_sq+ torch.eye(3, device=omega.device, dtype=omega.dtype) - 0.5 * omega_hat + c[..., None, None] * omega_hat_sq)t = torch.where(nonzero[..., None], (t[..., None, :] * V_inv).sum(-1), t)return torch.cat((t, omega), -1)diff --git a/kornia/geometry/liegroup/so3.py b/kornia/geometry/liegroup/so3.pyindex 20b92d05a..642022a64 100644--- a/kornia/geometry/liegroup/so3.py+++ b/kornia/geometry/liegroup/so3.py@@ -26,12 +26,47 @@ from torch import nnfrom kornia.core.check import KORNIA_CHECK_SHAPE, KORNIA_CHECK_TYPEfrom kornia.core.tensor_wrapper import _unwrap-from kornia.geometry.conversions import vector_to_skew_symmetric_matrix-from kornia.geometry.linalg import batched_dot_product+from kornia.geometry.conversions import quaternion_to_axis_angle, vector_to_skew_symmetric_matrixfrom kornia.geometry.quaternion import Quaternionfrom kornia.geometry.vector import Vector3+def _so3_small_angle_coefficients(theta: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]:+ r"""Evaluate the three angle coefficients of the SO(3) and SE(3) closed forms without cancellation.++ Returns :math:`(1 - \cos\theta) / \theta^2`, :math:`(\theta - \sin\theta) / \theta^3` and+ :math:`(1 - \tfrac{\theta}{2}\cot\tfrac{\theta}{2}) / \theta^2`, the coefficients of :math:`[\omega]_\times`+ and :math:`[\omega]_\times^2` in the SO(3) Jacobians, in the SE(3) :math:`V` matrix and in its inverse.++ Each closed form is a 0/0 at :math:`\theta = 0` and keeps only about :math:`\epsilon / \theta^2` of its+ relative accuracy near it: all three evaluate to exactly 0 in float32 for :math:`\theta \le 10^{-4}` and in+ float64 for :math:`\theta \le 10^{-8}`. Below ``theta_small`` the Taylor series through :math:`\theta^{10}`+ is used instead. At the switch point the series is accurate to a fraction of an ulp and the closed forms to a+ few hundred ulps, so the two branches agree there.++ Args:+ theta: rotation angles of any shape, non-negative.++ Returns:+ the three coefficients, each with the shape of ``theta``.+ """+ theta_small = 0.2 if theta.dtype == torch.float64 else 0.5+ small = theta < theta_small+ safe_theta = torch.where(small, torch.ones_like(theta), theta)+ t2 = theta * theta+ a_series = 0.5 + t2 * (-1 / 24 + t2 * (1 / 720 + t2 * (-1 / 40320 + t2 * (1 / 3628800 - t2 / 479001600))))+ b_series = 1 / 6 + t2 * (-1 / 120 + t2 * (1 / 5040 + t2 * (-1 / 362880 + t2 * (1 / 39916800 - t2 / 6227020800))))+ c_series = 1 / 12 + t2 * (+ 1 / 720 + t2 * (1 / 30240 + t2 * (1 / 1209600 + t2 * (1 / 47900160 + t2 * (691 / 1307674368000))))+ )+ safe_sq = safe_theta * safe_theta+ half = 0.5 * safe_theta+ a = torch.where(small, a_series, (1 - torch.cos(safe_theta)) / safe_sq)+ b = torch.where(small, b_series, (safe_theta - torch.sin(safe_theta)) / (safe_sq * safe_theta))+ c = torch.where(small, c_series, (1 - half * torch.cos(half) / torch.sin(half)) / safe_sq)+ return a, b, c++class So3(nn.Module):r"""Base class to represent the So3 group.@@ -142,33 +177,17 @@ class So3(nn.Module):"""Convert elements of lie group to elements of lie algebra.Example:- >>> data = torch.ones((2, 4))- >>> q = Quaternion(data)- >>> So3(q).log()+ >>> So3.identity(batch_size=2).log()tensor([[0., 0., 0.],[0., 0., 0.]])"""- 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)+ # quaternion_to_axis_angle is the principal logarithm and it measures the angle with atan2: q and -q, the+ # same rotation, give the same vector with |theta| <= pi (#4925), a rotation below 1e-4 rad in float32 keeps+ # its digits instead of collapsing to 0 through 2 * acos(real) (#4897), and the identity keeps the finite+ # gradient 2 * vec / real of #4404.# NOTE: this differs from https://github.com/strasdat/Sophus/blob/master/sympy/sophus/so3.py#L33- return torch.where(- nonzero[..., None],- 2 * safe_real[..., None].acos() * vec / safe_theta[..., None],- 2 * vec / safe_real_recip[..., None],- )+ return quaternion_to_axis_angle(_unwrap(self.q.data))@staticmethoddef hat(v: Vector3 | torch.Tensor) -> torch.Tensor:@@ -412,12 +431,9 @@ class So3(nn.Module):KORNIA_CHECK_SHAPE(vec, ["*", "3"])R_skew = vector_to_skew_symmetric_matrix(vec)theta = vec.norm(dim=-1, keepdim=True)[..., None]+ a, b, _ = _so3_small_angle_coefficients(theta)I = torch.eye(3, device=vec.device, dtype=vec.dtype) # noqa: E741- return (- I- - ((1 - torch.cos(theta)) / theta**2) * R_skew- + ((theta - torch.sin(theta)) / theta**3) * (R_skew @ R_skew)- )+ return I - a * R_skew + b * (R_skew @ R_skew)@staticmethoddef Jr(vec: torch.Tensor) -> torch.Tensor:@@ -447,12 +463,9 @@ class So3(nn.Module):KORNIA_CHECK_SHAPE(vec, ["*", "3"])R_skew = vector_to_skew_symmetric_matrix(vec)theta = vec.norm(dim=-1, keepdim=True)[..., None]+ a, b, _ = _so3_small_angle_coefficients(theta)I = torch.eye(3, device=vec.device, dtype=vec.dtype) # noqa: E741- return (- I- + ((1 - torch.cos(theta)) / theta**2) * R_skew- + ((theta - torch.sin(theta)) / theta**3) * (R_skew @ R_skew)- )+ return I + a * R_skew + b * (R_skew @ R_skew)@staticmethoddef Jl(vec: torch.Tensor) -> torch.Tensor:diff --git a/testing/half_precision_xfails/cpu_bfloat16.txt b/testing/half_precision_xfails/cpu_bfloat16.txtindex 0c8d09021..a0c58aa82 100644--- a/testing/half_precision_xfails/cpu_bfloat16.txt+++ b/testing/half_precision_xfails/cpu_bfloat16.txt@@ -234,7 +234,6 @@ call builtins.RuntimeError tests/geometry/liegroup/test_se2.py::TestSe2::test_trcall builtins.RuntimeError tests/geometry/liegroup/test_se2.py::TestSe2::test_trans_y[cpu-bfloat16-2]call builtins.RuntimeError tests/geometry/liegroup/test_se2.py::TestSe2::test_trans_y[cpu-bfloat16-5]call builtins.RuntimeError tests/geometry/liegroup/test_se2.py::TestSe2::test_trans_y[cpu-bfloat16-None]-call builtins.AssertionError tests/geometry/liegroup/test_se3.py::TestSe3::test_exp_log[cpu-bfloat16-5]call builtins.AssertionError tests/geometry/liegroup/test_se3.py::TestSe3::test_mul[cpu-bfloat16-2]call builtins.AssertionError tests/geometry/liegroup/test_se3.py::TestSe3::test_mul[cpu-bfloat16-None]call builtins.AssertionError tests/geometry/liegroup/test_se3.py::TestSe3::test_mul_point[cpu-bfloat16-1]diff --git a/testing/half_precision_xfails/cpu_float16.txt b/testing/half_precision_xfails/cpu_float16.txtindex 37857dc28..90448071d 100644--- a/testing/half_precision_xfails/cpu_float16.txt+++ b/testing/half_precision_xfails/cpu_float16.txt@@ -299,7 +299,6 @@ call builtins.NotImplementedError tests/geometry/liegroup/test_se2.py::TestSe2::call builtins.NotImplementedError tests/geometry/liegroup/test_se2.py::TestSe2::test_random[cpu-float16-2]call builtins.NotImplementedError tests/geometry/liegroup/test_se2.py::TestSe2::test_random[cpu-float16-5]call builtins.NotImplementedError tests/geometry/liegroup/test_se2.py::TestSe2::test_random[cpu-float16-None]-call builtins.AssertionError tests/geometry/liegroup/test_se3.py::TestSe3::test_exp_log[cpu-float16-None]call builtins.AssertionError tests/geometry/liegroup/test_se3.py::TestSe3::test_mul[cpu-float16-1]call builtins.AssertionError tests/geometry/liegroup/test_se3.py::TestSe3::test_mul[cpu-float16-5]call builtins.AssertionError tests/geometry/liegroup/test_se3.py::TestSe3::test_mul[cpu-float16-None]diff --git a/tests/geometry/liegroup/test_se3.py b/tests/geometry/liegroup/test_se3.pyindex 0198377ea..2b96291ed 100644--- a/tests/geometry/liegroup/test_se3.py+++ b/tests/geometry/liegroup/test_se3.py@@ -186,6 +186,39 @@ class TestSe3(BaseTester):zero_vec = zero_vec.repeat(batch_size, 1)self.assert_close(s.log(), torch.cat((t, zero_vec), -1))+ def test_log_is_principal_4925(self, device, dtype):+ # Se3.log inherits So3.log: a small rotation stored with real < 0 got |omega| close to 2 pi and, through+ # V_inv(omega), a translation that was six orders of magnitude off. Both signs now give the principal log.+ theta = {torch.bfloat16: 1e-1, torch.float16: 1e-2, torch.float32: 1e-4, torch.float64: 1e-6}[dtype]+ rtol = 1e-2 if dtype in (torch.float16, torch.bfloat16) else 1e-4+ axis = torch.tensor([[0.48, 0.6, 0.64]], dtype=torch.float64) # unit length+ q = Quaternion.from_axis_angle(theta * axis).data.to(device=device, dtype=dtype) # rounded once+ axis = axis.to(device=device, dtype=dtype)+ t = torch.tensor([[1.0, 2.0, 3.0]], device=device, dtype=dtype)+ xi = Se3(So3(Quaternion(-q)), t).log()+ self.assert_close(xi, Se3(So3(Quaternion(q)), t).log())+ self.assert_close(xi[..., 3:], theta * axis, rtol=rtol, atol=0.0)+ self.assert_close(xi[..., :3], t, rtol=0.0, atol=3.0 * theta)+ # every random pose logs to a principal rotation vector+ torch.manual_seed(0)+ omega = Se3.random(64, device=device, dtype=dtype).log()[..., 3:]+ assert bool((omega.norm(dim=-1) <= torch.pi * (1 + rtol)).all())++ def test_exp_log_keep_small_rotations(self, device, dtype):+ # V and V_inv are built from (1 - cos theta) / theta**2 and friends, which evaluate to exactly 0+ # for theta <= 1e-4 in float32 (1e-8 in float64) and lose most of their digits well above that,+ # so the rotation-coupled part of the translation vanished for small rotations.+ theta = {torch.bfloat16: 1e-1, torch.float16: 1e-2, torch.float32: 1e-4, torch.float64: 1e-8}[dtype]+ rtol = 1e-2 if dtype in (torch.float16, torch.bfloat16) else 1e-4+ v = torch.tensor([[1.0, 0.0, 0.0, 0.0, 0.0, theta]], device=device, dtype=dtype)+ t = Se3.exp(v).t+ # translating along x while turning by theta about z ends at ((sin theta) / theta, (1 - cos theta) / theta, 0)+ expected_y = torch.tensor(theta / 2 - theta**3 / 24, device=device, dtype=dtype)+ self.assert_close(t[0, 1], expected_y, rtol=rtol, atol=0.0)+ self.assert_close(t[0, 2], torch.zeros((), device=device, dtype=dtype))+ v = torch.tensor([[1.0, 2.0, 3.0, 0.6 * theta, 0.0, 0.8 * theta]], device=device, dtype=dtype)+ self.assert_close(Se3.exp(v).log(), v, rtol=rtol, atol=0.0)+@pytest.mark.parametrize("batch_size", (None, 1, 2, 5))def test_exp_log(self, device, dtype, batch_size):a = self._make_rand_data(device, dtype, batch_size, dims=6)diff --git a/tests/geometry/liegroup/test_so3.py b/tests/geometry/liegroup/test_so3.pyindex 78f7fb191..6e216ba9b 100644--- a/tests/geometry/liegroup/test_so3.py+++ b/tests/geometry/liegroup/test_so3.py@@ -20,6 +20,7 @@ import torchfrom kornia.geometry.conversions import euler_from_quaternionfrom kornia.geometry.liegroup import So3+from kornia.geometry.liegroup.so3 import _so3_small_angle_coefficientsfrom kornia.geometry.quaternion import Quaternionfrom kornia.geometry.vector import Vector3@@ -73,6 +74,80 @@ class TestSo3(BaseTester):So3(Quaternion(half_turn)).log().sum().backward()assert bool(torch.isfinite(half_turn.grad).all()), half_turn.grad+ def test_log_is_principal_4925(self, device, dtype):+ # q and -q are the same rotation. log used 2 * acos(real), which for real < 0 returned the vector of+ # length 2 pi - theta about the negated axis, so the same matrix had two different logs and exp(v).log()+ # was not the principal vector for |v| > pi.+ # the quaternions are built in float64 and rounded once, so that exp's own rounding stays out of the test+ rtol = 2e-2 if dtype in (torch.float16, torch.bfloat16) else 1e-4+ v = torch.tensor([[0.5, 0.1, -0.3]], dtype=torch.float64)+ q = Quaternion.from_axis_angle(v).data.to(device=device, dtype=dtype)+ v = v.to(device=device, dtype=dtype)+ self.assert_close(So3(Quaternion(-q)).log(), v, rtol=rtol, atol=1e-3 if rtol == 2e-2 else 1e-6)+ self.assert_close(So3(Quaternion(-q)).log(), So3(Quaternion(q)).log())+ axis = torch.tensor([[0.48, 0.6, 0.64]], dtype=torch.float64) # unit length+ q = Quaternion.from_axis_angle(4.0 * axis).data.to(device=device, dtype=dtype)+ expected = ((4.0 - 2.0 * torch.pi) * axis).to(device=device, dtype=dtype)+ self.assert_close(So3(Quaternion(q)).log(), expected, rtol=rtol, atol=0.0)++ def test_log_keeps_small_rotations(self, device, dtype):+ # log used 2 * acos(real) for the angle. acos loses all of its digits next to real = 1, so in+ # float32 every rotation below 1e-4 rad came back as exactly 0 and 1e-3 rad came back 2% short.+ # quaternion_to_axis_angle measures the same angle with atan2 and keeps full precision.+ theta = {torch.bfloat16: 1e-1, torch.float16: 1e-2, torch.float32: 1e-4, torch.float64: 1e-8}[dtype]+ rtol = 1e-2 if dtype in (torch.float16, torch.bfloat16) else 1e-4+ v = torch.tensor([[0.6, 0.0, 0.8]], device=device, dtype=dtype) * theta+ self.assert_close(So3.exp(v).log(), v, rtol=rtol, atol=0.0)+ # the half turn, where real = 0, keeps its value+ half_turn = So3(Quaternion(torch.tensor([[0.0, 0.0, 1.0, 0.0]], device=device, dtype=dtype)))+ self.assert_close(half_turn.log(), torch.tensor([[0.0, torch.pi, 0.0]], device=device, dtype=dtype))++ def test_jacobians_keep_small_rotations(self, device, dtype):+ # (1 - cos theta) / theta**2 and (theta - sin theta) / theta**3 are 0/0 at theta = 0 and evaluate+ # to exactly 0 instead of 1/2 and 1/6 for theta <= 1e-4 in float32 (1e-8 in float64), so the+ # Jacobians were nan at the identity and the identity matrix next to it.+ theta = {torch.bfloat16: 1e-1, torch.float16: 1e-2, torch.float32: 1e-4, torch.float64: 1e-8}[dtype]+ rtol = 1e-2 if dtype in (torch.float16, torch.bfloat16) else 1e-4+ I = torch.eye(3, device=device, dtype=dtype) # noqa: E741+ zero = torch.zeros(1, 3, device=device, dtype=dtype)+ self.assert_close(So3.right_jacobian(zero)[0], I)+ self.assert_close(So3.left_jacobian(zero)[0], I)+ v = torch.tensor([[0.0, 0.0, 1.0]], device=device, dtype=dtype) * theta+ # for a rotation about z the [0, 1] entry is (1 - cos theta) / theta = theta / 2 - theta**3 / 24+ expected = torch.tensor(theta / 2 - theta**3 / 24, device=device, dtype=dtype)+ self.assert_close(So3.right_jacobian(v)[0, 0, 1], expected, rtol=rtol, atol=0.0)+ self.assert_close(So3.left_jacobian(v)[0, 0, 1], -expected, rtol=rtol, atol=0.0)++ def test_small_angle_coefficients_across_the_switch(self, device, dtype):+ # The three coefficients on both sides of the series/closed-form switch (0.2 rad in float64, 0.5 in+ # float32), against 50-digit references. Generated with mpmath (mp.dps = 50):+ # a = (1 - cos t) / t**2, b = (t - sin t) / t**3, c = (1 - (t / 2) * cot(t / 2)) / t**2+ if dtype not in (torch.float32, torch.float64):+ pytest.skip("the closed forms above the switch keep only a few bits in half precision")+ ref = torch.tensor(+ [+ (1e-6, 0.4999999999999583, 0.16666666666665833, 0.08333333333333472),+ (1e-3, 0.4999999583333347, 0.16666665833333352, 0.08333333472222225),+ (0.05, 0.4998958420135014, 0.16664583457336965, 0.08333680576224836),+ (0.19, 0.4984976421808776, 0.16636609177714273, 0.08338351535672024),+ (0.21, 0.498165198998906, 0.16629955230541296, 0.08339464771681691),+ (0.45, 0.4916192476411016, 0.16498727998649976, 0.08361594626029004),+ (0.55, 0.48752224112560083, 0.16416391326425744, 0.08375652128283852),+ (1.0, 0.4596976941318603, 0.1585290151921035, 0.08475613914377404),+ (2.0, 0.3540367091367856, 0.1363378216467898, 0.08947684601641732),+ (3.0, 0.2211102774000495, 0.10588444414593084, 0.09929197039400237),+ ],+ device=device,+ dtype=dtype,+ )+ # measured worst case over [1e-9, pi]: 5.2e-14 (float64, c just above 0.2), 5.9e-6 (float32, c near 0.52)+ rtol = 2e-13 if dtype == torch.float64 else 2e-5+ a, b, c = _so3_small_angle_coefficients(ref[:, 0])+ self.assert_close(torch.stack((a, b, c), -1), ref[:, 1:], rtol=rtol, atol=0.0)+ # exact at the identity+ zero = _so3_small_angle_coefficients(torch.zeros(1, device=device, dtype=dtype))+ self.assert_close(torch.cat(zero), torch.tensor([1 / 2, 1 / 6, 1 / 12], device=device, dtype=dtype))+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,