π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
fix: preserve small real quartic roots (#5382)
Karnajeet Gosaviaaeedce1a8cc
diff --git a/changelog.d/5382.fixed.md b/changelog.d/5382.fixed.mdnew file mode 100644index 000000000..841a5210e--- /dev/null+++ b/changelog.d/5382.fixed.md@@ -0,0 +1 @@+`solve_quartic` no longer loses the small real roots of a quartic whose other root pair is much larger. Ferrari's small quadratic factor is now rebuilt from the large one with Vieta's relations instead of a cancelling difference. In float32, `(x - 0.5)(x + 0.25)(x^2 + 1e7)` used to return no real roots and `(x - 0.5)(x + 0.25)(x - 1e4)(x - 2e4)` only the two large ones; both now return all their real roots. In float64, a close small pair next to a large complex pair could lose both roots (`(x - 0.01)(x - 0.0105)(x^2 + 2000 x + 4e9)`) or come back about 1e-7 off; such roots are now accurate to about 1e-15. Rows whose two quadratic factors are not separated (constant terms within a factor of 16) are unchanged.diff --git a/kornia/geometry/solvers/polynomial_solver.py b/kornia/geometry/solvers/polynomial_solver.pyindex 563e8a4c2..525a30cc5 100644--- a/kornia/geometry/solvers/polynomial_solver.py+++ b/kornia/geometry/solvers/polynomial_solver.py@@ -697,6 +697,24 @@ def solve_quartic(coeffs: torch.Tensor) -> torch.Tensor:q2_b = 0.5 * A + Rq2_c = 0.5 * y + E+ # When one root pair is much larger than the other, the small factor's constant y/2 -+ E is the difference of two+ # numbers of the large pair's size, and in float32 that cancellation flips its discriminant: the small real roots+ # come back as zero placeholders. The large factor has no such cancellation. Rebuild the small factor from+ # it with Vieta's relations for the product (x^2 + b1 x + c1)(x^2 + b2 x + c2): c1 * c2 = D and+ # b1 * c2 + b2 * c1 = C, as solve_quadratic takes its small root as c / q. A separation of _DOMINANT_ROOT_RATIO+ # between the two constants decides it; the roots do not depend on the ratio anywhere from 2 to 1024.+ first_small = torch.abs(q1_c) <= torch.abs(q2_c)+ c_large = torch.where(first_small, q2_c, q1_c)+ b_large = torch.where(first_small, q2_b, q1_b)+ separated = _DOMINANT_ROOT_RATIO * torch.minimum(torch.abs(q1_c), torch.abs(q2_c)) < torch.abs(c_large)+ safe_c_large = torch.where(separated, c_large, torch.ones_like(c_large))+ c_small = D / safe_c_large+ b_small = (C - b_large * c_small) / safe_c_large+ q1_b = torch.where(separated & first_small, b_small, q1_b)+ q1_c = torch.where(separated & first_small, c_small, q1_c)+ q2_b = torch.where(separated & ~first_small, b_small, q2_b)+ q2_c = torch.where(separated & ~first_small, c_small, q2_c)+roots1 = solve_quadratic(torch.stack([q1_a, q1_b, q1_c], dim=1))roots2 = solve_quadratic(torch.stack([q2_a, q2_b, q2_c], dim=1))diff --git a/tests/geometry/solvers/test_polynomial_solver.py b/tests/geometry/solvers/test_polynomial_solver.pyindex 6438a918e..df79d85a8 100644--- a/tests/geometry/solvers/test_polynomial_solver.py+++ b/tests/geometry/solvers/test_polynomial_solver.py@@ -1455,6 +1455,68 @@ class TestConventionPolynomialSolvers(BaseTester):expected = torch.tensor([[10000.0, 20000.0, 30000.0, 40000.0]], device=device, dtype=dtype)self.assert_close(out, expected, atol=1e-6, rtol=1e-9)+ def test_quartic_keeps_small_real_roots_next_to_large_complex_pair_5348(self, device, dtype):+ if dtype != torch.float32:+ pytest.skip("this issue is specific to float32 resolvent accuracy")+ # (x - 0.5)(x + 0.25)(x^2 + M): the real roots stay fixed while the other pair grows.+ values = [1e5, 1e6, 1e7, 1e8]+ coeffs = torch.tensor(+ [[1.0, -0.25, value - 0.125, -0.25 * value, -0.125 * value] for value in values],+ device=device,+ dtype=dtype,+ )++ roots = solver.solve_quartic(coeffs)++ assert torch.equal((roots != 0).sum(dim=-1), torch.full((len(values),), 2, device=device))+ expected = torch.tensor([[-0.25, 0.0, 0.0, 0.5]] * len(values), device=device, dtype=dtype)+ self.assert_close(roots.sort(dim=-1).values, expected, atol=1e-4, rtol=1e-4)++ def test_quartic_keeps_small_real_roots_next_to_large_real_pair_5348(self, device, dtype):+ if dtype != torch.float32:+ pytest.skip("the cancellation pinned here is a float32 one")+ # (x - 0.5)(x + 0.25)(x - 1e4)(x - 2e4): the large pair is real, so recovering the small roots from zero+ # placeholders afterwards cannot reach them; rebuilding the small factor from the large one does.+ coeffs = torch.tensor([[1.0, -30000.25, 200007499.875, -49996250.0, -25000000.0]], device=device, dtype=dtype)++ roots = solver.solve_quartic(coeffs).sort(dim=-1).values++ expected = torch.tensor([[-0.25, 0.5, 10000.0, 20000.0]], device=device, dtype=dtype)+ self.assert_close(roots, expected, atol=1e-5, rtol=1e-6)++ def test_quartic_close_small_pair_next_to_large_complex_pair_float64_5348(self, device, dtype):+ if dtype != torch.float64:+ pytest.skip("float64 rows; the float32 family is pinned above")+ # (x - 0.01)(x - 0.0105)(x^2 + 2000 x + 4e9) and (x + 0.03)(x + 0.0315)(x^2 + 100 x + 1e10). The cancellation+ # also costs float64: the first row lost both real roots and the second was 1.9e-7 off. The complex pair's+ # nonzero linear term makes the small factor's x coefficient depend on b_large * c_small.+ coeffs = torch.tensor(+ [+ [1.0, 1999.9795, 3999999959.000105, -81999999.79, 420000.0],+ [1.0, 100.0615, 10000000006.150944, 615000000.0945, 9450000.0],+ ],+ device=device,+ dtype=dtype,+ )++ roots = solver.solve_quartic(coeffs)++ assert torch.equal((roots != 0).sum(dim=-1), torch.full((2,), 2, device=device))+ expected = torch.tensor([[0.0, 0.0, 0.01, 0.0105], [-0.0315, -0.03, 0.0, 0.0]], device=device, dtype=dtype)+ self.assert_close(roots.sort(dim=-1).values, expected, atol=0.0, rtol=1e-12)++ def test_quartic_gradient_finite_with_tiny_quadratic_coefficient(self, device, dtype):+ # x^4 + 1e-12 x^2 + x + 1 has no real roots. A candidate derived from B x^2 + C x + D would sit near+ # -C / B = -1e12, whose fourth power overflows float32 in a discarded torch.where lane and turns every+ # coefficient gradient into nan, although the returned roots are all zero.+ coeffs = torch.tensor([[1.0, 0.0, 1e-12, 1.0, 1.0]], device=device, dtype=dtype, requires_grad=True)++ roots = solver.solve_quartic(coeffs)+ roots.sum().backward()++ assert torch.equal(roots.detach(), torch.zeros_like(roots))+ assert torch.isfinite(coeffs.grad).all()+def test_convention_solve_quartic_tiny_leading_coefficient_real_roots_4954(self, device, dtype):if dtype != torch.float32:pytest.skip("pinned in float32, where the old absolute tolerance (1e-6) is what this row crosses")