🐍 Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
fix(solvers): solve half-precision cubics in float32 in solve_cubic (#4898)
Rızgar Ozan771fb4619df9
diff --git a/README.md b/README.mdindex 81181d4ef..cbde48b9a 100644--- a/README.md+++ b/README.md@@ -103,7 +103,7 @@ covers CUDA or MPS half precision.| `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.solvers` | ⚠️ | ⚠️ | 2 / 2 | `solve_quartic` accuracy on random and one reference quartic |+| `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 || `kornia.geometry.ransac` | ⚠️ | ⚠️ | 4 / 4 | The essential and fundamental models raise through the epipolar solvers |diff --git a/changelog.d/4898.fixed.md b/changelog.d/4898.fixed.mdnew file mode 100644index 000000000..3f4854b16--- /dev/null+++ b/changelog.d/4898.fixed.md@@ -0,0 +1 @@+`solve_cubic` no longer returns NaN for `float16` cubics whose `Q^3` underflows to 0 while `R` is 0, such as `x^3 - 0.003x` or `x^3 + 0.003x`. Half-precision cubics are now solved in `float32` and the roots are cast back to the input dtype, as `solve_quartic` already did for its Ferrari path. This also fixes the `bfloat16` reference quartic that went through the cubic fallback. (#4856)diff --git a/kornia/geometry/solvers/polynomial_solver.py b/kornia/geometry/solvers/polynomial_solver.pyindex 8628aab33..bb8c6f2f4 100644--- a/kornia/geometry/solvers/polynomial_solver.py+++ b/kornia/geometry/solvers/polynomial_solver.py@@ -103,6 +103,8 @@ def solve_cubic(coeffs: torch.Tensor) -> torch.Tensor:In cases where a cubic polynomial has only one or two real roots, the output for the non-realroots should be represented as 0. Thus, the output for a single real root should be in theformat [real_root, 0, 0], and for two real roots, it should be [real_root_1, real_root_2, 0].+ ``float16`` and ``bfloat16`` cubics are solved in ``float32`` and the roots are cast back to+ the input dtype... note::At the acos boundary reached by a repeated (or near-repeated) real root, backward suppresses@@ -113,6 +115,13 @@ def solve_cubic(coeffs: torch.Tensor) -> torch.Tensor:"""KORNIA_CHECK_SHAPE(coeffs, ["B", "4"])+ # In float16, Q^3 underflows to 0 for |Q| below about 4e-3. With R == 0 that makes D == 0, so+ # the D <= 0 branch divides 0 by sqrt(0) when Q < 0 and takes sqrt(-Q) of a positive Q when+ # Q > 0: every root comes back NaN. Solve half-precision cubics in float32 and return the roots+ # in the input dtype, as solve_quartic does for its Ferrari path.+ if coeffs.dtype in (torch.float16, torch.bfloat16):+ return solve_cubic(coeffs.float()).to(coeffs.dtype)+_PI = torch.tensor(math.pi, device=coeffs.device, dtype=coeffs.dtype)# Coefficients of cubic equation@@ -330,7 +339,7 @@ def solve_quartic(coeffs: torch.Tensor) -> torch.Tensor:# Normalized coefficients: x^4 + A*x^3 + B*x^2 + C*x + D = 0# The Ferrari intermediates overflow or quantize too coarsely in half dtypes even when the# final roots are representable. Keep the public half-precision contract while evaluating the- # quartic-only path in float32; the cubic fallback above remains in the input dtype.+ # quartic-only path in float32; the cubic fallback above does the same inside solve_cubic.quartic_coeffs = coeffs[mask_quartic]if coeffs.dtype in (torch.float16, torch.bfloat16):quartic_coeffs = quartic_coeffs.float()diff --git a/testing/half_precision_xfails/cpu_bfloat16.txt b/testing/half_precision_xfails/cpu_bfloat16.txtindex 84b6910cd..0c8d09021 100644--- a/testing/half_precision_xfails/cpu_bfloat16.txt+++ b/testing/half_precision_xfails/cpu_bfloat16.txt@@ -305,7 +305,6 @@ call builtins.RuntimeError tests/geometry/liegroup/test_so2.py::TestSo2::test_racall builtins.AssertionError tests/geometry/liegroup/test_so3.py::TestSo3::test_ortho[cpu-bfloat16-2]call builtins.AssertionError tests/geometry/liegroup/test_so3.py::TestSo3::test_ortho[cpu-bfloat16-5]call builtins.AssertionError tests/geometry/solvers/test_polynomial_solver.py::TestQuarticSolver::test_random[cpu-bfloat16]-call builtins.AssertionError tests/geometry/solvers/test_polynomial_solver.py::TestQuarticSolver::test_solve_quartic[cpu-bfloat16-coeffs3-expected_solutions3]call builtins.AssertionError tests/geometry/subpix/test_dsnt.py::TestRenderGaussian2d::test_normalized_coordinates[cpu-bfloat16]call builtins.AssertionError tests/geometry/subpix/test_dsnt.py::TestRenderGaussian2d::test_pixel_coordinates[cpu-bfloat16]call builtins.AssertionError tests/geometry/subpix/test_spatial_softargmax.py::TestConvQuadInterp3dModule::test_diag[cpu-bfloat16]diff --git a/tests/geometry/solvers/test_polynomial_solver.py b/tests/geometry/solvers/test_polynomial_solver.pyindex cbbebe6db..93734ac73 100644--- a/tests/geometry/solvers/test_polynomial_solver.py+++ b/tests/geometry/solvers/test_polynomial_solver.py@@ -177,10 +177,7 @@ class TestCubicSolver(BaseTester):x = torch.tensor([coeffs], device=device, dtype=dtype, requires_grad=True)roots = solver.solve_cubic(x)expected = torch.tensor([[root, 0.0, 0.0]], device=device, dtype=dtype)- # In half precision R itself carries the rounding of its cancelling terms (bfloat16 gives- # R = -0.074 instead of -0.0625 for the shifted case), and the cube root amplifies it.- tol = {torch.float16: 1e-2, torch.bfloat16: 5e-2}.get(dtype)- self.assert_close(roots.detach(), expected, rtol=tol, atol=tol)+ self.assert_close(roots.detach(), expected)roots[:, 0].sum().backward()assert bool(torch.isfinite(x.grad).all()), x.grad@@ -192,6 +189,20 @@ class TestCubicSolver(BaseTester):expected_grad = torch.tensor([[-(root ** (3 - k)) / dp for k in range(4)]], device=device, dtype=dtype)self.assert_close(x.grad, expected_grad)+ @pytest.mark.parametrize("e", [3e-3, 1e-3, -3e-3, -1e-3])+ def test_odd_cubic_with_small_q_4856(self, e, device, dtype):+ # #4856: for x^3 - e*x, R == 0 and |Q| = |e| / 3 is small enough that Q^3 underflowed to 0 in+ # float16, so D == 0 and all three roots came back nan (e > 0 divided 0 by 0, e < 0 took+ # sqrt(-Q) of a positive Q).+ x = torch.tensor([[1.0, 0.0, -e, 0.0]], device=device, dtype=dtype, requires_grad=True)+ roots = solver.solve_cubic(x)+ s = e**0.5 if e > 0 else 0.0+ expected = torch.tensor([[s, -s, 0.0]], device=device, dtype=dtype)+ self.assert_close(roots.detach(), expected)++ roots.sum().backward()+ assert bool(torch.isfinite(x.grad).all()), x.grad+class TestMultiplyDegOnePoly(BaseTester):def test_smoke(self, device, dtype):