🐍 Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
fix(geometry): make solve_quartic's cubic fallback tolerance relative to the row (#4921)
Rızgar Ozane240c7aaf5b7
diff --git a/changelog.d/4921.fixed.md b/changelog.d/4921.fixed.mdnew file mode 100644index 000000000..4e2ef8152--- /dev/null+++ b/changelog.d/4921.fixed.md@@ -0,0 +1 @@+`solve_quartic` decides whether a row is really a cubic relative to the row's scale: the leading-coefficient tolerance for the cubic fallback (`1e-6`, or `1e-12` in float64) is multiplied by the largest coefficient magnitude of the row, capped at 1. `(x - 1)(x - 2)(x - 3)(x - 4)` scaled by `5e-7` in float32 (or `1e-13` in float64) now returns `1, 2, 3, 4` instead of a single wrong root. Rows whose largest coefficient is 1 or more keep the previous absolute tolerance. (#4905)diff --git a/kornia/geometry/solvers/polynomial_solver.py b/kornia/geometry/solvers/polynomial_solver.pyindex 9365d83b9..c817303c9 100644--- a/kornia/geometry/solvers/polynomial_solver.py+++ b/kornia/geometry/solvers/polynomial_solver.py@@ -318,10 +318,11 @@ def solve_quartic(coeffs: torch.Tensor) -> torch.Tensor:Convention:- Coefficient layout and zero padding as :func:`solve_quadratic`; the roots are unordered.- Known defects: the solver is not scale-invariant, so a quartic whose roots are all small can lose real- roots and return values that are not roots (`#4833 <https://github.com/kornia/kornia/issues/4833>`_);- a leading coefficient below ``1e-6`` in magnitude (``1e-12`` in float64) counts as zero whatever the- other coefficients are, so a small multiple of a quartic is solved as a cubic and loses its roots- (`#4905 <https://github.com/kornia/kornia/issues/4905>`_).+ roots and return values that are not roots (`#4833 <https://github.com/kornia/kornia/issues/4833>`_).+ - A row is solved as the cubic of its last four coefficients when its leading coefficient is 0 or smaller in+ magnitude than ``1e-6`` (``1e-12`` in float64) times ``min(1, max_i |coeffs_i|)``. For a row whose largest+ coefficient is at most 1 the test is relative, so scaling the row down does not change how it is solved;+ at unit scale and above it is absolute, as before.Args:coeffs : The coefficients quartic equation : `(B, 5)`@@ -360,8 +361,10 @@ def solve_quartic(coeffs: torch.Tensor) -> torch.Tensor:# float32's cubic-fallback tolerance; float64's 1e-12 would also round to 0 in float16.zero_tol = 1e-6 if coeffs.dtype in (torch.float32, torch.float16, torch.bfloat16) else 1e-12- # Cubic fallback for a approx 0- mask_a_zero = torch.abs(a) < zero_tol+ # Cubic fallback for a approx 0. Scaling a row does not move its roots, so a row whose largest coefficient is+ # below 1 gets a proportionally smaller tolerance; rows at unit scale or above keep the absolute one.+ row_scale = coeffs.abs().amax(dim=-1).clamp(max=1.0)+ mask_a_zero = (torch.abs(a) < zero_tol * row_scale) | (a == 0)mask_quartic = ~mask_a_zeroif torch.any(mask_a_zero):diff --git a/tests/geometry/solvers/test_polynomial_solver.py b/tests/geometry/solvers/test_polynomial_solver.pyindex d08e72d49..ced10fa24 100644--- a/tests/geometry/solvers/test_polynomial_solver.py+++ b/tests/geometry/solvers/test_polynomial_solver.py@@ -1198,15 +1198,45 @@ class TestConventionPolynomialSolvers(BaseTester):for root in (1e-3, 2e-3):assert (out - root).abs().min() > 1e-2 * root- def test_wart_solve_quartic_absolute_leading_tolerance_4905(self, device, dtype):+ def test_convention_solve_quartic_relative_leading_tolerance_4905(self, device, dtype):# (x - 1)(x - 2)(x - 3)(x - 4), and the same row times a power of two (exact in every dtype) that brings the# leading coefficient below the fallback tolerance (1e-6, or 1e-12 in float64).row = torch.tensor([[1.0, -10.0, 35.0, -50.0, 24.0]], device=device, dtype=dtype)scale = 2.0**-41 if dtype == torch.float64 else 2.0**-21roots = torch.tensor([[1.0, 2.0, 3.0, 4.0]], device=device, dtype=dtype)self.assert_close(solver.solve_quartic(row).sort(dim=-1).values, roots)- # #4905: the tolerance is absolute, so the scaled row is solved as the cubic that remains without x^4, and- # the roots 2, 3 and 4 are lost. Once the test is relative, both rows give the same roots.- out = solver.solve_quartic(row * scale)- for root in (2.0, 3.0, 4.0):- assert (out - root).abs().min() > 0.5+ # #4905: below unit scale the tolerance is relative to the row's largest coefficient, so scaling the row+ # down does not turn it into a cubic.+ self.assert_close(solver.solve_quartic(row * scale).sort(dim=-1).values, roots)++ def test_convention_solve_quartic_cubic_fallback_4905(self, device, dtype):+ # Rows at unit scale or above keep the absolute tolerance: (x - 50)(x - 60)(x - 70)(x - 80) has a leading+ # coefficient 6e-8 times its constant term and is still a quartic, while a leading coefficient below the+ # tolerance on a unit-scale row, or an exact 0 on an all-zero row, still falls back to the cubic. Below unit+ # scale the test is relative in both directions: the unit-scale fallback row times 2^-14 falls back as well.+ if dtype in (torch.float16, torch.bfloat16):+ pytest.skip("the 50..80 row's 1.68e7 constant term overflows float16 and keeps 3 digits in bfloat16")+ tiny = 1e-13 if dtype == torch.float64 else 1e-7+ cubic_row = [tiny, 1.0, -6.0, 11.0, -6.0]+ coeffs = torch.tensor(+ [+ [1.0, -260.0, 25100.0, -1066000.0, 16800000.0],+ cubic_row,+ [c * 2.0**-14 for c in cubic_row],+ [0.0, 0.0, 0.0, 0.0, 0.0],+ ],+ device=device,+ dtype=dtype,+ requires_grad=True,+ )+ expected = torch.tensor(+ [[50.0, 60.0, 70.0, 80.0], [0.0, 1.0, 2.0, 3.0], [0.0, 1.0, 2.0, 3.0], [0.0, 0.0, 0.0, 0.0]],+ device=device,+ dtype=dtype,+ )+ roots = solver.solve_quartic(coeffs)+ self.assert_close(roots.detach().sort(dim=-1).values, expected, atol=1e-3, rtol=1e-4)+ # The all-zero row's relative tolerance is 0; the exact a == 0 test keeps it off the quartic path, where its+ # gradient is nan.+ (grad,) = torch.autograd.grad(roots.sum(), coeffs)+ assert grad.isfinite().all()