π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
fix(geometry): keep the translation of Se2.exp and Se2.log at small angles (#4960)
εΊζ’η1fba8aa58afa
diff --git a/changelog.d/4960.fixed.md b/changelog.d/4960.fixed.mdnew file mode 100644index 000000000..513f6775a--- /dev/null+++ b/changelog.d/4960.fixed.md@@ -0,0 +1,11 @@+`Se2.exp` and `Se2.log` now keep the translation at and near `theta = 0` (#4924). Both guarded their 0/0 coefficients+with a fallback of 0 where the limit is 1, so `Se2.exp([1, 2, 0]).t` was `[0, 0]`, the log of every pure translation was+`[0, 0, 0]`, and just above `theta = 0` the closed forms cancelled: `Se2.exp(v).log()` was off by 2.0 at `theta = 1e-4`+in float32 (2e-2 in float16, 1e-8 in float64). `Se2.log` now evaluates `(theta / 2) cot(theta / 2)` through the+cancellation-free `So3` coefficients, and `Se2.exp` evaluates `sin(theta) / theta` and `(1 - cos(theta)) / theta` through+them below 0.5 rad and as `sin(theta) / theta` and `2 sin(theta / 2)^2 / theta` above it, which also keeps `exp(v).t`+to a few ulps where it is nearly zero (`theta` near a nonzero multiple of `2 pi`). The gradients at the identity are the+true ones instead of 0 and `nan`. For a `v` that does not require grad, `Se2.exp(v).t` is now an `nn.Parameter` like+`Se3.exp(v).t`, instead of a tensor whose autograd graph led to the hidden `So2` parameter. The `So3` coefficient+series are now evaluated on 0 above their switch, so the float16 gradients of `Se3.exp`, `So3.left_jacobian` and+`So3.right_jacobian` are finite from 50 to 255 rad instead of `nan` (#4965).diff --git a/kornia/geometry/liegroup/se2.py b/kornia/geometry/liegroup/se2.pyindex 5b6ad63d6..1e74d7ecb 100644--- a/kornia/geometry/liegroup/se2.py+++ b/kornia/geometry/liegroup/se2.py@@ -29,6 +29,7 @@ from kornia.core.check import KORNIA_CHECK, KORNIA_CHECK_SAME_DEVICES, KORNIA_CHfrom kornia.core.tensor_wrapper import _unwrapfrom kornia.core.utils import register_module_statefrom kornia.geometry.liegroup.so2 import So2+from kornia.geometry.liegroup.so3 import _so3_small_angle_coefficientsfrom kornia.geometry.vector import Vector2@@ -175,7 +176,8 @@ class Se2(nn.Module):Parameter containing:tensor([0.5403+0.8415j], requires_grad=True)>>> s.t- tensor([[0.3818, 1.3012]], grad_fn=<StackBackward0>)+ Parameter containing:+ tensor([[0.3818, 1.3012]], requires_grad=True)"""# check_v_shape@@ -185,14 +187,20 @@ class Se2(nn.Module):raise ValueError(f"Invalid input shape, we expect [B, 3], [3] Got: {v.shape}")theta = v[..., 2]so2 = So2.exp(theta)- z = torch.tensor(0.0, device=v.device, dtype=v.dtype)- theta_nonzeros = theta != 0.0- # 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)+ # V = [[a, -b], [b, a]] with a = sin(theta) / theta and b = (1 - cos(theta)) / theta. Both are+ # 0/0 at theta = 0, 1 - cos(theta) cancels just above it, and so does the autograd derivative of+ # sin(theta) / theta, so below 0.5 rad write them through the cancellation-free So3 coefficients:+ # a = 1 - theta^2 (theta - sin(theta)) / theta^3 and+ # b = theta (1 - cos(theta)) / theta^2 (kornia#4924), evaluated at |theta| because both are even.+ # Above it take sin(theta) / theta and 2 sin(theta / 2)^2 / theta directly: 1 - theta^2 (...)+ # cancels where sin(theta) / theta is small, and theta^3 overflows float16 above 40.3 rad. Each+ # branch sees a substituted angle where it is not selected, since torch.where differentiates both.+ small = theta.abs() < 0.5+ theta_s = torch.where(small, theta, torch.zeros_like(theta))+ theta_l = torch.where(small, torch.ones_like(theta), theta)+ coef_a, coef_b, _ = _so3_small_angle_coefficients(theta_s.abs())+ a = torch.where(small, 1.0 - theta_s * theta_s * coef_b, torch.sin(theta_l) / theta_l)+ b = torch.where(small, theta_s * coef_a, 2.0 * torch.sin(0.5 * theta_l) ** 2 / theta_l)x = v[..., 0]y = v[..., 1]t = torch.stack((a * x - b * y, b * x + a * y), -1)@@ -214,12 +222,11 @@ class Se2(nn.Module):"""theta = self.so2.log()half_theta = 0.5 * theta- denom = self.so2.z.real - 1- a = torch.where(- denom != 0,- -(half_theta * self.so2.z.imag) / denom,- torch.tensor(0.0, device=theta.device, dtype=theta.dtype),- )+ # V^-1 = [[a, theta / 2], [-theta / 2, a]] with a = (theta / 2) cot(theta / 2), a 0/0 at+ # theta = 0 that cancels just above it: a = 1 - theta^2 (1 - (theta / 2) cot(theta / 2)) / theta^2+ # through the cancellation-free So3 coefficient (kornia#4924).+ _, _, coef_c = _so3_small_angle_coefficients(theta.abs())+ a = 1.0 - theta * theta * coef_crow0 = torch.stack((a, half_theta), -1)row1 = torch.stack((-half_theta, a), -1)V_inv = torch.stack((row0, row1), -2)diff --git a/kornia/geometry/liegroup/so3.py b/kornia/geometry/liegroup/so3.pyindex 683fa4d6e..a6985952e 100644--- a/kornia/geometry/liegroup/so3.py+++ b/kornia/geometry/liegroup/so3.py@@ -52,8 +52,12 @@ def _so3_small_angle_coefficients(theta: torch.Tensor) -> tuple[torch.Tensor, to"""theta_small = 0.2 if theta.dtype == torch.float64 else 0.5small = theta < theta_small+ # torch.where differentiates the branch it does not select, so each branch gets a substituted argument+ # where the other is used: 1 for the closed forms (0/0 at theta = 0) and 0 for the series, whose Horner+ # terms overflow float16 from about 50 rad and would put 0 * inf = nan into the gradient (kornia#4965).safe_theta = torch.where(small, torch.ones_like(theta), theta)- t2 = theta * theta+ series_theta = torch.where(small, theta, torch.zeros_like(theta))+ t2 = series_theta * series_thetaa_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 * (diff --git a/tests/geometry/liegroup/test_se2.py b/tests/geometry/liegroup/test_se2.pyindex b4de15bea..6fb83acdc 100644--- a/tests/geometry/liegroup/test_se2.py+++ b/tests/geometry/liegroup/test_se2.py@@ -15,6 +15,8 @@# limitations under the License.#+import math+import pytestimport torch@@ -97,17 +99,23 @@ class TestSe2(BaseTester):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):+ def test_gradient_at_the_identity_4404_4924(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.+ # gradient at the identity. #4924: the value that where fell back to there was 0 where the+ # limit is 1, so the (vx, vy) gradient of exp(v).t was 0 and the theta gradient of log was+ # nan. Pin the values: with t = V(theta) (vx, vy), d sum(matrix()) / dv is+ # [1, 1, (vx - vy) / 2] at theta = 0 and d sum(log(exp(v))) / dv is [1, 1, 1].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)+ v = torch.tensor([[1.0, 2.0, 0.0]], device=device, dtype=dtype, requires_grad=True)Se2.exp(v).matrix().sum().backward()- assert bool(torch.isfinite(v.grad).all()), v.grad+ self.assert_close(v.grad, torch.tensor([[1.0, 1.0, -0.5]], device=device, dtype=dtype))+ v.grad = None+ Se2.exp(v).log().sum().backward()+ self.assert_close(v.grad, torch.tensor([[1.0, 1.0, 1.0]], device=device, dtype=dtype))# TODO: implement medef test_jit(self, device, dtype):@@ -175,20 +183,17 @@ class TestSe2(BaseTester):def test_exp(self, device, dtype, batch_size):t = self._make_rand_data(device, dtype, (batch_size, 2))theta = torch.zeros(batch_size if batch_size is not None else (), device=device, dtype=dtype)- z = torch.zeros((batch_size, 2) if batch_size is not None else (2,), device=device, dtype=dtype)s = Se2.exp(torch.cat((t, theta[..., None]), -1))self.assert_close(s.r.z, So2.exp(theta).z)- self.assert_close(s.t, z)+ # V(0) is the identity, so a pure translation keeps its translation (#4924)+ self.assert_close(s.t, t)@pytest.mark.parametrize("batch_size", (None, 1, 2, 5))def test_log(self, device, dtype, batch_size):t = self._make_rand_data(device, dtype, (batch_size, 2))s = Se2(So2.identity(batch_size, device, dtype), t)- s.log()- zero_vec = torch.zeros(3, device=device, dtype=dtype)- if batch_size is not None:- zero_vec = zero_vec.repeat(batch_size, 1)- self.assert_close(s.log(), zero_vec)+ # V(0)^-1 is the identity, so the log of a pure translation is (t, 0) (#4924)+ self.assert_close(s.log(), torch.cat((t, torch.zeros_like(t[..., :1])), -1))@pytest.mark.parametrize("batch_size", (None, 1, 2, 5))def test_exp_log(self, device, dtype, batch_size):@@ -196,6 +201,86 @@ class TestSe2(BaseTester):b = Se2.exp(a).log()self.assert_close(b, a, low_tolerance=True)+ def test_exp_log_keep_small_rotations_4924(self, device, dtype):+ # #4924: exp guarded a = sin(theta) / theta and b = (1 - cos(theta)) / theta with a fallback of 0+ # at theta = 0, where their limits are 1 and 0, and log guarded (theta / 2) cot(theta / 2) the same+ # way, so a pure translation went into and out of the tangent space as [0, 0]. Just above+ # theta = 0 the closed forms cancelled: exp(v).t was off by 1e-4 and log(exp(v)) by 2.0 at+ # theta = 1e-4 in float32 (2e-2 in float16, 1e-8 in float64).+ if dtype == torch.bfloat16:+ pytest.skip("torch.complex has no bfloat16 overload, so So2 cannot be built at all")+ theta = {torch.float16: 2e-2, torch.float32: 1e-4}.get(dtype, 1e-8)+ v = torch.tensor([[1.0, 2.0, 0.0], [1.0, 2.0, theta], [1.0, 2.0, -theta]], dtype=dtype)+ # V(theta) (vx, vy) for the rounded angle, in float64 on the CPU (MPS has no float64) and+ # without cancellation: 1 - cos(theta) = 2 sin(theta / 2)^2+ th = v[..., 2].double()+ a = torch.where(th == 0, torch.ones_like(th), torch.sin(th) / th)+ b = torch.where(th == 0, torch.zeros_like(th), 2 * torch.sin(th / 2) ** 2 / th)+ x, y = v[..., 0].double(), v[..., 1].double()+ t_ref = torch.stack((a * x - b * y, b * x + a * y), -1).to(device=device, dtype=dtype)+ v = v.to(device)+ eps = torch.finfo(dtype).eps+ self.assert_close(Se2.exp(v).t, t_ref, rtol=8 * eps, atol=8 * eps)+ g = Se2(So2.exp(v[..., 2]), t_ref) # the element exp(v), rounded to dtype+ self.assert_close(g.log(), v, rtol=8 * eps, atol=8 * eps)++ def test_exp_keeps_large_angles_4924(self, device, dtype):+ # Past the small-angle branch exp takes sin(theta) / theta and 2 sin(theta / 2)^2 / theta directly.+ # 1 - theta^2 (theta - sin(theta)) / theta^3 cancels wherever sin(theta) / theta is small (37.7 is+ # within 1e-3 of 12 pi), 1 - cos(theta) cancels there too, and theta^3 overflows float16 above 40.3 rad,+ # which made that coefficient 0 and exp(v).t close to (vx, vy); the series that torch.where discards+ # overflows from 50 rad and made the gradient nan.+ if dtype == torch.bfloat16:+ pytest.skip("torch.complex has no bfloat16 overload, so So2 cannot be built at all")+ angles = (-300.0, -100.0, -41.0, 12.5, 37.7, 41.0, 100.0, 300.0)+ v = torch.tensor([[1.0, 2.0, th] for th in angles], dtype=dtype)+ # V(theta) (vx, vy) for the rounded angle, in float64 on the CPU (MPS has no float64)+ th = v[..., 2].double()+ a, b = torch.sin(th) / th, 2 * torch.sin(th / 2) ** 2 / th+ x, y = v[..., 0].double(), v[..., 1].double()+ t_ref = torch.stack((a * x - b * y, b * x + a * y), -1).to(device=device, dtype=dtype)+ v = v.to(device).requires_grad_(True)+ t = Se2.exp(v).t+ self.assert_close(t, t_ref, rtol=16 * torch.finfo(dtype).eps, atol=0.0)+ t.sum().backward()+ assert bool(torch.isfinite(v.grad).all()), v.grad++ def test_exp_gradient_below_the_switch_4924(self, device, dtype):+ # Below 0.5 rad the angle gradient comes from the series: autograd of sin(theta) / theta is+ # cos(theta) / theta - sin(theta) / theta^2, which loses about three digits at theta = 0.06.+ # Reference: the derivative series of a = sin(theta) / theta and b = (1 - cos(theta)) / theta in float64.+ if dtype == torch.bfloat16:+ pytest.skip("torch.complex has no bfloat16 overload, so So2 cannot be built at all")+ v = torch.tensor([[1.0, 2.0, 0.06], [1.0, 2.0, -0.3]], dtype=dtype)+ th = v[..., 2].double()+ da = sum((-1) ** k * 2 * k * th ** (2 * k - 1) / float(math.factorial(2 * k + 1)) for k in range(1, 12))+ db = sum((-1) ** (k + 1) * (2 * k - 1) * th ** (2 * k - 2) / float(math.factorial(2 * k)) for k in range(1, 12))+ # d sum(t) / d theta with t = (a x - b y, b x + a y)+ x, y = v[..., 0].double(), v[..., 1].double()+ ref = (da * (x + y) + db * (x - y)).to(device=device, dtype=dtype)+ v = v.to(device).requires_grad_(True)+ Se2.exp(v).t.sum().backward()+ eps = torch.finfo(dtype).eps+ self.assert_close(v.grad[..., 2], ref, rtol=8 * eps, atol=8 * eps)++ def test_exp_log_negative_angles_past_the_series_switch_4924(self, device, dtype):+ # The coefficients are even in theta, so exp and log evaluate them at |theta|. The So3 helper takes its+ # series below a positive switch point, so a signed theta would take the truncated series for every+ # negative angle; at theta = -3 that is off by about 1e-4 in log. Pin both signs past the switch.+ if dtype == torch.bfloat16:+ pytest.skip("torch.complex has no bfloat16 overload, so So2 cannot be built at all")+ v = torch.tensor([[1.0, 2.0, th] for th in (-3.0, -2.0, -1.0, 1.0, 2.0, 3.0)], dtype=dtype)+ # V(theta) (vx, vy) for the rounded angle, in float64 on the CPU (MPS has no float64)+ th = v[..., 2].double()+ a, b = torch.sin(th) / th, 2 * torch.sin(th / 2) ** 2 / th+ x, y = v[..., 0].double(), v[..., 1].double()+ t_ref = torch.stack((a * x - b * y, b * x + a * y), -1).to(device=device, dtype=dtype)+ v = v.to(device)+ eps = torch.finfo(dtype).eps+ self.assert_close(Se2.exp(v).t, t_ref, rtol=8 * eps, atol=8 * eps)+ g = Se2(So2.exp(v[..., 2]), t_ref) # the element exp(v), rounded to dtype+ self.assert_close(g.log(), v, rtol=8 * eps, atol=8 * eps)+@pytest.mark.parametrize("batch_size", (None, 1, 2, 5))def test_hat(self, device, dtype, batch_size):v = self._make_rand_data(device, dtype, (batch_size, 2))diff --git a/tests/geometry/liegroup/test_so3.py b/tests/geometry/liegroup/test_so3.pyindex 6f55d5af6..187fc12a6 100644--- a/tests/geometry/liegroup/test_so3.py+++ b/tests/geometry/liegroup/test_so3.py@@ -148,6 +148,20 @@ class TestSo3(BaseTester):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_small_angle_coefficients_gradient_past_the_series_range_4965(self, device, dtype):+ # #4965: the series were evaluated on every angle and discarded above the switch by torch.where, which+ # still differentiates them. In float16 their Horner terms overflow from about 50 rad, so 0 * inf = nan+ # reached the gradient of the coefficients and of both Jacobians although the values came from the closed+ # forms. 200 rad stays below the float16 overflow of theta**2 in the closed forms themselves.+ theta = torch.tensor([50.0, 100.0, 200.0], device=device, dtype=dtype, requires_grad=True)+ sum(c.sum() for c in _so3_small_angle_coefficients(theta)).backward()+ assert bool(torch.isfinite(theta.grad).all()), theta.grad+ axis = torch.tensor([0.48, 0.6, 0.64], device=device, dtype=dtype)+ for jacobian in (So3.right_jacobian, So3.left_jacobian):+ v = (theta.detach()[:, None] * axis).requires_grad_(True)+ jacobian(v).sum().backward()+ assert bool(torch.isfinite(v.grad).all()), (jacobian.__name__, v.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,