Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

fix(geometry): normalize the scale of small-root quartics (#5474)

Afloate753cc4609d9
diff --git a/changelog.d/5474.fixed.md b/changelog.d/5474.fixed.md
new file mode 100644
index 000000000..24d7f75fa
--- /dev/null
+++ b/changelog.d/5474.fixed.md
@@ -0,0 +1 @@
+`solve_quartic` now rescales small-root quartics before evaluating Ferrari's thresholds. It preserves four real roots and rejects non-real candidates when changing the variable's scale previously changed the returned root set. Ordinary and large-root rows retain their existing evaluation path. Rescaling remains bounded by the compute dtype's normal-exponent range and cannot recover underflowed input coefficients.
diff --git a/kornia/geometry/solvers/polynomial_solver.py b/kornia/geometry/solvers/polynomial_solver.py
index 525a30cc5..5f684f4db 100644
--- a/kornia/geometry/solvers/polynomial_solver.py
+++ b/kornia/geometry/solvers/polynomial_solver.py
@@ -489,8 +489,9 @@ 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>`_).
+ - Small-root quartics are evaluated after an exact power-of-two variable rescaling. Within the normal
+ exponent range of the compute dtype, the Ferrari thresholds then apply at unit coefficient scale.
+ Rows whose monic coefficient scale is at least 1 are unchanged.
- A row is solved as the cubic of its last four coefficients when its leading coefficient is 0, or when both
hold: ``|a|`` is smaller than ``1e-6`` (``1e-12`` in float64) times ``min(1, max_i |coeffs_i|)``, and the
scale-invariant root bound ``max(|b/a|, |c/a|^(1/2), |d/a|^(1/3), |e/a|^(1/4))`` exceeds ``1 / tol``
@@ -512,6 +513,11 @@ def solve_quartic(coeffs: torch.Tensor) -> torch.Tensor:
For ``float16`` and ``bfloat16`` quartics, Ferrari intermediates are evaluated in ``float32``
and the returned roots are cast back to the input dtype.
+ .. note::
+ Variable rescaling is bounded to normal reciprocal powers of two in the compute dtype. It does not
+ recover input coefficients that have underflowed, and extreme subnormal coefficient scales may remain
+ below unit scale.
+
.. note::
For a repeated (or near-repeated) real root, the resolvent-cubic solve internally
delegates to :func:`solve_cubic`'s finite-but-surrogate boundary-gradient convention;
@@ -572,6 +578,25 @@ def solve_quartic(coeffs: torch.Tensor) -> torch.Tensor:
C = d_q * inv_a
D = e_q * inv_a
+ # Solve for u = x / s when the monic root bound is below 1. Otherwise the unit floors in Ferrari's
+ # radicand, residual and derivative thresholds become absolute as x shrinks: real roots are dropped and
+ # complex roots turn into accepted non-roots. Within the helper's normal-exponent range, an exact power of
+ # two brings the coefficient scale into [1, 2) without rounding; extreme subnormal scales may stay below 1.
+ # Keep s = 1 for ordinary rows and x^4, and scale each coefficient
+ # one factor at a time to avoid underflow in s**4. The discrete scale is constant for autograd.
+ bound = torch.maximum(
+ torch.maximum(A.abs(), B.abs().sqrt()), torch.maximum(C.abs().pow(1.0 / 3.0), D.abs().sqrt().sqrt())
+ ).detach()
+ positive_bound = bound > 0
+ exponent = torch.floor(torch.log2(torch.where(positive_bound, bound, torch.ones_like(bound)))).clamp(max=0)
+ exponent = torch.where(positive_bound, exponent, torch.zeros_like(exponent))
+ variable_scale = _exact_power_of_two(exponent)
+ inverse_scale = _exact_power_of_two(-exponent)
+ A = A * inverse_scale
+ B = B * inverse_scale * inverse_scale
+ C = C * inverse_scale * inverse_scale * inverse_scale
+ D = D * inverse_scale * inverse_scale * inverse_scale * inverse_scale
+
# Resolvent cubic coefficients
rc_a = torch.ones_like(A)
rc_b = -B
@@ -817,6 +842,7 @@ def solve_quartic(coeffs: torch.Tensor) -> torch.Tensor:
accepted = root_candidates != 0
is_repeat = (coincide & outranked_by & accepted.unsqueeze(-1) & accepted.unsqueeze(-2)).any(dim=-1)
root_candidates = torch.where(is_repeat & is_simple, torch.zeros_like(root_candidates), root_candidates)
+ root_candidates = root_candidates * variable_scale.unsqueeze(-1)
roots1, roots2 = root_candidates[:, :2], root_candidates[:, 2:]
solutions[mask_quartic, 0:2] = roots1.to(dtype=solutions.dtype)
diff --git a/tests/geometry/solvers/test_polynomial_solver.py b/tests/geometry/solvers/test_polynomial_solver.py
index df79d85a8..725be232b 100644
--- a/tests/geometry/solvers/test_polynomial_solver.py
+++ b/tests/geometry/solvers/test_polynomial_solver.py
@@ -1425,12 +1425,58 @@ class TestConventionPolynomialSolvers(BaseTester):
pytest.skip("this row's 2e-11 and -4.2e-08 coefficients underflow float16 and keep 3 digits in bfloat16")
# #4833: x^4 - 0.009x^3 + 3e-05x^2 - 4.2e-08x + 2e-11 = (x - 0.001)(x - 0.002)(x^2 - 0.006x + 1e-05) has
# the real roots 1e-3 and 2e-3. This literal lost them in the resolvent cubic, whose R = 2e-18 sat under
- # the 1e-16 floor removed with #4914, not to the quartic's own unit floors, which #4833 still describes.
+ # the 1e-16 floor removed with #4914; the additional scale families below pin the quartic's own thresholds.
coeffs = torch.tensor([[1.0, -0.009, 3e-05, -4.2e-08, 2e-11]], device=device, dtype=dtype)
out = solver.solve_quartic(coeffs)
for root in (1e-3, 2e-3):
assert (out - root).abs().min() <= 1e-5 * root, out
+ @pytest.mark.parametrize("exponent", [-4, -8, -16, -24, -32])
+ def test_small_scale_quartic_preserves_four_real_roots_4833(self, exponent, device, dtype):
+ if dtype not in (torch.float32, torch.float64):
+ pytest.skip("The scaled coefficients are not representable accurately in half precision.")
+ # Replacing x by 2**exponent * u in (u-1)(u-2)(u-3)(u-4) scales coefficient k by 2**(k*exponent).
+ # All four roots stay real and separated; unit-floored Ferrari thresholds lost two at small scales.
+ scale = 2.0**exponent
+ # Form the final values before transfer: at exponent -32, float32 scale**4 is subnormal,
+ # while 24 * scale**4 is normal. Metal may flush that intermediate power to zero.
+ coefficients = torch.tensor(
+ [[value * scale**power for power, value in enumerate((1.0, -10.0, 35.0, -50.0, 24.0))]],
+ device=device,
+ dtype=dtype,
+ )
+ roots = solver.solve_quartic(coefficients).sort(dim=-1).values / scale
+ expected = torch.tensor([[1.0, 2.0, 3.0, 4.0]], device=device, dtype=dtype)
+ self.assert_close(roots, expected, rtol=1e-4, atol=1e-5)
+
+ @pytest.mark.parametrize("exponent", [-4, -8, -16, -32])
+ def test_small_scale_quartic_does_not_create_real_roots_4833(self, exponent, device, dtype):
+ if dtype not in (torch.float32, torch.float64):
+ pytest.skip("The scaled coefficients are not representable accurately in half precision.")
+ # (u^2 + 2u + 5)(u^2 + 2u + 5.01) has two negative quadratic discriminants, at every scale.
+ scale = 2.0**exponent
+ # Avoid the subnormal scale**4 intermediate while preserving the intended normal coefficients.
+ coefficients = torch.tensor(
+ [[value * scale**power for power, value in enumerate((1.0, 4.0, 14.01, 20.02, 25.05))]],
+ device=device,
+ dtype=dtype,
+ )
+ roots = solver.solve_quartic(coefficients)
+ self.assert_close(roots, torch.zeros_like(roots), rtol=0, atol=0)
+
+ def test_small_scale_quartic_gradcheck_4833(self, device):
+ # Perturb the unit-scale coefficients, then change variables. Perturbing tiny physical coefficients
+ # by gradcheck's absolute epsilon would change the root family instead of checking its local Jacobian.
+ coefficients = torch.tensor([[1.0, -10.0, 35.0, -50.0, 24.0]], device=device, dtype=torch.float64)
+ powers = torch.arange(5, device=device, dtype=torch.float64)
+ scale = 2.0**-16
+ coefficient_scale = scale**powers
+
+ def scaled_solver(value):
+ return solver.solve_quartic(value * coefficient_scale) / scale
+
+ self.gradcheck(scaled_solver, (coefficients.requires_grad_(),))
+
def test_convention_solve_quartic_scale_invariant_large_roots_4954(self, device, dtype):
if dtype != torch.float32:
pytest.skip(