Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

fix: correct quartic real root selection (#4357)

victorwon2001e5eeb3820575
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 2f43ea031..243c49365 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -501,6 +501,13 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
to the origin, and the exact principal-point path now has finite autograd gradients. The zero-radius decision is
made from the unsquared normalized coordinates, and the `float16` radius uses `float32` intermediates so its
squared value does not underflow; nonzero radial rescaling remains epsilon-free. (#4308, #4370)
+* `solve_quartic` now validates Ferrari resolvent candidates with a dtype-aware scaled residual,
+ falls back to the smallest scaled residual when no candidate passes, and keeps the Ferrari `E`
+ factorization away from an ill-conditioned `R` division. Cancellation-level `R^2` is snapped to
+ zero relative to the coefficient scale, and all Ferrari compute dtypes choose between the linear-
+ and constant-term `E` forms by normalized coefficient error; float32 also refines the selected
+ resolvent root once. The gradient-safe zero-radicand path remains intact, preventing half-precision
+ non-finite or dropped roots and full-precision non-roots while preserving the public contract. (#4357)
* `StereoCamera` now rejects projection matrices whose last two dimensions are not `(3, 4)` with a
`StereoException` naming the invalid camera. Previously, the shape guards never fired, so malformed
diff --git a/kornia/geometry/solvers/polynomial_solver.py b/kornia/geometry/solvers/polynomial_solver.py
index 561cb3eaf..94f8e10a7 100644
--- a/kornia/geometry/solvers/polynomial_solver.py
+++ b/kornia/geometry/solvers/polynomial_solver.py
@@ -254,6 +254,8 @@ def solve_quartic(coeffs: torch.Tensor) -> torch.Tensor:
In cases where a quartic polynomial has fewer than four real roots, the remaining entries
in the output are set to 0. Similarly, any non-real (complex) roots are represented as 0.
This is done to maintain a consistent output shape for all cases.
+ For ``float16`` and ``bfloat16`` quartics, Ferrari intermediates are evaluated in ``float32``
+ and the returned roots are cast back to the input dtype.
.. note::
For a repeated (or near-repeated) real root, the resolvent-cubic solve internally
@@ -263,14 +265,14 @@ def solve_quartic(coeffs: torch.Tensor) -> torch.Tensor:
.. note::
The same surrogate convention applies at this function's own two ``sqrt`` boundaries:
when the resolvent radicand ``R^2`` is 0 (a pure biquadratic such as :math:`x^4 - 16`)
- and when the :math:`R \approx 0` fallback's radicand is 0, backward suppresses the diverging
- ``sqrt`` derivative to keep gradients finite. The result is finite but is not the root
- Jacobian; the forward values are unaffected.
+ and when the constant-term identity used for ``E`` has a zero radicand, backward suppresses
+ the diverging ``sqrt`` derivative to keep gradients finite. The result is finite but is not
+ the root Jacobian; the forward values are unaffected.
"""
KORNIA_CHECK_SHAPE(coeffs, ["B", "5"])
# Coefficients
- a, b, c, d, e = coeffs.unbind(dim=-1)
+ a = coeffs[:, 0]
solutions = torch.zeros((len(coeffs), 4), device=coeffs.device, dtype=coeffs.dtype)
@@ -288,13 +290,19 @@ def solve_quartic(coeffs: torch.Tensor) -> torch.Tensor:
return solutions
# Normalized coefficients: x^4 + A*x^3 + B*x^2 + C*x + D = 0
- a_q = a[mask_quartic]
+ # 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_coeffs = coeffs[mask_quartic]
+ if coeffs.dtype in (torch.float16, torch.bfloat16):
+ quartic_coeffs = quartic_coeffs.float()
+ a_q, b_q, c_q, d_q, e_q = quartic_coeffs.unbind(dim=-1)
inv_a = 1.0 / a_q
- A = b[mask_quartic] * inv_a
- B = c[mask_quartic] * inv_a
- C = d[mask_quartic] * inv_a
- D = e[mask_quartic] * inv_a
+ A = b_q * inv_a
+ B = c_q * inv_a
+ C = d_q * inv_a
+ D = e_q * inv_a
# Resolvent cubic coefficients
rc_a = torch.ones_like(A)
@@ -307,14 +315,63 @@ def solve_quartic(coeffs: torch.Tensor) -> torch.Tensor:
# Solve cubic (Ferrari's method)
y_roots = solve_cubic(cubic_coeffs)
+ # solve_cubic uses zeros as placeholders for non-real roots. Filter those placeholders by
+ # checking which returned values actually satisfy the resolvent before ranking R^2.
+ y_abs = torch.abs(y_roots)
+ rc_b_exp = rc_b.unsqueeze(-1)
+ rc_c_exp = rc_c.unsqueeze(-1)
+ rc_d_exp = rc_d.unsqueeze(-1)
+ y_residual = ((y_roots + rc_b_exp) * y_roots + rc_c_exp) * y_roots + rc_d_exp
+ y_residual_scale = torch.maximum(
+ torch.ones_like(y_roots),
+ y_abs**3 + torch.abs(rc_b_exp) * y_abs**2 + torch.abs(rc_c_exp) * y_abs + torch.abs(rc_d_exp),
+ )
+ # Account for the rounding accumulated by the cubic solve and Horner evaluation in the
+ # actual Ferrari compute dtype. Candidates just outside this threshold are still compared
+ # by their scaled residual below rather than falling back to an unfiltered R^2 ranking.
+ residual_tol = max(zero_tol, 16.0 * torch.finfo(y_roots.dtype).eps)
+ if coeffs.dtype in (torch.float16, torch.bfloat16):
+ residual_tol = max(residual_tol, torch.finfo(coeffs.dtype).eps)
+ scaled_y_residual = torch.abs(y_residual) / y_residual_scale
+ valid_y_root = scaled_y_residual <= residual_tol
+
# Robust Root Selection: Pick y that maximizes R^2
A_sq = A * A
R_sq_candidates = 0.25 * A_sq.unsqueeze(-1) - B.unsqueeze(-1) + y_roots
- best_idx = torch.argmax(R_sq_candidates, dim=-1, keepdim=True)
+ ranked_R_sq = torch.where(valid_y_root, R_sq_candidates, torch.full_like(R_sq_candidates, float("-inf")))
+ has_valid_y_root = valid_y_root.any(dim=-1, keepdim=True)
+ best_valid_idx = torch.argmax(ranked_R_sq, dim=-1, keepdim=True)
+ best_residual_idx = torch.argmin(scaled_y_residual, dim=-1, keepdim=True)
+ best_idx = torch.where(has_valid_y_root, best_valid_idx, best_residual_idx)
y = torch.gather(y_roots, -1, best_idx).squeeze(-1)
R_sq = torch.gather(R_sq_candidates, -1, best_idx).squeeze(-1)
+ if coeffs.dtype == torch.float32:
+ # A selected float32 resolvent root can be accurate enough to identify the right candidate
+ # while still leaving enough factorization error to move a quartic root materially. Refine
+ # that already-selected root once; do not refine solve_cubic's zero-placeholder candidates.
+ y_residual_selected = ((y + rc_b) * y + rc_c) * y + rc_d
+ y_derivative = 3.0 * y * y + 2.0 * rc_b * y + rc_c
+ y_derivative_scale = torch.maximum(
+ torch.ones_like(y_derivative),
+ 3.0 * torch.abs(y) * torch.abs(y) + 2.0 * torch.abs(rc_b) * torch.abs(y) + torch.abs(rc_c),
+ )
+ refine_y = torch.abs(y_derivative) > torch.finfo(y.dtype).eps * y_derivative_scale
+ safe_y_derivative = torch.where(refine_y, y_derivative, torch.ones_like(y_derivative))
+ y = torch.where(refine_y, y - y_residual_selected / safe_y_derivative, y)
+ R_sq = torch.addcmul(y - B, A, A, value=0.25)
+
+ # R^2 = A^2 / 4 - B + y can retain cancellation-level roundoff for an exact biquadratic.
+ # Float64 needs a wider four-epsilon budget for cancellation between those terms, while
+ # float32 (including half inputs evaluated in float32) keeps the narrower half-epsilon budget
+ # so genuine small positive R^2 values are not snapped away. This happens before the guarded
+ # sqrt so the exact-zero gradient convention remains unchanged.
+ R_sq_scale = torch.maximum(torch.ones_like(R_sq), 0.25 * A_sq + torch.abs(B) + torch.abs(y))
+ R_sq_snap_multiplier = 4.0 if R_sq.dtype == torch.float64 else 0.5
+ R_sq_snap_tol = R_sq_snap_multiplier * torch.finfo(R_sq.dtype).eps * R_sq_scale
+ R_sq = torch.where(torch.abs(R_sq) <= R_sq_snap_tol, torch.zeros_like(R_sq), R_sq)
+
# `clamp(min=0).sqrt()` does not guard the gradient: d(sqrt)/dx is unbounded at 0, and on
# torch < 2.14 clamp passes the incoming gradient straight through at the bound, as measured in PR #4406, so
# R_sq == 0 -- a biquadratic such as x^4 - 16 -- gave inf and then nan. Substitute a safe
@@ -328,28 +385,38 @@ def solve_quartic(coeffs: torch.Tensor) -> torch.Tensor:
torch.zeros_like(R_sq),
)
- # Compute E term
- mask_R_small = torch.abs(R) < zero_tol
- mask_R_large = ~mask_R_small
- E = torch.zeros_like(R)
-
- if torch.any(mask_R_large):
- numerator = A[mask_R_large] * y[mask_R_large] - 2.0 * C[mask_R_large]
- denominator = 4.0 * R[mask_R_large]
- E[mask_R_large] = numerator / denominator
-
- # Fallback for R approx 0
- if torch.any(mask_R_small):
- radicand = 0.25 * y[mask_R_small] * y[mask_R_small] - D[mask_R_small]
- # Same guard as for R above.
- # Reachable, and its own gradient boundary: a quartic with no real roots, such as
- # (x^2+1)(x^2+4) = [1, 0, 5, 0, 4], drives R_sq < 0 -> R = 0 -> radicand == 0 exactly.
- mask_radicand_positive = radicand > 0
- E[mask_R_small] = torch.where(
- mask_radicand_positive,
- torch.sqrt(torch.where(mask_radicand_positive, radicand, torch.ones_like(radicand))),
- torch.zeros_like(radicand),
- )
+ # Compute |E| from the constant-term identity E^2 = y^2 / 4 - D instead of dividing by R.
+ # The sign follows the equivalent cross term A*y - 2*C; at an exact zero cross term, choose
+ # the positive branch to preserve the previous R~=0 forward convention. Guard the sqrt the
+ # same way as R above so a zero radicand keeps a finite surrogate gradient (#4339).
+ E_radicand = 0.25 * y * y - D
+ mask_E_radicand_positive = E_radicand > 0
+ E_magnitude = torch.where(
+ mask_E_radicand_positive,
+ torch.sqrt(torch.where(mask_E_radicand_positive, E_radicand, torch.ones_like(E_radicand))),
+ torch.zeros_like(E_radicand),
+ )
+ E_cross_term = A * y - 2.0 * C
+ E_constant = torch.where(E_cross_term < 0, -E_magnitude, E_magnitude)
+
+ # Away from R == 0, the division form can satisfy the linear coefficient more accurately,
+ # while the constant-term form remains stable near the division singularity. Compare their
+ # normalized Ferrari coefficient reconstruction errors in the actual Ferrari compute dtype.
+ safe_R = torch.where(R > 0, R, torch.ones_like(R))
+ E_division = E_cross_term / (4.0 * safe_R)
+ root_sq_scale = torch.maximum(torch.ones_like(R_sq), A_sq)
+ root_sq_scale = torch.maximum(root_sq_scale, torch.abs(B))
+ root_sq_scale = torch.maximum(root_sq_scale, torch.abs(y))
+ root_scale = torch.sqrt(root_sq_scale)
+
+ division_C_error = torch.abs(0.5 * A * y - 2.0 * R * E_division - C) / (root_sq_scale * root_scale)
+ division_D_error = torch.abs(0.25 * y * y - E_division * E_division - D) / (root_sq_scale * root_sq_scale)
+ constant_C_error = torch.abs(0.5 * A * y - 2.0 * R * E_constant - C) / (root_sq_scale * root_scale)
+ constant_D_error = torch.abs(0.25 * y * y - E_constant * E_constant - D) / (root_sq_scale * root_sq_scale)
+ division_error = torch.maximum(division_C_error, division_D_error)
+ constant_error = torch.maximum(constant_C_error, constant_D_error)
+ use_constant_E = (R == 0) | (constant_error < division_error)
+ E = torch.where(use_constant_E, E_constant, E_division)
# Solve two resulting quadratic equations
# Quad 1: x^2 + (A/2 - R)x + (y/2 - E) = 0
@@ -365,8 +432,8 @@ def solve_quartic(coeffs: torch.Tensor) -> torch.Tensor:
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))
- solutions[mask_quartic, 0:2] = roots1
- solutions[mask_quartic, 2:4] = roots2
+ solutions[mask_quartic, 0:2] = roots1.to(dtype=solutions.dtype)
+ solutions[mask_quartic, 2:4] = roots2.to(dtype=solutions.dtype)
return solutions
diff --git a/testing/half_precision_xfails/cpu_bfloat16.txt b/testing/half_precision_xfails/cpu_bfloat16.txt
index 4613958c2..1a6991552 100644
--- a/testing/half_precision_xfails/cpu_bfloat16.txt
+++ b/testing/half_precision_xfails/cpu_bfloat16.txt
@@ -337,7 +337,6 @@ call builtins.RuntimeError tests/geometry/liegroup/test_so2.py::TestSo2::test_ra
call 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-coeffs0-expected_solutions0]
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]
diff --git a/testing/half_precision_xfails/cpu_float16.txt b/testing/half_precision_xfails/cpu_float16.txt
index 6ae55e0c0..ad742f73b 100644
--- a/testing/half_precision_xfails/cpu_float16.txt
+++ b/testing/half_precision_xfails/cpu_float16.txt
@@ -356,15 +356,8 @@ call builtins.NotImplementedError tests/geometry/liegroup/test_so2.py::TestSo2::
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/solvers/test_polynomial_solver.py::TestQuarticSolver::test_convention_gradient_is_finite_for_a_pure_biquadratic_4229[cpu-float16-coeffs0-expected0-expected_grad0]
-call builtins.AssertionError tests/geometry/solvers/test_polynomial_solver.py::TestQuarticSolver::test_convention_gradient_is_finite_for_a_pure_biquadratic_4229[cpu-float16-coeffs1-expected1-expected_grad1]
-call builtins.AssertionError tests/geometry/solvers/test_polynomial_solver.py::TestQuarticSolver::test_convention_gradient_is_finite_for_a_pure_biquadratic_4229[cpu-float16-coeffs2-None-expected_grad2]
-call builtins.AssertionError tests/geometry/solvers/test_polynomial_solver.py::TestQuarticSolver::test_convention_gradient_does_not_leak_across_batch_rows_4334[cpu-float16]
call builtins.AssertionError tests/geometry/solvers/test_polynomial_solver.py::TestQuarticSolver::test_random[cpu-float16]
-call builtins.AssertionError tests/geometry/solvers/test_polynomial_solver.py::TestQuarticSolver::test_solve_quartic[cpu-float16-coeffs0-expected_solutions0]
call builtins.AssertionError tests/geometry/solvers/test_polynomial_solver.py::TestQuarticSolver::test_solve_quartic[cpu-float16-coeffs3-expected_solutions3]
-call builtins.AssertionError tests/geometry/solvers/test_polynomial_solver.py::TestQuarticSolver::test_solve_quartic[cpu-float16-coeffs4-expected_solutions4]
-call builtins.AssertionError tests/geometry/solvers/test_polynomial_solver.py::TestQuarticSolver::test_solve_quartic[cpu-float16-coeffs6-expected_solutions6]
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::TestConvSoftArgmax2d::test_cold_diag[cpu-float16]
call builtins.AssertionError tests/geometry/subpix/test_spatial_softargmax.py::TestConvSoftArgmax2d::test_cold_diag_norm[cpu-float16]
diff --git a/tests/geometry/solvers/test_polynomial_solver.py b/tests/geometry/solvers/test_polynomial_solver.py
index 75ee75749..fa59ce4b1 100644
--- a/tests/geometry/solvers/test_polynomial_solver.py
+++ b/tests/geometry/solvers/test_polynomial_solver.py
@@ -15,6 +15,7 @@
# limitations under the License.
#
+import numpy as np
import pytest
import torch
@@ -426,6 +427,236 @@ class TestQuarticSolver(BaseTester):
# to recover exactly those roots (no complex outputs).
self.assert_close(computed_roots_sorted, true_roots_sorted, atol=1e-3, rtol=1e-3)
+ @pytest.mark.parametrize(
+ "coeffs, expected_solutions",
+ [
+ (
+ [1.0, 2.0, 0.0, 0.0, -16.0],
+ [-2.760555, 0.0, 0.0, 1.638345],
+ ),
+ (
+ [1.0, 0.0, -4.0, 0.0, -5.0],
+ [-(5.0**0.5), 0.0, 0.0, 5.0**0.5],
+ ),
+ ],
+ )
+ def test_real_roots_with_complex_pair(self, coeffs, expected_solutions, device, dtype):
+ if dtype not in (torch.float32, torch.float64):
+ pytest.skip("This regression is limited to float32 and float64.")
+
+ coeffs_tensor = torch.tensor([coeffs], device=device, dtype=dtype)
+ expected = torch.tensor([expected_solutions], device=device, dtype=dtype)
+
+ roots = solver.solve_quartic(coeffs_tensor)
+ roots_sorted, _ = torch.sort(roots, dim=-1)
+
+ self.assert_close(roots_sorted, expected, rtol=1e-4, atol=1e-4)
+
+ def test_resolvent_filter_half_precision(self, device, dtype):
+ if dtype not in (torch.float16, torch.bfloat16):
+ pytest.skip("This regression targets half-precision resolvent validation.")
+
+ coeffs = torch.tensor([[1.0, -10.0, 35.0, -50.0, 24.0]], device=device, dtype=dtype)
+ expected = torch.tensor([[1.0, 2.0, 3.0, 4.0]], device=device, dtype=dtype)
+
+ roots = solver.solve_quartic(coeffs)
+ assert bool(torch.isfinite(roots).all()), roots
+ assert bool((roots != 0).all()), roots
+ roots_sorted, _ = torch.sort(roots, dim=-1)
+
+ self.assert_close(roots_sorted, expected)
+
+ @pytest.mark.parametrize(
+ "coeffs",
+ [
+ [1.0, 0.0, 0.0, 1e-6, -16.0],
+ [1.0, 1e-6, 0.0, 0.0, -16.0],
+ ],
+ )
+ def test_near_biquadratic_avoids_R_division(self, coeffs, device, dtype):
+ if dtype != torch.float64:
+ pytest.skip("This regression targets the float64 R^2 tolerance.")
+
+ coeffs_tensor = torch.tensor([coeffs], device=device, dtype=dtype)
+ expected = torch.tensor([[-2.0, 0.0, 0.0, 2.0]], device=device, dtype=dtype)
+
+ roots = solver.solve_quartic(coeffs_tensor)
+ roots_sorted, _ = torch.sort(roots, dim=-1)
+
+ self.assert_close(roots_sorted, expected, rtol=1e-6, atol=1e-6)
+
+ @pytest.mark.parametrize(
+ "coeffs, expected_solutions",
+ [
+ (
+ [1.0, -0.046868806472256, 0.0, 0.0, -3.9079498911375055],
+ [-1.3944338896982997, 0.0, 0.0, 1.417871547980907],
+ ),
+ (
+ [1.0, 0.0, 0.876698529368765, 1e-6, -0.007128260662146779],
+ [-0.08976001409129965, 0.0, 0.0, 0.08975889403473052],
+ ),
+ ],
+ )
+ def test_small_R_sq_constant_term_identity(self, coeffs, expected_solutions, device, dtype):
+ if dtype != torch.float64:
+ pytest.skip("This regression targets float64 resolvent conditioning.")
+
+ coeffs_tensor = torch.tensor([coeffs], device=device, dtype=dtype)
+ expected = torch.tensor([expected_solutions], device=device, dtype=dtype)
+
+ roots = solver.solve_quartic(coeffs_tensor)
+ roots_sorted, _ = torch.sort(roots, dim=-1)
+
+ self.assert_close(roots_sorted, expected, rtol=0.0, atol=1e-5)
+
+ def test_direct_coefficients_against_numpy(self, device, dtype):
+ if dtype not in (torch.float32, torch.float64):
+ pytest.skip("NumPy reference coverage is limited to float32 and float64.")
+
+ rng = np.random.default_rng(4346)
+ coeffs_np = np.concatenate([np.ones((64, 1)), rng.uniform(-5.0, 5.0, size=(64, 4))], axis=1)
+ expected_np = np.zeros((64, 4))
+
+ for idx, row in enumerate(coeffs_np):
+ roots = np.roots(row)
+ real_roots = roots.real[np.abs(roots.imag) <= 1e-7]
+ expected_np[idx, : len(real_roots)] = real_roots
+
+ coeffs_tensor = torch.tensor(coeffs_np, device=device, dtype=dtype)
+ expected = torch.tensor(expected_np, device=device, dtype=dtype)
+
+ computed_roots = solver.solve_quartic(coeffs_tensor)
+ computed_roots_sorted, _ = torch.sort(computed_roots, dim=-1)
+ expected_sorted, _ = torch.sort(expected, dim=-1)
+
+ if dtype == torch.float64:
+ self.assert_close(computed_roots_sorted, expected_sorted, rtol=0.0, atol=1e-5)
+ else:
+ self.assert_close(computed_roots_sorted, expected_sorted, rtol=1e-3, atol=1e-3)
+
+ def test_constant_term_E_float32_regression(self, device, dtype):
+ if dtype != torch.float32:
+ pytest.skip("This regression targets the float32 near-zero-R conditioning failure.")
+
+ coeffs = torch.tensor([[1.0, -2.4491360, 1.1192101, -2.0354464, -3.8231988]], device=device, dtype=dtype)
+ expected_real = torch.tensor([-0.782185, 2.552848], device=device, dtype=dtype)
+
+ roots = solver.solve_quartic(coeffs)
+ assert bool(torch.isfinite(roots).all()), roots
+ assert int(torch.count_nonzero(roots)) == 2, roots
+
+ real_roots = torch.sort(roots[roots != 0]).values
+ self.assert_close(real_roots, expected_real, rtol=1e-3, atol=1e-3)
+
+ residuals = (
+ coeffs[0, 0] * real_roots**4
+ + coeffs[0, 1] * real_roots**3
+ + coeffs[0, 2] * real_roots**2
+ + coeffs[0, 3] * real_roots
+ + coeffs[0, 4]
+ )
+ self.assert_close(residuals, torch.zeros_like(residuals), rtol=0.0, atol=1e-3)
+
+ def test_resolvent_fallback_float32_regression(self, device, dtype):
+ if dtype != torch.float32:
+ pytest.skip("This regression targets float32 resolvent fallback selection.")
+
+ coeffs = torch.tensor(
+ [[1.0, 4.340823173522949, 3.653407096862793, 3.0506274700164795, -2.266538143157959]],
+ device=device,
+ dtype=dtype,
+ )
+ expected_real = torch.tensor([-3.61119394, 0.41863132], device=device, dtype=dtype)
+
+ roots = solver.solve_quartic(coeffs)
+ assert bool(torch.isfinite(roots).all()), roots
+ assert int(torch.count_nonzero(roots)) == 2, roots
+
+ real_roots = torch.sort(roots[roots != 0]).values
+ self.assert_close(real_roots, expected_real, rtol=1e-3, atol=1e-3)
+
+ residuals = (
+ coeffs[0, 0] * real_roots**4
+ + coeffs[0, 1] * real_roots**3
+ + coeffs[0, 2] * real_roots**2
+ + coeffs[0, 3] * real_roots
+ + coeffs[0, 4]
+ )
+ self.assert_close(residuals, torch.zeros_like(residuals), rtol=0.0, atol=1e-3)
+
+ def test_E_reconstruction_precision_float64(self, device, dtype):
+ if dtype != torch.float64:
+ pytest.skip("This regression targets float64 Ferrari factorization precision.")
+
+ # (x^2 + 3x + 2)(x^2 - 5x + 2.000001)
+ coeffs = torch.tensor([[1.0, -2.0, -10.999999, -3.999997, 4.000002]], device=device, dtype=dtype)
+ discriminant = torch.sqrt(torch.tensor(16.999996, device=device, dtype=dtype))
+ expected = torch.tensor(
+ [[-2.0, -1.0, (5.0 - discriminant) / 2.0, (5.0 + discriminant) / 2.0]],
+ device=device,
+ dtype=dtype,
+ )
+
+ roots = torch.sort(solver.solve_quartic(coeffs), dim=-1).values
+ expected = torch.sort(expected, dim=-1).values
+ self.assert_close(roots, expected, rtol=0.0, atol=1e-12)
+
+ residuals = (
+ coeffs[:, 0:1] * roots**4
+ + coeffs[:, 1:2] * roots**3
+ + coeffs[:, 2:3] * roots**2
+ + coeffs[:, 3:4] * roots
+ + coeffs[:, 4:5]
+ )
+ self.assert_close(residuals, torch.zeros_like(residuals), rtol=0.0, atol=1e-12)
+
+ def test_biquadratic_R_sq_relative_snap(self, device, dtype):
+ if dtype not in (torch.float32, torch.float64):
+ pytest.skip("This regression targets full-precision R^2 cancellation handling.")
+
+ coeffs = torch.tensor([[1.0, 0.0, 2.9696312, 0.0, -2.3985832]], device=device, dtype=dtype)
+ expected_real = torch.tensor([-0.8128378975367444, 0.8128378975367438], device=device, dtype=dtype)
+
+ roots = solver.solve_quartic(coeffs)
+ assert bool(torch.isfinite(roots).all()), roots
+ assert int(torch.count_nonzero(roots)) == 2, roots
+
+ real_roots = torch.sort(roots[roots != 0]).values
+ self.assert_close(real_roots, expected_real, rtol=0.0, atol=5e-6)
+
+ residuals = (
+ coeffs[0, 0] * real_roots**4
+ + coeffs[0, 1] * real_roots**3
+ + coeffs[0, 2] * real_roots**2
+ + coeffs[0, 3] * real_roots
+ + coeffs[0, 4]
+ )
+ self.assert_close(residuals, torch.zeros_like(residuals), rtol=0.0, atol=2e-5)
+
+ def test_biquadratic_R_sq_relative_snap_float64_issue_literal(self, device, dtype):
+ if dtype != torch.float64:
+ pytest.skip("This regression targets the float64 R^2 cancellation budget.")
+
+ coeffs = torch.tensor([[1.0, 0.0, -4.0, 0.0, -5.0]], device=device, dtype=dtype)
+ expected_real = torch.tensor([-(5.0**0.5), 5.0**0.5], device=device, dtype=dtype)
+
+ roots = solver.solve_quartic(coeffs)
+ assert bool(torch.isfinite(roots).all()), roots
+ assert int(torch.count_nonzero(roots)) == 2, roots
+
+ real_roots = torch.sort(roots[roots != 0]).values
+ self.assert_close(real_roots, expected_real, rtol=1e-12, atol=1e-12)
+
+ residuals = (
+ coeffs[0, 0] * real_roots**4
+ + coeffs[0, 1] * real_roots**3
+ + coeffs[0, 2] * real_roots**2
+ + coeffs[0, 3] * real_roots
+ + coeffs[0, 4]
+ )
+ self.assert_close(residuals, torch.zeros_like(residuals), rtol=0.0, atol=1e-12)
+
def test_gradcheck(self, device):
# Use a specific polynomial with distinct roots to ensure gradient stability
# x^4 - 10x^3 + 35x^2 - 50x + 24 = 0
@@ -445,8 +676,8 @@ class TestQuarticSolver(BaseTester):
([1.0, 0.0, 0.0, 0.0, -16.0], [2.0, -2.0], [0.0, -0.5, 0.0, 0.0, 0.0]),
# x^4 - 1 = (x^2-1)(x^2+1): two real roots, +-1. R_sq lands exactly on 0.
([1.0, 0.0, 0.0, 0.0, -1.0], [1.0, -1.0], [0.0, -0.5, 0.0, 0.0, 0.0]),
- # (x^2+1)(x^2+4): no real roots. R_sq < 0 sends R to the `R approx 0` fallback,
- # whose own radicand is then exactly 0 -- the second sqrt site.
+ # (x^2+1)(x^2+4): no real roots. R_sq < 0 makes R zero, while the constant-term
+ # identity for E also has radicand 0 exactly -- the second sqrt site.
([1.0, 0.0, 5.0, 0.0, 4.0], None, [0.0, 0.0, 0.0, 0.0, 0.0]),
],
)
@@ -467,8 +698,8 @@ class TestQuarticSolver(BaseTester):
assert bool(torch.isfinite(c.grad).all()), c.grad
# Pin the value the guard produces, not just its finiteness: a "detach everything"
# pseudo-fix keeps the gradient finite but does not reproduce these numbers. This is a
- # convention, not a Jacobian -- the forward is discontinuous at exactly these points
- # (#4346), so there is no finite-difference derivative to pin against.
+ # convention at the zero-radicand sqrt boundaries (#4229/#4339), not a claim about the
+ # mathematical quartic-root Jacobian.
self.assert_close(
c.grad[0],
torch.tensor(expected_grad, device=device, dtype=dtype),