π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
fix(solvers): guard solve_quartic's sqrt gradients at a zero radicand (#4339)
Dipak Chaudhari78432080d365
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex b6926dcb3..375c953f0 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -366,6 +366,13 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0* Fixed `unproject_points_z1` depth shape handling for singleton and multi-axis batches,accepting both trailing-singleton and flat depth tensors. (#4355)+* `solve_quartic` returns finite gradients for a pure biquadratic such as `x^4 - 16`. Its two+ `torch.clamp(..., min=0.0).sqrt()` sites do not guard the gradient they look like they guard:+ `d(sqrt)/dx` is unbounded at 0, and on torch below 2.14 `clamp` passes the incoming gradient+ through at the bound rather than zeroing it, so on the older half of kornia's supported torch+ range the backward returned `inf` and then `nan` (#4229). Both sites now substitute a safe+ radicand under the `sqrt`, as `solve_quadratic` in the same module already did. Forward values+ are unchanged. (#4339)* `RenderingDeFMO` (used by `DeFMO`) no longer crashes on a half-precision forward pass. Its renderingtime-steps (`times`) were a plain Python attribute, not a registered buffer, so `nn.Module.to()` neverdiff --git a/kornia/geometry/solvers/polynomial_solver.py b/kornia/geometry/solvers/polynomial_solver.pyindex 3a594f8be..46aa7505d 100644--- a/kornia/geometry/solvers/polynomial_solver.py+++ b/kornia/geometry/solvers/polynomial_solver.py@@ -256,6 +256,13 @@ def solve_quartic(coeffs: torch.Tensor) -> torch.Tensor:For a repeated (or near-repeated) real root, the resolvent-cubic solve internallydelegates to :func:`solve_cubic`'s finite-but-surrogate boundary-gradient convention;see that function's docstring for details.++ .. 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."""KORNIA_CHECK_SHAPE(coeffs, ["B", "5"])@@ -305,7 +312,18 @@ def solve_quartic(coeffs: torch.Tensor) -> torch.Tensor:y = torch.gather(y_roots, -1, best_idx).squeeze(-1)R_sq = torch.gather(R_sq_candidates, -1, best_idx).squeeze(-1)- R = torch.sqrt(torch.clamp(R_sq, min=0.0))+ # `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 (#4229), so+ # R_sq == 0 -- a biquadratic such as x^4 - 16 -- gave inf and then nan. Substitute a safe+ # radicand instead, as solve_quadratic above already does, so sqrt is never differentiated at 0.+ # On torch >= 2.14 clamp already zeroes the boundary gradient, so the pins for this guard pass+ # on base there too; the 2.5.1 and 2.9.1 CI legs are the ones that discriminate.+ mask_R_sq_positive = R_sq > 0+ R = torch.where(+ mask_R_sq_positive,+ torch.sqrt(torch.where(mask_R_sq_positive, R_sq, torch.ones_like(R_sq))),+ torch.zeros_like(R_sq),+ )# Compute E termmask_R_small = torch.abs(R) < zero_tol@@ -320,7 +338,15 @@ def solve_quartic(coeffs: torch.Tensor) -> torch.Tensor:# Fallback for R approx 0if torch.any(mask_R_small):radicand = 0.25 * y[mask_R_small] * y[mask_R_small] - D[mask_R_small]- E[mask_R_small] = torch.sqrt(torch.clamp(radicand, min=0.0))+ # 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),+ )# Solve two resulting quadratic equations# Quad 1: x^2 + (A/2 - R)x + (y/2 - E) = 0diff --git a/testing/half_precision_xfails/cpu_float16.txt b/testing/half_precision_xfails/cpu_float16.txtindex fb83ed3d3..7538fccdc 100644--- a/testing/half_precision_xfails/cpu_float16.txt+++ b/testing/half_precision_xfails/cpu_float16.txt@@ -395,6 +395,9 @@ 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_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.pyindex 61a3752c9..4ba06f8a0 100644--- a/tests/geometry/solvers/test_polynomial_solver.py+++ b/tests/geometry/solvers/test_polynomial_solver.py@@ -410,3 +410,59 @@ class TestQuarticSolver(BaseTester):requires_grad=True,)self.gradcheck(solver.solve_quartic, (coeffs,), raise_exception=True, fast_mode=True)++ @pytest.mark.parametrize(+ ("coeffs", "expected", "expected_grad"),+ [+ # x^4 - 16 = (x^2-4)(x^2+4): two real roots, +-2. R_sq lands exactly on 0.+ ([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.+ ([1.0, 0.0, 5.0, 0.0, 4.0], None, [0.0, 0.0, 0.0, 0.0, 0.0]),+ ],+ )+ def test_convention_gradient_is_finite_for_a_pure_biquadratic_4229(+ self, coeffs, expected, expected_grad, device, dtype+ ):+ # A quartic with no x^3 and no x^2 term puts R_sq exactly on 0, and+ # `torch.clamp(R_sq, min=0.0).sqrt()` does not guard that: d(sqrt)/dx is unbounded at 0,+ # and on torch < 2.14 clamp passes the incoming gradient through at the bound rather+ # than zeroing it (#4229). kornia supports torch>=2.5.1, so the guard was a no-op on the+ # older half of the supported range and the backward returned nan. On torch >= 2.14 clamp+ # already zeroes the boundary gradient, so these pins pass on base on those legs; the+ # 2.5.1 and 2.9.1 CI legs carry the discrimination.+ c = torch.tensor([coeffs], device=device, dtype=dtype, requires_grad=True)+ roots = solver.solve_quartic(c)+ roots.sum().backward()++ 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.+ self.assert_close(+ c.grad[0],+ torch.tensor(expected_grad, device=device, dtype=dtype),+ rtol=1e-4,+ atol=1e-4,+ )+ # The forward pass was always correct; pin it, so a fix that repairs the gradient by+ # moving the value is caught here.+ if expected is None:+ # No real roots: every entry is the zero placeholder.+ self.assert_close(+ roots.detach()[0],+ torch.zeros(4, device=device, dtype=dtype),+ rtol=1e-4,+ atol=1e-4,+ )+ else:+ real = torch.sort(roots.detach()[0][:2]).values+ self.assert_close(+ real,+ torch.sort(torch.tensor(expected, device=device, dtype=dtype)).values,+ rtol=1e-4,+ atol=1e-4,+ )