π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
fix(geometry): keep the polynomial solver's tables out of each call's device and dtype (#6588)
Dmytro Mishkin3aa458b07cc2
diff --git a/changelog.d/6588.fixed.md b/changelog.d/6588.fixed.mdnew file mode 100644index 000000000..c43928605--- /dev/null+++ b/changelog.d/6588.fixed.md@@ -0,0 +1 @@+`determinant_to_polynomial`, `multiply_deg_one_poly` and `multiply_deg_two_one_poly` no longer rebind their module-level tables to the device and dtype of each call. On torch 2.14, after an MPS float32 call the next CPU float64 call converted the tables to garbage and stored them back, so every later call in the process returned NaN or wrong values on every device.diff --git a/kornia/geometry/solvers/polynomial_solver.py b/kornia/geometry/solvers/polynomial_solver.pyindex f145ed12a..cd79e8928 100644--- a/kornia/geometry/solvers/polynomial_solver.py+++ b/kornia/geometry/solvers/polynomial_solver.py@@ -1389,10 +1389,7 @@ def multiply_deg_one_poly(a: torch.Tensor, b: torch.Tensor) -> torch.Tensor:"""KORNIA_CHECK_SHAPE(a, ["B", "4"], "a must have shape (B, 4).")KORNIA_CHECK_SHAPE(b, ["B", "4"], "b must have shape (B, 4).")- global T_deg1 # noqa: PLW0603- if T_deg1.device != a.device or T_deg1.dtype != a.dtype:- T_deg1 = T_deg1.to(device=a.device, dtype=a.dtype)- return (a.unsqueeze(2) * b.unsqueeze(1)).flatten(start_dim=-2) @ T_deg1+ return (a.unsqueeze(2) * b.unsqueeze(1)).flatten(start_dim=-2) @ T_deg1.to(a.device, a.dtype)# Reference@@ -1468,12 +1465,9 @@ def multiply_deg_two_one_poly(a: torch.Tensor, b: torch.Tensor) -> torch.Tensor:"""KORNIA_CHECK_SHAPE(a, ["B", "10"], "a must have shape (B, 10).")KORNIA_CHECK_SHAPE(b, ["B", "4"], "b must have shape (B, 4).")- global T_deg2 # noqa: PLW0603- if T_deg2.device != a.device or T_deg2.dtype != a.dtype:- T_deg2 = T_deg2.to(device=a.device, dtype=a.dtype)product_basis = a.unsqueeze(2) * b.unsqueeze(1)product_vector = product_basis.flatten(start_dim=-2)- return product_vector @ T_deg2+ return product_vector @ T_deg2.to(a.device, a.dtype)# Compute degree 10 poly representing determinant (equation 14 in the paper)@@ -2975,19 +2969,14 @@ def determinant_to_polynomial("""B, device, dtype = A.shape[0], A.device, A.dtype- global multiplication_indices, signs, coefficient_map # noqa: PLW0603compute_dtype = torch.float32 if dtype in (torch.float16, torch.bfloat16) else dtype- multiplication_indices = multiplication_indices.to(device)- signs = signs.to(device, compute_dtype)- coefficient_map = coefficient_map.to(device)-A_flat = A.flatten(start_dim=1).to(compute_dtype)- gathered_values = A_flat[:, multiplication_indices]+ gathered_values = A_flat[:, multiplication_indices.to(device)]products = torch.prod(gathered_values, dim=-1)- signed_products = products * signs+ signed_products = products * signs.to(device, compute_dtype)cs = torch.zeros(B, 11, device=device, dtype=compute_dtype)- batch_coefficient_map = coefficient_map.repeat(B, 1)+ batch_coefficient_map = coefficient_map.to(device).repeat(B, 1)cs.scatter_add_(dim=1, index=batch_coefficient_map, src=signed_products)return cs.to(dtype)diff --git a/tests/geometry/solvers/test_polynomial_solver.py b/tests/geometry/solvers/test_polynomial_solver.pyindex 02fb95f8c..561c9ec18 100644--- a/tests/geometry/solvers/test_polynomial_solver.py+++ b/tests/geometry/solvers/test_polynomial_solver.py@@ -21,6 +21,7 @@ import torchimport kornia.geometry.solvers as solverfrom kornia.core.exceptions import ShapeError+from kornia.geometry.solvers import polynomial_solverfrom kornia.geometry.solvers.polynomial_solver import _exact_power_of_two, _solve_cubic_real, _solve_cubic_with_countfrom testing.base import BaseTester@@ -822,6 +823,56 @@ class TestDeterminantToPolynomial(BaseTester):assert result.dtype == dtypeself.assert_close(result, expected, rtol=0, atol=0)+ def test_a_call_leaves_later_cpu_float64_calls_unchanged_6571(self, device, dtype):+ """A call on any device and dtype does not change the result of a later CPU float64 call."""+ A = torch.zeros(1, 3, 13).index_put(+ (torch.tensor([0, 0, 0]), torch.tensor([0, 1, 2]), torch.tensor([0, 4, 8])), torch.tensor([2.0, 3.0, 5.0])+ )+ expected = torch.zeros(1, 11, dtype=torch.float64).index_put(+ (torch.tensor([0]), torch.tensor([10])), torch.tensor([30.0], dtype=torch.float64)+ )+ solver.determinant_to_polynomial(A.to(device, dtype))+ self.assert_close(solver.determinant_to_polynomial(A.double()), expected)+++ "name, call",+ [+ ("multiplication_indices", lambda x: solver.determinant_to_polynomial(x.expand(1, 3, 13))),+ ("signs", lambda x: solver.determinant_to_polynomial(x.expand(1, 3, 13))),+ ("coefficient_map", lambda x: solver.determinant_to_polynomial(x.expand(1, 3, 13))),+ ("T_deg1", lambda x: solver.multiply_deg_one_poly(x.expand(1, 4), x.expand(1, 4))),+ ("T_deg2", lambda x: solver.multiply_deg_two_one_poly(x.expand(1, 10), x.expand(1, 4))),+ ],+)+def test_module_tables_are_not_rebound_by_a_call_6571(name, call, device, dtype):+ """A call's result depends only on its input, so a call must leave the module's lookup tables alone."""+ before = getattr(polynomial_solver, name)+ # The dtypes differ so that a table following its caller moves in at least one of the two calls.+ for call_dtype in (dtype, torch.float32 if dtype == torch.float64 else torch.float64):+ if device.type == "mps" and call_dtype == torch.float64:+ continue+ call(torch.ones(1, device=device, dtype=call_dtype))+ assert getattr(polynomial_solver, name) is before+++ "call, shapes",+ [+ (solver.multiply_deg_one_poly, ((1, 4), (1, 4))),+ (solver.multiply_deg_two_one_poly, ((1, 10), (1, 4))),+ ],+)+def test_multiply_poly_after_a_call_elsewhere_matches_a_fresh_call_6571(call, shapes, device, dtype):+ """The polynomial products share the determinant's table handling: an earlier call does not change a later one."""+ a, b = (torch.arange(1.0, shape[-1] + 1, dtype=torch.float64).view(shape) for shape in shapes)+ expected = call(a, b).clone()+ call(a.to(device, dtype), b.to(device, dtype))+ actual = call(a, b)+ assert actual.device.type == "cpu"+ assert actual.dtype == torch.float64+ assert torch.equal(actual, expected)+class TestQuarticSolver(BaseTester):@pytest.mark.parametrize(