Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

fix(geometry): stabilize quadratic solver (#4919)

NiteeshGowda729ec18bc412f3
diff --git a/changelog.d/4919.fixed.md b/changelog.d/4919.fixed.md
new file mode 100644
index 000000000..59bf384e9
--- /dev/null
+++ b/changelog.d/4919.fixed.md
@@ -0,0 +1 @@
+`solve_quadratic` no longer loses the root of smaller magnitude to cancellation when `|4ac|` is much smaller than `b^2`: it uses `q = -(b + sign(b) sqrt(D)) / 2` and returns `c / q` and `q / a` in the previous slot order. `[1e-8, 2, -6]` gave `[0, -2e8]` in float32 and now gives `[3, -2e8]`, and the root's gradient is correct too.
diff --git a/kornia/geometry/solvers/polynomial_solver.py b/kornia/geometry/solvers/polynomial_solver.py
index c817303c9..268174e12 100644
--- a/kornia/geometry/solvers/polynomial_solver.py
+++ b/kornia/geometry/solvers/polynomial_solver.py
@@ -75,9 +75,6 @@ def solve_quadratic(coeffs: torch.Tensor) -> torch.Tensor:
mask_linear = a == 0
mask_b_zero = b == 0
- # Calculate 1/(2*a) for efficient computation
- inv_2a = 0.5 / torch.where(mask_linear, one, a)
-
# Branch-free selection so the function traces under graph capture. The square root is only taken
# where delta > 0: a zero discriminant yields the double root -b/(2a) with sqrt_delta = 0, and a
# negative one yields zeros; feeding those lanes a safe placeholder keeps their gradients finite.
@@ -87,8 +84,19 @@ def solve_quadratic(coeffs: torch.Tensor) -> torch.Tensor:
mask_nonpositive, zero, torch.sqrt(torch.where(mask_nonpositive, torch.ones_like(delta), delta))
)
- root_plus = (-b + sqrt_delta) * inv_2a
- root_minus = (-b - sqrt_delta) * inv_2a
+ # (-b +- sqrt(delta)) / (2a) subtracts nearly equal numbers for the root of smaller magnitude when
+ # |4ac| << b^2 (#4914). q = -(b + sign(b) sqrt(delta)) / 2 adds numbers of the same sign; the roots are
+ # q / a and c / q, which are (-b - sqrt(delta)) / (2a) and (-b + sqrt(delta)) / (2a) for b >= 0 and the
+ # other way round for b < 0. c / q is only taken where delta > 0 and a != 0, where |q| >= sqrt(delta) / 2 > 0;
+ # at a double root both slots are q / a = -b / (2a). Elsewhere a placeholder q keeps the discarded lane's
+ # gradient finite: with no real root and a tiny b, c / q^2 overflows and torch.where would turn it into nan.
+ sign_b = torch.where(b >= 0, one, -one)
+ q = -0.5 * (b + sign_b * sqrt_delta)
+ mask_distinct = ~(mask_nonpositive | mask_linear)
+ root_q_over_a = q / torch.where(mask_linear, one, a)
+ root_c_over_q = torch.where(mask_distinct, c / torch.where(mask_distinct, q, one), root_q_over_a)
+ root_plus = torch.where(b >= 0, root_c_over_q, root_q_over_a)
+ root_minus = torch.where(b >= 0, root_q_over_a, root_c_over_q)
# The a * x^2 / b term is 0 in the forward pass, but it keeps the root's dependence on a in the
# gradient (d root / da = -root^2 / b). With b == 0 as well there is no root to report. The lane
diff --git a/tests/geometry/solvers/test_polynomial_solver.py b/tests/geometry/solvers/test_polynomial_solver.py
index ced10fa24..7ca5d54fb 100644
--- a/tests/geometry/solvers/test_polynomial_solver.py
+++ b/tests/geometry/solvers/test_polynomial_solver.py
@@ -70,6 +70,45 @@ class TestQuadraticSolver(BaseTester):
coeffs = torch.tensor([[1.0, -5.0, 6.0]], device=device, dtype=torch.float64, requires_grad=True)
self.gradcheck(solver.solve_quadratic, (coeffs,))
+ def test_stable_formula_4914(self, device, dtype):
+ # #4914: the direct quadratic formula loses the finite root through cancellation
+ # when |4ac| << b^2. The stable formulation should retain both real roots.
+ if dtype == torch.float16:
+ pytest.skip("1e-8 rounds to 0 in float16, and the root near -2e8 is beyond its range")
+ coeffs = torch.tensor([[1e-8, 2.0, -6.0]], device=device, dtype=dtype)
+ roots = solver.solve_quadratic(coeffs)
+
+ expected = torch.tensor([3.0, -2e8], device=device, dtype=dtype)
+ self.assert_close(roots[0], expected, rtol=1e-6, atol=1e-5)
+
+ def test_stable_formula_gradient_4914(self, device, dtype):
+ if dtype not in (torch.float32, torch.float64):
+ pytest.skip("Gradient values are checked in float32 and float64.")
+ # By the implicit function theorem d root / d coeffs[k] = -root^(2 - k) / p'(root), with p'(r) = 2ar + b.
+ # (-b + sqrt(D)) / (2a) loses the root near 3 of 1e-8 x^2 + 2x - 6 to cancellation, and its gradient with
+ # it: d root / da came out as 3e8 in float32 and -4.96 instead of -4.5 in float64.
+ x = torch.tensor([[1e-8, 2.0, -6.0]], device=device, dtype=dtype, requires_grad=True)
+ roots = solver.solve_quadratic(x)
+ for slot in range(2):
+ (grad,) = torch.autograd.grad(roots[0, slot], x, retain_graph=True)
+ r = roots[0, slot].detach()
+ expected = -torch.stack([r * r, r, torch.ones_like(r)]) / (2e-8 * r + 2.0)
+ self.assert_close(grad[0], expected, rtol=1e-5, atol=0.0)
+
+ def test_stable_formula_keeps_order_and_edge_gradients_4914(self, device, dtype):
+ # Slot 0 is (-b + sqrt(D)) / (2a) also for b == 0, where the sign of b does not pick the branch.
+ out = solver.solve_quadratic(torch.tensor([[1.0, 0.0, -4.0], [-1.0, 0.0, 4.0]], device=device, dtype=dtype))
+ self.assert_close(out, torch.tensor([[2.0, -2.0], [-2.0, 2.0]], device=device, dtype=dtype))
+ if dtype not in (torch.float32, torch.float64):
+ return
+ # c / q is only taken where the two real roots differ. With no real root and a tiny b, c / q^2 overflows,
+ # and torch.where would turn the row's zero gradient into nan. At the double root of x^2 - 6x + 9 both
+ # slots are -b / (2a), so the gradient of their sum is that of -b / a, [b / a^2, -1 / a, 0].
+ tiny = 1e-25 if dtype == torch.float32 else 1e-160
+ x = torch.tensor([[1.0, tiny, 1.0], [1.0, -6.0, 9.0]], device=device, dtype=dtype, requires_grad=True)
+ (grad,) = torch.autograd.grad(solver.solve_quadratic(x).sum(), x)
+ self.assert_close(grad, torch.tensor([[0.0, 0.0, 0.0], [-6.0, -1.0, 0.0]], device=device, dtype=dtype))
+
class TestCubicSolver(BaseTester):
def test_smoke(self, device, dtype):