🐍 Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
fix(geometry): support complex-half So2 inverse (#5843)
peng xiang8f77191273ff
diff --git a/README.md b/README.mdindex d28946b69..4184f793c 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` | ⚠️ | ⚠️ | 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.liegroup` | ⚠️ | ⚠️ | 4 / 130 | `So2`/`Se2` store complex tensors; float16 inverses are computed in complex64. PyTorch has no complex bfloat16 dtype, so most bfloat16 `So2`/`Se2` tests raise (119 entries); `So3`/`Se3` miss a few composition, point-transform and orthogonality accuracy checks || `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/5843.fixed.md b/changelog.d/5843.fixed.mdnew file mode 100644index 000000000..e1ae07862--- /dev/null+++ b/changelog.d/5843.fixed.md@@ -0,0 +1 @@+`So2.inverse()`, and so `Se2.inverse()`, now run on CPU float16 rotations, where they raised `NotImplementedError` because the CPU has no ComplexHalf reciprocal: the reciprocal is computed in complex64 and returned in the input dtype. On MPS, float16 inverses of rotations scaled far from unit length no longer return 0 or NaN, and inverses of unit rotations are more accurate.diff --git a/docs/source/get-started/precision.rst b/docs/source/get-started/precision.rstindex 41eb73f9a..05a9050fb 100644--- a/docs/source/get-started/precision.rst+++ b/docs/source/get-started/precision.rst@@ -89,10 +89,10 @@ precision, so the table says nothing about those backends.* - ``kornia.geometry.liegroup``- ⚠️ Partial- ⚠️ Partial- - 36 / 130- - ``So2`` and ``Se2`` use complex tensors: float16 hits missing ``ComplexHalf`` kernels, and most- bfloat16 ``So2`` / ``Se2`` tests raise because the complex path does not accept bfloat16 (119 entries).- ``So3`` and ``Se3`` nearly all pass.+ - 4 / 130+ - ``So2`` and ``Se2`` store complex tensors; float16 inverses are computed in complex64. PyTorch has no+ complex bfloat16 dtype, so most bfloat16 ``So2`` / ``Se2`` tests raise (119 entries). ``So3`` and ``Se3``+ miss a few composition, point-transform and orthogonality accuracy checks.* - ``kornia.geometry.solvers``- ⚠️ Partial- ⚠️ Partialdiff --git a/kornia/geometry/liegroup/so2.py b/kornia/geometry/liegroup/so2.pyindex 36fa292cb..de5347e28 100644--- a/kornia/geometry/liegroup/so2.py+++ b/kornia/geometry/liegroup/so2.py@@ -338,13 +338,19 @@ class So2(nn.Module):def inverse(self) -> So2:"""Return the inverse transformation.+ Complex-half state is inverted in complex64 and returned in its original dtype.+Example:>>> s = So2.identity()>>> s.inverse().ztensor(1.+0.j, grad_fn=<MulBackward0>)"""- return So2(1 / self.z)+ z = self.z+ # CPU reciprocal has no ComplexHalf kernel. Promotion also preserves the inverse of non-unit z.+ if z.dtype == torch.complex32:+ return So2((1 / z.to(torch.complex64)).to(z.dtype))+ return So2(1 / z)@classmethoddef random(diff --git a/testing/half_precision_xfails/cpu_float16.txt b/testing/half_precision_xfails/cpu_float16.txtindex b4376ec03..984c969fe 100644--- a/testing/half_precision_xfails/cpu_float16.txt+++ b/testing/half_precision_xfails/cpu_float16.txt@@ -142,37 +142,9 @@ call builtins.NotImplementedError tests/geometry/epipolar/test_projection.py::Tecall builtins.NotImplementedError tests/geometry/epipolar/test_projection.py::TestKRtFromProjection::test_simple[cpu-float16]call builtins.NotImplementedError tests/geometry/epipolar/test_projection.py::TestKRtFromProjection::test_smoke[cpu-float16]call builtins.NotImplementedError tests/geometry/epipolar/test_projection.py::TestProjectionFromKRt::test_krt_from_projection[cpu-float16]-call builtins.NotImplementedError tests/geometry/liegroup/test_se2.py::TestSe2::test_cardinality[cpu-float16-input_shape0]-call builtins.NotImplementedError tests/geometry/liegroup/test_se2.py::TestSe2::test_cardinality[cpu-float16-input_shape1]-call builtins.NotImplementedError tests/geometry/liegroup/test_se2.py::TestSe2::test_cardinality[cpu-float16-input_shape2]-call builtins.NotImplementedError tests/geometry/liegroup/test_se2.py::TestSe2::test_cardinality[cpu-float16-input_shape3]-call builtins.NotImplementedError tests/geometry/liegroup/test_se2.py::TestSe2::test_inverse[cpu-float16-1]-call builtins.NotImplementedError tests/geometry/liegroup/test_se2.py::TestSe2::test_inverse[cpu-float16-2]-call builtins.NotImplementedError tests/geometry/liegroup/test_se2.py::TestSe2::test_inverse[cpu-float16-5]-call builtins.NotImplementedError tests/geometry/liegroup/test_se2.py::TestSe2::test_inverse[cpu-float16-None]-call builtins.NotImplementedError tests/geometry/liegroup/test_se2.py::TestSe2::test_mul[cpu-float16-1]-call builtins.NotImplementedError tests/geometry/liegroup/test_se2.py::TestSe2::test_mul[cpu-float16-2]-call builtins.NotImplementedError tests/geometry/liegroup/test_se2.py::TestSe2::test_mul[cpu-float16-5]-call builtins.NotImplementedError tests/geometry/liegroup/test_se2.py::TestSe2::test_mul[cpu-float16-None]-call builtins.NotImplementedError tests/geometry/liegroup/test_se2.py::TestSe2::test_mul_vector[cpu-float16-1]-call builtins.NotImplementedError tests/geometry/liegroup/test_se2.py::TestSe2::test_mul_vector[cpu-float16-2]-call builtins.NotImplementedError tests/geometry/liegroup/test_se2.py::TestSe2::test_mul_vector[cpu-float16-5]-call builtins.NotImplementedError tests/geometry/liegroup/test_se2.py::TestSe2::test_mul_vector[cpu-float16-None]-call builtins.NotImplementedError tests/geometry/liegroup/test_se2.py::TestSe2::test_random[cpu-float16-1]-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_mul[cpu-float16-5]call builtins.AssertionError tests/geometry/liegroup/test_se3.py::TestSe3::test_mul_point[cpu-float16-5]call builtins.AssertionError tests/geometry/liegroup/test_se3.py::TestSe3::test_mul_vector[cpu-float16-5]-call builtins.NotImplementedError tests/geometry/liegroup/test_so2.py::TestSo2::test_mul[cpu-float16-1]-call builtins.NotImplementedError tests/geometry/liegroup/test_so2.py::TestSo2::test_mul[cpu-float16-2]-call builtins.NotImplementedError tests/geometry/liegroup/test_so2.py::TestSo2::test_mul[cpu-float16-5]-call builtins.NotImplementedError tests/geometry/liegroup/test_so2.py::TestSo2::test_mul[cpu-float16-None]-call builtins.NotImplementedError tests/geometry/liegroup/test_so2.py::TestSo2::test_random[cpu-float16-1]-call builtins.NotImplementedError tests/geometry/liegroup/test_so2.py::TestSo2::test_random[cpu-float16-2]-call builtins.NotImplementedError tests/geometry/liegroup/test_so2.py::TestSo2::test_random[cpu-float16-5]-call builtins.NotImplementedError tests/geometry/liegroup/test_so2.py::TestSo2::test_random[cpu-float16-None]call builtins.AssertionError tests/geometry/liegroup/test_so3.py::TestSo3::test_ortho[cpu-float16-2]call builtins.AssertionError tests/geometry/subpix/test_spatial_softargmax.py::TestConvQuadInterp3dModule::test_diag[cpu-float16]call builtins.AssertionError tests/geometry/subpix/test_spatial_softargmax.py::TestSpatialSoftArgmax2d::test_batch2_n2[cpu-float16]diff --git a/tests/geometry/liegroup/test_se2.py b/tests/geometry/liegroup/test_se2.pyindex 003251dcd..0b50c13dc 100644--- a/tests/geometry/liegroup/test_se2.py+++ b/tests/geometry/liegroup/test_se2.py@@ -663,9 +663,8 @@ class TestSe2(BaseTester):Se2.random(1, device, dtype),Se2(So2.identity(1, device, dtype), Vector2(p)),from_exp * identity,+ identity.inverse(),]- if dtype != torch.float16: # So2.inverse divides a ComplexHalf z, which the CPU does not implement- poses.append(identity.inverse())for pose in poses:assert isinstance(pose.t, torch.Tensor)assert pose.t.shape == (1, 2)diff --git a/tests/geometry/liegroup/test_so2.py b/tests/geometry/liegroup/test_so2.pyindex da5af1751..bbbb89792 100644--- a/tests/geometry/liegroup/test_so2.py+++ b/tests/geometry/liegroup/test_so2.py@@ -434,6 +434,57 @@ class _So2PointTransform(torch.nn.Module):return (self.rotation.matrix() @ point[..., None]).squeeze(-1)+class TestSo2Inverse(BaseTester):+ @pytest.mark.parametrize("shape", [(), (1,), (4, 1)])+ @pytest.mark.parametrize("parts", [(0.6, 0.8), (2.0, -3.0), (512.0, 256.0), (2**-14, -(2**-15))])+ def test_matches_complex_reference_4153(self, device, dtype, shape, parts):+ if dtype == torch.bfloat16:+ pytest.skip("torch has no complex bfloat16 dtype, which So2 stores its rotation in")+ # Non-unit inputs are accepted by So2. Large/small inputs also catch a squared norm computed in float16.+ real = torch.full(shape, parts[0], device=device, dtype=dtype)+ imag = torch.full(shape, parts[1], device=device, dtype=dtype)+ z = torch.complex(real, imag)+ result = So2(z).inverse().z+ expected = (1 / z.detach().cpu().to(torch.complex128)).to(device=device, dtype=z.dtype)+ assert result.dtype == z.dtype+ assert result.device == z.device+ assert result.shape == So2(z).z.shape+ assert torch.isfinite(result.real).all()+ assert torch.isfinite(result.imag).all()+ self.assert_close(result.real, expected.real.reshape(result.shape))+ self.assert_close(result.imag, expected.imag.reshape(result.shape))++ @pytest.mark.parametrize("as_parameter", [False, True])+ def test_backward_matches_complex_reference_4153(self, device, dtype, as_parameter):+ if dtype == torch.bfloat16:+ pytest.skip("torch has no complex bfloat16 dtype, which So2 stores its rotation in")+ parts = torch.tensor([[0.6, 0.8], [0.25, -0.5], [2.0, -3.0]], device=device, dtype=dtype)+ z = torch.complex(parts[:, 0], parts[:, 1]).requires_grad_()+ if as_parameter:+ z = torch.nn.Parameter(z)+ result = So2(z).inverse().z+ grad = torch.autograd.grad((result.real + 2 * result.imag).sum(), z)[0]+ ref = z.detach().cpu().to(torch.complex128).requires_grad_()+ inverse = 1 / ref+ expected = torch.autograd.grad((inverse.real + 2 * inverse.imag).sum(), ref)[0].to(device=device, dtype=z.dtype)+ assert grad.dtype == z.dtype+ assert torch.isfinite(grad.real).all()+ assert torch.isfinite(grad.imag).all()+ self.assert_close(grad.real, expected.real)+ self.assert_close(grad.imag, expected.imag)++ @pytest.mark.skipif(not dynamo_is_available(), reason=DYNAMO_UNAVAILABLE_REASON)+ def test_dynamo(self, device, dtype, torch_optimizer):+ if dtype == torch.bfloat16:+ pytest.skip("torch has no complex bfloat16 dtype, which So2 stores its rotation in")++ def inverse(parts):+ return So2(torch.complex(parts[:, 0], parts[:, 1])).inverse().matrix()++ parts = torch.tensor([[0.6, 0.8], [2.0, -3.0]], device=device, dtype=dtype)+ self.assert_close(torch_optimizer(inverse, fullgraph=True)(parts), inverse(parts))++class TestSo2DtypeMigration(BaseTester):@pytest.fixture(autouse=True)def _require_complex_dtype(self, dtype):diff --git a/tests/geometry/test_pose.py b/tests/geometry/test_pose.pyindex e6c198d9c..d7478553e 100644--- a/tests/geometry/test_pose.py+++ b/tests/geometry/test_pose.py@@ -263,10 +263,8 @@ class TestNamedPoseConventions(BaseTester):self.assert_close(a_from_b.pose.matrix(), expected, low_tolerance=low)def test_convention_named_pose_se2_composition_and_inverse(self, device, dtype):- if dtype not in (torch.float32, torch.float64):- pytest.skip(- "torch.complex has no bfloat16 overload, and So2.inverse needs a ComplexHalf reciprocal the CPU lacks"- )+ if dtype == torch.bfloat16:+ pytest.skip("torch.complex has no bfloat16 overload")# The Se2 half of the block: two non-commuting planar poses (M1 M2 != M2 M1 by 0.611), neither the identity.g1 = Se2.exp(torch.tensor([0.5, -1.0, 0.3], device=device, dtype=dtype))g2 = Se2.exp(torch.tensor([-0.2, 0.4, -0.7], device=device, dtype=dtype))