π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
fix(geometry): scale solve_cubic rows by a power of two and avoid the A + B cancellation for a tiny leading coefficient (#5024)
εΊζ’η69dd6bd2ace6
diff --git a/changelog.d/5024.fixed.md b/changelog.d/5024.fixed.mdnew file mode 100644index 000000000..f6466ad67--- /dev/null+++ b/changelog.d/5024.fixed.md@@ -0,0 +1,8 @@+`solve_cubic` evaluates the closed form on each row scaled by an exact power of two to a unit root bound and scales+the roots back, takes Cardano's `A + B` as `2R / (A^2 + B^2 + Q)` when `Q > 0` and `A^2 < 4.79 Q`, and drops the+`|R| > 1e-16` floor that returned `-b/3` for `D > 0` rows with a small `R`, so a tiny leading coefficient keeps its+finite root in float32 and float64 and the #4833 literal solves (#4914). A row whose largest root exceeds 16 times+the scale of the other two keeps that root and gets the other two from Vieta's relations and `solve_quadratic`, so+`1e-8 x^3 + (x - 1)(x - 2)` returns all three roots instead of two values that are not roots. Outside that case,+`D <= 0` rows whose `Q^3` and `R^2` stayed within the dtype's range keep their bits, rows whose intermediates+overflowed or underflowed are now solved, and `D > 0` rows can move at rounding level.diff --git a/kornia/geometry/solvers/polynomial_solver.py b/kornia/geometry/solvers/polynomial_solver.pyindex 75891b20d..35b03faa9 100644--- a/kornia/geometry/solvers/polynomial_solver.py+++ b/kornia/geometry/solvers/polynomial_solver.py@@ -112,6 +112,27 @@ def solve_quadratic(coeffs: torch.Tensor) -> torch.Tensor:return torch.stack([root_0, root_1], dim=-1)+# Bit layout of the float dtypes solve_cubic scales in: the integer dtype of the same width, the exponent bias and the+# number of mantissa bits. A float with a zero mantissa is 2 ** (stored exponent - bias).+_FLOAT_LAYOUT = {torch.float32: (torch.int32, 127, 23), torch.float64: (torch.int64, 1023, 52)}++# A cubic root that is this many times larger than the other two is taken as dominant by solve_cubic, which then gets+# the other two from Vieta's relations instead of the closed form. See the comment there.+_DOMINANT_ROOT_RATIO = 2.0**4+++def _exact_power_of_two(exponent: torch.Tensor) -> torch.Tensor:+ """Return ``2 ** exponent`` for an integer-valued float tensor, exact on every backend.++ ``torch.exp2`` and ``torch.pow`` are not exact for integer arguments on every backend (MPS), and a scale that is+ not a power of two changes the bits of the scaled row. The exponent is clamped so that both ``2 ** exponent`` and+ ``2 ** -exponent`` are normal floats, and is written into the exponent field of the float.+ """+ int_dtype, bias, mantissa_bits = _FLOAT_LAYOUT[exponent.dtype]+ biased = exponent.clamp(1 - bias, bias - 1).to(int_dtype) + bias+ return (biased * 2**mantissa_bits).view(exponent.dtype)++def solve_cubic(coeffs: torch.Tensor) -> torch.Tensor:r"""Solve given cubic equation.@@ -124,6 +145,9 @@ def solve_cubic(coeffs: torch.Tensor) -> torch.Tensor:- Coefficient layout and zero padding as :func:`solve_quadratic`. Three real roots are returned unsorted,and a single real root is in slot 0.- A zero leading coefficient lowers the degree, and the roots of the remaining polynomial come first.+ - The closed form is evaluated on the row scaled by an exact power of two to a unit root bound, and the+ roots are scaled back, so its intermediates neither overflow nor underflow for a tiny leading coefficient+ or for roots far from unit scale (#4914).Args:coeffs : The coefficients cubic equation : `(B, 4)`@@ -207,11 +231,28 @@ def _solve_cubic_with_count(coeffs: torch.Tensor) -> tuple[torch.Tensor, torch.T# Normalized form x^3 + a2 * x^2 + a1 * x + a0 = 0inv_a = 1.0 / a[~mask_a_zero]b_a = inv_a * b[~mask_a_zero]- b_a2 = b_a * b_a-c_a = inv_a * c[~mask_a_zero]d_a = inv_a * d[~mask_a_zero]+ # Solve for y = x / s, with s the power of two just above max(|b/a|, |c/a|^(1/2), |d/a|^(1/3)), which bounds the+ # root magnitude. The scaled coefficients b/(a s), c/(a s^2) and d/(a s^3) are below 1 in magnitude, so Q^3 and+ # R^2 below neither overflow when a tiny leading coefficient makes b/a, c/a and d/a huge (#4914) nor underflow for+ # tiny roots. Multiplying by a power of two is exact, so a row that neither overflowed nor underflowed takes the+ # same branch as before and its D <= 0 roots are the same bits. s is a step function of the coefficients, so it is+ # a constant for autograd. A row with b == c == d == 0 has bound 0 and keeps s = 1.+ bound = torch.maximum(torch.maximum(b_a.abs(), c_a.abs().sqrt()), d_a.abs().pow(1.0 / 3.0)).detach()+ positive_bound = bound > 0+ exponent = torch.floor(torch.log2(torch.where(positive_bound, bound, torch.ones_like(bound)))) + 1+ exponent = torch.where(positive_bound, exponent, torch.zeros_like(exponent))+ s = _exact_power_of_two(exponent)+ inv_s = _exact_power_of_two(-exponent)+ b_a = b_a * inv_s+ c_a = c_a * inv_s * inv_s+ d_a = d_a * inv_s * inv_s * inv_s+ b_a2 = b_a * b_a+ scale = torch.ones_like(a)+ scale[~mask_a_zero] = s+# Solve the cubic equationQ = (3 * c_a - b_a2) / 9R = (9 * b_a * c_a - 27 * d_a - 2 * b_a * b_a2) / 54@@ -282,26 +323,80 @@ def _solve_cubic_with_count(coeffs: torch.Tensor) -> tuple[torch.Tensor, torch.Tmask_D_positive_solution = (a_D_positive > 0) & (a_Q_zero != 0)mask_D_positive = (D > 0) & (Q != 0)if torch.any(mask_D_positive):- AD = torch.zeros_like(R)- BD = torch.zeros_like(R)- R_abs = torch.abs(R)- # 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-- if torch.any(mask_R_positive_):- AD[mask_R_positive_] = -AD[mask_R_positive_]-- BD[mask_R_positive] = -Q[mask_R_positive] / AD[mask_R_positive]- x0_D_positive = AD[mask_D_positive] + BD[mask_D_positive] - b_a_3[mask_D_positive]+ # Cardano: the real root is A + B with A = cbrt(R + sqrt(D)) and B = cbrt(R - sqrt(D)) = -Q / A. Take the cube+ # root of the larger magnitude, |R| + sqrt(D), and restore the sign of R, so A is never 0 and no floor on |R|+ # is needed. Only the mask_D_positive rows enter: sqrt(D) on a D <= 0 row is nan, and although such a row+ # would never be read out, `-Q / nan` would stay in the graph and its backward poison every coefficient's+ # gradient.+ Q_pos, R_pos, D_pos = Q[mask_D_positive], R[mask_D_positive], D[mask_D_positive]+ AD = torch.pow(R_pos.abs() + torch.sqrt(D_pos), 1 / 3)+ AD = torch.where(R_pos < 0, -AD, AD)+ BD = -Q_pos / AD+ # When Q > 0, A and B have opposite signs and A + B cancels once the root is small next to sqrt(Q), the case+ # of a tiny leading coefficient (#4914): the finite root of 1e-30 x^3 + 2 x - 6 came out as 0 in float64.+ # A^3 + B^3 = 2 R and A B = -Q, so A + B = 2 R / (A^2 - A B + B^2) = 2 R / (A^2 + B^2 + Q), a quotient of+ # same-sign sums when Q > 0. When Q < 0, A and B have the same sign, A + B does not cancel and stays the more+ # accurate form. With t = A^2 / Q >= 1, a relative rounding error in A moves A + B by (t + 1) / (t - 1) times+ # as much and the quotient by 2 (t^2 - 1) / (t^2 + t + 1) times as much; the two are equal at+ # t = (5 + sqrt(21)) / 2 = 4.79, so the quotient is only taken below that, where A + B cancels, and A + B is+ # kept where |R| >> Q^(3/2) and the quotient would be up to twice as sensitive.+ quotient_is_better = (Q_pos > 0) & (AD * AD < 4.79 * Q_pos)+ sum_AB = torch.where(quotient_is_better, 2 * R_pos / (AD * AD + BD * BD + Q_pos), AD + BD)+ x0_D_positive = sum_AB - b_a_3[mask_D_positive]solutions[mask_D_positive_solution, 0] = x0_D_positivenum_real[mask_D_positive_solution] = 1- return solutions, num_real+ roots = solutions * scale[:, None]++ # A root that dominates the other two, the case of a tiny leading coefficient with b != 0 (#4914: the row is+ # y^3 + b' y^2 + tiny y + tinier after scaling), makes D = Q^3 + R^2 a difference of nearly equal numbers, so the+ # branch is chosen by rounding: the D > 0 branch then drops two real roots, and the trigonometric branch returns+ # the two small roots as differences of numbers of size |b'| / 3, which are not roots at all. Both branches get+ # the dominant root x0 right. Keep it and take the other two from Vieta's relations, x1 x2 = -d / (a x0) and+ # x1 + x2 = (c + d / x0) / (a x0), which are well conditioned when |x0| dominates (a x0 is then about -b), and+ # let the stable quadratic decide whether they are real. They are formed in the original scale, where the two+ # small roots are ordinary numbers; in the scaled row they can be below the dtype's normal range. Only a row+ # whose largest root exceeds _DOMINANT_ROOT_RATIO times the scale of the other two enters, so every other row+ # keeps its bits. The gate is decided on detached values: a rejected row can overflow these quotients, and a lane+ # that autograd differentiates must not. The dominant root keeps its slot and the other two take the remaining+ # slots in the order closest to the closed-form values they replace, so a row the closed form got right keeps its+ # slot order; a complex pair puts the single real root in slot 0 as everywhere else.+ mask_cubic = ~mask_a_zero+ if torch.any(mask_cubic):+ x = roots[mask_cubic]+ slot0 = x.abs().argmax(dim=1, keepdim=True)+ x0 = x.gather(1, slot0).squeeze(1)+ a_cubic, c_cubic, d_cubic = a[mask_cubic], c[mask_cubic], d[mask_cubic]+ x0_detached = x0.detach()+ safe_x0 = torch.where(x0_detached == 0, torch.ones_like(x0_detached), x0_detached)+ lead = a_cubic.detach() * safe_x0+ product = -d_cubic.detach() / lead+ total = (c_cubic.detach() + d_cubic.detach() / safe_x0) / lead+ other_scale = torch.maximum(total.abs(), product.abs().sqrt())+ mask_dominant = (x0_detached != 0) & (x0_detached.abs() > _DOMINANT_ROOT_RATIO * other_scale)+ if torch.any(mask_dominant):+ x0_dominant = x0[mask_dominant]+ lead = a_cubic[mask_dominant] * x0_dominant+ product = -d_cubic[mask_dominant] / lead+ total = (c_cubic[mask_dominant] + d_cubic[mask_dominant] / x0_dominant) / lead+ others = solve_quadratic(torch.stack([torch.ones_like(total), -total, product], dim=1))+ pair_is_real = total * total - 4 * product >= 0+ previous = x[mask_dominant]+ slot0_dominant = slot0[mask_dominant]+ rest = torch.sort(torch.cat([(slot0_dominant + 1) % 3, (slot0_dominant + 2) % 3], dim=1), dim=1).values+ previous_rest = previous.gather(1, rest)+ swap = (previous_rest - others.flip(1)).abs().sum(1) < (previous_rest - others).abs().sum(1)+ others = torch.where(swap[:, None], others.flip(1), others)+ in_place = torch.zeros_like(previous)+ in_place.scatter_(1, slot0_dominant, x0_dominant[:, None])+ in_place.scatter_(1, rest, others)+ alone = torch.stack([x0_dominant, torch.zeros_like(x0_dominant), torch.zeros_like(x0_dominant)], dim=1)+ mask_dominant_rows = torch.zeros_like(mask_a_zero)+ mask_dominant_rows[mask_cubic] = mask_dominant+ roots[mask_dominant_rows] = torch.where(pair_is_real[:, None], in_place, alone)+ num_real[mask_dominant_rows] = torch.where(pair_is_real, 3, 1)++ return roots, num_realdef _solve_cubic_real(coeffs: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor]:diff --git a/tests/geometry/solvers/test_polynomial_solver.py b/tests/geometry/solvers/test_polynomial_solver.pyindex 0a3b76462..e32cfa93a 100644--- a/tests/geometry/solvers/test_polynomial_solver.py+++ b/tests/geometry/solvers/test_polynomial_solver.py@@ -21,7 +21,7 @@ import torchimport kornia.geometry.solvers as solverfrom kornia.core.exceptions import ShapeError-from kornia.geometry.solvers.polynomial_solver import _solve_cubic_real, _solve_cubic_with_count+from kornia.geometry.solvers.polynomial_solver import _exact_power_of_two, _solve_cubic_real, _solve_cubic_with_countfrom testing.base import BaseTester@@ -266,6 +266,151 @@ class TestCubicSolver(BaseTester):self.assert_close(roots, solver.solve_cubic(coeffs), rtol=0.0, atol=0.0)assert num_real.tolist() == [3, 1, 1, 3, 3, 2, 2, 0, 1, 0]+ def test_tiny_leading_coefficient_4914(self, device, dtype):+ if dtype == torch.float16:+ pytest.skip("1e-30 rounds to 0 in float16, which solves the row as the linear equation 2x - 6 = 0")+ # #4914: 1e-30 x^3 + 2x - 6 has the real root 3 (the other two are +-1.4e15 i). Normalising by a gave+ # c/a = 2e30 and d/a = -6e30, whose Q^3 overflowed float32 (root inf), and in float64 Cardano's A + B+ # cancelled to 0 (root 0). The row is now solved scaled by 2^-51, and A + B as 2R / (A^2 + B^2 + Q).+ coeffs = torch.tensor([[1e-30, 0.0, 2.0, -6.0]], device=device, dtype=dtype)+ roots = solver.solve_cubic(coeffs)+ expected = torch.tensor([[3.0, 0.0, 0.0]], device=device, dtype=dtype)+ self.assert_close(roots, expected, rtol=8 * torch.finfo(dtype).eps, atol=0.0)++ def test_tiny_leading_coefficient_gradient_4914(self, device, dtype):+ if dtype not in (torch.float32, torch.float64):+ pytest.skip("Gradient values are checked in float32 and float64.")+ # Implicit-function derivative of the simple root r: dr/dcoeffs[k] = -r^(3 - k) / p'(r), p'(3) = 2 here.+ # The root moves by 27a/2 with a and by 9b/2 with b, below the resolution of the closed form at a = 1e-30,+ # so those two derivatives cannot come out of it (inf in float32); the c and d derivatives do.+ x = torch.tensor([[1e-30, 0.0, 2.0, -6.0]], device=device, dtype=dtype, requires_grad=True)+ (grad,) = torch.autograd.grad(solver.solve_cubic(x)[0, 0], x)+ self.assert_close(grad[0, 2:], torch.tensor([-1.5, -0.5], device=device, dtype=dtype), rtol=1e-5, atol=0.0)++ # The root bound takes |d|^(1/3), whose derivative is infinite at d == 0. The bound is a step function of+ # the coefficients and is detached: the root 0 of x^3 + x^2 + x keeps its derivative -1 / p'(0) in d.+ x = torch.tensor([[1.0, 1.0, 1.0, 0.0]], device=device, dtype=dtype, requires_grad=True)+ (grad,) = torch.autograd.grad(solver.solve_cubic(x)[0, 0], x)+ self.assert_close(grad, torch.tensor([[0.0, 0.0, 0.0, -1.0]], device=device, dtype=dtype), rtol=0.0, atol=1e-6)++ # 2x^3 has the root bound 0 and is not scaled. Its triple root 0 keeps the Q == R == 0 branch's gradient,+ # -b / (3a) per root, so the sum of the roots moves by -1 / a with b.+ x = torch.tensor([[2.0, 0.0, 0.0, 0.0]], device=device, dtype=dtype, requires_grad=True)+ roots = solver.solve_cubic(x)+ self.assert_close(roots.detach(), torch.zeros(1, 3, device=device, dtype=dtype), rtol=0.0, atol=0.0)+ (grad,) = torch.autograd.grad(roots.sum(), x)+ self.assert_close(grad, torch.tensor([[0.0, -0.5, 0.0, 0.0]], device=device, dtype=dtype), rtol=0.0, atol=0.0)++ def test_scaled_row_has_scaled_roots_4914(self, device, dtype):+ if dtype not in (torch.float32, torch.float64):+ pytest.skip("Half-precision rows are solved in float32, and 2^40 is beyond float16.")+ # The row scale has to be an exact power of two on every backend: torch.exp2 is not, for integer arguments+ # on MPS, and the triple root below then left its Q == R == 0 branch.+ exponents = torch.tensor([-120.0, -38.0, 0.0, 2.0, 120.0], device=device, dtype=dtype)+ expected = torch.tensor([2.0**-120, 2.0**-38, 1.0, 4.0, 2.0**120], device=device, dtype=dtype)+ assert torch.equal(_exact_power_of_two(exponents), expected), _exact_power_of_two(exponents)++ # Coefficient i divided by s^i moves every root by 1 / s. With s an exact power of two the scaled row reaches+ # the closed form as the same numbers, so its roots are the original ones times 1 / s. One row per branch:+ # three real roots, one real root with Q > 0 and with Q < 0, Q == 0, and a triple root. Before the fix,+ # Q^3 left the dtype's range at these s and the rows returned zeros, inf or a wrong branch.+ rows = torch.tensor(+ [+ [1.0, -6.0, 11.0, -6.0], # (x - 1)(x - 2)(x - 3)+ [1.0, 0.0, 1.0, -2.0], # (x - 1)(x^2 + x + 2): Q > 0+ [1.0, 3.0, 1.0, -5.0], # (x - 1)(x^2 + 4x + 5): Q < 0+ [1.0, 0.0, 0.0, 1.0], # x^3 + 1: Q == 0+ [1.0, -3.0, 3.0, -1.0], # (x - 1)^3+ ],+ device=device,+ dtype=dtype,+ )+ base = solver.solve_cubic(rows)+ exponent = 40 if dtype == torch.float32 else 200+ for s in (2.0**exponent, 2.0**-exponent):+ # Python computes the powers of two exactly, and multiplying by them is exact on every backend, where+ # `s ** torch.arange(4)` and a division are not (MPS).+ powers = torch.tensor([1.0, 1.0 / s, 1.0 / s**2, 1.0 / s**3], device=device, dtype=dtype)+ self.assert_close(solver.solve_cubic(rows * powers) * s, base, rtol=8 * torch.finfo(dtype).eps, atol=0.0)++ def test_small_r_keeps_the_root_4914(self, device, dtype):+ if dtype not in (torch.float32, torch.float64):+ pytest.skip("2e-17 rounds to 0 in float16, and bfloat16 keeps 3 digits of these rows.")+ # The D > 0 branch took A = B = 0 for |R| <= 1e-16 and returned -b / 3 for the root. x^3 + x - 2e-17 has+ # R = 1e-17 and the root 2e-17, not 0. The second row is the resolvent cubic of the #4833 quartic+ # x^4 - 0.009x^3 + 3e-05x^2 - 4.2e-08x + 2e-11: its R is 2e-18 and its real root 1.2e-5, which came back+ # as -b / 3 = 1e-5 and lost the quartic's roots 1e-3 and 2e-3.+ rows = torch.tensor([[1.0, 0.0, 1.0, -2e-17], [1.0, -3e-05, 2.98e-10, -9.84e-16]], device=device, dtype=dtype)+ roots = solver.solve_cubic(rows)+ expected = torch.tensor([[2e-17, 0.0, 0.0], [1.2e-5, 0.0, 0.0]], device=device, dtype=dtype)+ tol = 1e-5 if dtype == torch.float32 else 1e-12+ self.assert_close(roots, expected, rtol=tol, atol=0.0)++ def test_root_bound_takes_every_coefficient_4914(self, device, dtype):+ if dtype not in (torch.float32, torch.float64):+ pytest.skip("These rows are beyond the range of float16, and half-precision rows are solved in float32.")+ # Each row's root bound is set by one coefficient: b (x^3 + b x^2 = x^2 (x + b)), c (the root -d / c of+ # x^3 + c x + d with c huge) and b at the top of the dtype's range, where the scale exponent has to be+ # clamped. Scaled without that coefficient's term in the bound, or with an unclamped exponent, Q^3 and R^2+ # overflow or the scale is not a finite power of two, and the root comes back as 0 or nan.+ if dtype == torch.float32:+ rows = [[1.0, 1e20, 0.0, 0.0], [1.0, 0.0, 1e30, 1e20], [1.0, 1e38, 0.0, 0.0]]+ expected = [[-1e20, 0.0, 0.0], [-1e-10, 0.0, 0.0], [-1e38, 0.0, 0.0]]+ else:+ rows = [[1.0, 1e160, 0.0, 0.0], [1.0, 0.0, 1e200, 1.0], [1.0, 1e308, 0.0, 0.0]]+ expected = [[-1e160, 0.0, 0.0], [-1e-200, 0.0, 0.0], [-1e308, 0.0, 0.0]]+ roots = solver.solve_cubic(torch.tensor(rows, device=device, dtype=dtype))+ expected = torch.tensor(expected, device=device, dtype=dtype)+ self.assert_close(roots.sort(dim=-1).values, expected, rtol=8 * torch.finfo(dtype).eps, atol=0.0)++ def test_dominant_root_keeps_the_other_two_4914(self, device, dtype):+ if dtype not in (torch.float32, torch.float64):+ pytest.skip("1e-30 rounds to 0 in float16, and half-precision rows are solved in float32.")+ # #4914: with b != 0, a tiny a puts a root near -b / a in front of the quadratic b x^2 + c x + d. The scaled+ # row's D = Q^3 + R^2 is then a difference of nearly equal numbers, and the closed form either dropped the two+ # small real roots or returned values that are not roots in their slots (6.65e3 and -6.64e3 for a = 1e-8 in+ # float32). The dominant root stays and the other two come from Vieta's relations and the stable quadratic,+ # whose discriminant tells the real pair 1 + a + O(a^2), 2 - 8a + O(a^2) from the complex pair of x^2 + x + 1.+ tol = 1e-6 if dtype == torch.float32 else 1e-13+ for a in (1e-8, 1e-30):+ rows = torch.tensor([[a, 1.0, -3.0, 2.0], [a, 1.0, 1.0, 1.0]], device=device, dtype=dtype)+ expected = torch.tensor(+ [[-1 / a - 3, 1 + a, 2 - 8 * a], [-1 / a + 1, 0.0, 0.0]], device=device, dtype=dtype+ )+ roots, num_real = _solve_cubic_with_count(rows)+ self.assert_close(roots[:1].sort(dim=-1).values, expected[:1].sort(dim=-1).values, rtol=tol, atol=0.0)+ # Unsorted: the single real root goes to slot 0 and the count marks slots 1 and 2 as padding. The closed+ # form had put -1 / a in slot 1 here (float32 at a = 1e-8, float64 at a = 1e-30).+ self.assert_close(roots[1:], expected[1:], rtol=tol, atol=0.0)+ assert num_real.tolist() == [3, 1], num_real++ def test_dominant_root_over_a_double_zero_root_4914(self, device, dtype):+ if dtype not in (torch.float32, torch.float64):+ pytest.skip("1e-30 rounds to 0 in float16, and half-precision rows are solved in float32.")+ # x^2 (x + b / a): Vieta gives the pair total = product = 0, a zero discriminant, so the double root 0 is real+ # and counts twice, as solve_quadratic's delta == 0 double root and the D == 0 row of #4862 do.+ rows = torch.tensor([[1.0, 1.0, 0.0, 0.0], [1e-30, 1.0, 0.0, 0.0]], device=device, dtype=dtype)+ expected = torch.tensor([[-1.0, 0.0, 0.0], [-1e30, 0.0, 0.0]], device=device, dtype=dtype)+ roots, num_real = _solve_cubic_with_count(rows)+ self.assert_close(roots.sort(dim=-1).values, expected, rtol=8 * torch.finfo(dtype).eps, atol=0.0)+ assert num_real.tolist() == [3, 3], num_real++ def test_dominant_root_gradcheck_4914(self, device):+ # Vieta rows: (x - 1)(x - 2)(x + 1000), (x + 1000)(x^2 + x + 1) and (x - 32)(x - 1)(x + 1). The first and the+ # last were right before and keep the closed form's slot order; the complex pair puts its root in slot 0.+ rows = torch.tensor(+ [[1.0, 997.0, -2998.0, 2000.0], [1.0, 1001.0, 1001.0, 1000.0], [1.0, -32.0, -1.0, 32.0]],+ device=device,+ dtype=torch.float64,+ )+ expected = torch.tensor(+ [[2.0, -1000.0, 1.0], [-1000.0, 0.0, 0.0], [32.0, -1.0, 1.0]], device=device, dtype=torch.float64+ )+ roots, num_real = _solve_cubic_with_count(rows)+ self.assert_close(roots, expected, rtol=1e-13, atol=0.0)+ assert num_real.tolist() == [3, 1, 3], num_real+ self.gradcheck(solver.solve_cubic, (rows.requires_grad_(),))+class TestMultiplyDegOnePoly(BaseTester):def test_smoke(self, device, dtype):@@ -1250,15 +1395,16 @@ class TestConventionPolynomialSolvers(BaseTester):expected = torch.tensor([[*lead, b, -1.0, 0.0]], device=device, dtype=dtype)self.assert_close(grad, expected)- def test_wart_solve_quartic_small_scale_4833(self, device, dtype):+ def test_small_scale_quartic_literal_4833(self, device, dtype):if dtype in (torch.float16, torch.bfloat16):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, but the solver is not scale-invariant and returns neither to 1 %.+ # 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.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-2 * root+ assert (out - root).abs().min() <= 1e-5 * root, outdef test_wart_solve_quartic_scaled_large_roots_fall_back_to_cubic_4954(self, device, dtype):if dtype != torch.float32: