Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

fix(solvers): stop solve_cubic's D>0 branch poisoning other rows' gradients (#4338)

Dipak Chaudhari8f292308a75f
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 14cb45845..27c71fd5e 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -410,6 +410,13 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
form and reshapes internally, but both callers index dim 1 as the vertex axis, so the box axis was
read as the vertices: an out-of-bounds error with one box, and three `(1, 3)` tensors -- one value
per coordinate rather than per box -- with eight. (#4248, #4351)
+* `solve_cubic` and `solve_quartic` return finite gradients for a row whose neighbours in the
+ same batch take a different branch. The `D > 0` branch selected its rows with `abs(R) > 1e-16`
+ alone, so it evaluated `sqrt(D)` on `D < 0` rows too. Those rows are never read back, but the
+ resulting `-Q / nan` stays in the graph and its backward returns `nan`, which reaches every
+ coefficient: a three-real-root cubic differentiated correctly on its own and gave `nan` as soon
+ as a one-real-root cubic shared the batch, and `solve_quartic` inherited it through its
+ resolvent cubic. The forward values are unchanged. (#4334, #4338)
* `Normalize`, `Denormalize` and `Rescale` register their constants (`mean`, `std`, `factor`) as
non-persistent buffers instead of plain attributes, so `.to(device)` moves them with the module.
diff --git a/kornia/geometry/solvers/polynomial_solver.py b/kornia/geometry/solvers/polynomial_solver.py
index 46aa7505d..f2160cb7b 100644
--- a/kornia/geometry/solvers/polynomial_solver.py
+++ b/kornia/geometry/solvers/polynomial_solver.py
@@ -214,7 +214,10 @@ def solve_cubic(coeffs: torch.Tensor) -> torch.Tensor:
AD = torch.zeros_like(R)
BD = torch.zeros_like(R)
R_abs = torch.abs(R)
- mask_R_positive = R_abs > 1e-16
+ # Intersect with mask_D_positive: sqrt(D) on a D <= 0 row is nan, and
+ # although such a row is never read out of AD/BD, `-Q / nan` stays in
+ # the graph and its backward poisons every coefficient's gradient.
+ mask_R_positive = (R_abs > 1e-16) & mask_D_positive
if torch.any(mask_R_positive):
AD[mask_R_positive] = torch.pow(R_abs[mask_R_positive] + torch.sqrt(D[mask_R_positive]), 1 / 3)
mask_R_positive_ = R < 0
diff --git a/testing/half_precision_xfails/cpu_float16.txt b/testing/half_precision_xfails/cpu_float16.txt
index 7538fccdc..ecaa4c23a 100644
--- a/testing/half_precision_xfails/cpu_float16.txt
+++ b/testing/half_precision_xfails/cpu_float16.txt
@@ -398,6 +398,7 @@ call builtins.AssertionError tests/geometry/liegroup/test_so3.py::TestSo3::test_
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]
diff --git a/tests/geometry/solvers/test_polynomial_solver.py b/tests/geometry/solvers/test_polynomial_solver.py
index 4ba06f8a0..75ee75749 100644
--- a/tests/geometry/solvers/test_polynomial_solver.py
+++ b/tests/geometry/solvers/test_polynomial_solver.py
@@ -124,6 +124,33 @@ class TestCubicSolver(BaseTester):
cubic_roots.sum().backward()
assert bool(torch.isfinite(cubic_coeffs.grad).all()), cubic_coeffs.grad
+ def test_convention_gradient_does_not_leak_across_batch_rows_4334(self, device, dtype):
+ # #4334: the D > 0 branch keyed its work off `abs(R) > 1e-16` alone, so it evaluated
+ # sqrt(D) on D < 0 rows too. Those rows are never read back, but `-Q / nan` stays in
+ # the graph and DivBackward0 returns nan, which reaches every coefficient. The result
+ # is that a row differentiates fine alone and gives nan in a mixed batch.
+ three = [1.0, -7.0, 14.0, -8.0] # (x-1)(x-2)(x-4): D < 0, three real roots, R != 0
+ one = [1.0, 0.0, 1.0, -2.0] # (x-1)(x^2+x+2): D > 0, one real root, Q != 0
+
+ alone = torch.tensor([three], device=device, dtype=dtype, requires_grad=True)
+ solver.solve_cubic(alone).sum().backward()
+
+ mixed = torch.tensor([three, one], device=device, dtype=dtype, requires_grad=True)
+ solver.solve_cubic(mixed).sum().backward()
+
+ assert bool(torch.isfinite(mixed.grad).all()), mixed.grad
+ # Batching must not change the answer either, not merely keep it finite.
+ self.assert_close(mixed.grad[0], alone.grad[0])
+
+ def test_convention_batched_forward_is_unchanged_by_neighbours_4334(self, device, dtype):
+ # The forward pass was always correct; pin that, so a later fix that repairs the
+ # gradient by perturbing the value is caught here.
+ three = [1.0, -7.0, 14.0, -8.0]
+ one = [1.0, 0.0, 1.0, -2.0]
+ alone = torch.tensor([three], device=device, dtype=dtype)
+ mixed = torch.tensor([three, one], device=device, dtype=dtype)
+ self.assert_close(solver.solve_cubic(mixed)[0], solver.solve_cubic(alone)[0])
+
class TestMultiplyDegOnePoly(BaseTester):
def test_smoke(self, device, dtype):
@@ -466,3 +493,20 @@ class TestQuarticSolver(BaseTester):
rtol=1e-4,
atol=1e-4,
)
+
+ def test_convention_gradient_does_not_leak_across_batch_rows_4334(self, device, dtype):
+ # #4334 through the resolvent cubic: a four-real-root quartic batched with a
+ # two-real-root one took nan gradients from solve_cubic's D > 0 branch.
+ four = [1.0, -10.0, 35.0, -50.0, 24.0] # (x-1)(x-2)(x-3)(x-4)
+ two = [1.0, 0.0, 0.0, 0.0, -16.0] # x^4 - 16
+
+ alone = torch.tensor([four], device=device, dtype=dtype, requires_grad=True)
+ solver.solve_quartic(alone).sum().backward()
+
+ mixed = torch.tensor([four, two], device=device, dtype=dtype, requires_grad=True)
+ solver.solve_quartic(mixed).sum().backward()
+
+ # Check row 0 for the cross-batch contamination from #4334. Row 1's separate
+ # zero-radicand gradient convention was fixed in #4339 and is covered above.
+ assert bool(torch.isfinite(mixed.grad[0]).all()), mixed.grad
+ self.assert_close(mixed.grad[0], alone.grad[0])