Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

fix(geometry): evaluate determinant_to_polynomial half inputs in float32 (#6565)

Dmytro Mishkin1510c8166dbe
diff --git a/changelog.d/6565.fixed.md b/changelog.d/6565.fixed.md
new file mode 100644
index 000000000..5aac65763
--- /dev/null
+++ b/changelog.d/6565.fixed.md
@@ -0,0 +1,4 @@
+`determinant_to_polynomial` now evaluates float16 and bfloat16 inputs in float32 and returns the input dtype. It used to
+sum the coefficients in the half dtype, so on CUDA and MPS two calls on the same input could return coefficients that
+differed far beyond the half dtype's rounding (0.21 in bfloat16 on CUDA, 0.75 on MPS). The float32 sum leaves only
+float32 roundoff, which can still change a coefficient by one half-precision step after the cast.
diff --git a/kornia/geometry/solvers/polynomial_solver.py b/kornia/geometry/solvers/polynomial_solver.py
index 24f4b5852..f145ed12a 100644
--- a/kornia/geometry/solvers/polynomial_solver.py
+++ b/kornia/geometry/solvers/polynomial_solver.py
@@ -2957,6 +2957,11 @@ def determinant_to_polynomial(
- Each row of ``A`` holds two cubics (columns 0 to 3 and 4 to 7) and a quartic (columns 8 to 12) in
``z``, highest degree first. The returned coefficients are lowest degree first (``cs[i]`` multiplies
``z**i``), the reverse of the :func:`solve_quadratic` layout.
+ - Half inputs are evaluated in float32 and the coefficients are returned in the input dtype. Each
+ coefficient sums 6 to 84 triple products; summed in float16 or bfloat16, the result depends on the
+ order of the additions, which CUDA's and MPS's ``scatter_add_`` do not fix. The float32 sum is
+ order-dependent only at float32 roundoff, which can still move a coefficient by one step of the
+ half dtype after the cast.
Args:
A: torch.Tensor ``(B, 3, 13)``.
@@ -2971,17 +2976,18 @@ def determinant_to_polynomial(
"""
B, device, dtype = A.shape[0], A.device, A.dtype
global multiplication_indices, signs, coefficient_map # noqa: PLW0603
+ compute_dtype = torch.float32 if dtype in (torch.float16, torch.bfloat16) else dtype
multiplication_indices = multiplication_indices.to(device)
- signs = signs.to(device, dtype)
+ signs = signs.to(device, compute_dtype)
coefficient_map = coefficient_map.to(device)
- A_flat = A.flatten(start_dim=1)
+ A_flat = A.flatten(start_dim=1).to(compute_dtype)
gathered_values = A_flat[:, multiplication_indices]
products = torch.prod(gathered_values, dim=-1)
signed_products = products * signs
- cs = torch.zeros(B, 11, device=device, dtype=dtype)
+ cs = torch.zeros(B, 11, device=device, dtype=compute_dtype)
batch_coefficient_map = coefficient_map.repeat(B, 1)
cs.scatter_add_(dim=1, index=batch_coefficient_map, src=signed_products)
- return cs
+ return cs.to(dtype)
diff --git a/tests/geometry/solvers/test_polynomial_solver.py b/tests/geometry/solvers/test_polynomial_solver.py
index 7d1e926f3..02fb95f8c 100644
--- a/tests/geometry/solvers/test_polynomial_solver.py
+++ b/tests/geometry/solvers/test_polynomial_solver.py
@@ -804,6 +804,24 @@ class TestDeterminantToPolynomial(BaseTester):
# Compare result with expected values
self.assert_close(result, expected, rtol=1e-5, atol=1e-5)
+ def test_half_products_cancel_in_float32(self, device, dtype):
+ """Two products of ``cs[:, 0]`` that cancel to ``2**-14`` keep the residual in every dtype.
+
+ ``A[0, 0, 3] * A[0, 1, 7] * A[0, 2, 12] = 1.0078125**2 = 1 + 2**-6 + 2**-14`` and
+ ``A[0, 0, 7] * A[0, 1, 3] * A[0, 2, 12] = 1.015625 = 1 + 2**-6`` enter ``cs[:, 0]`` with opposite signs. Rounded
+ to float16 or bfloat16, the first product equals the second and the coefficient is 0. In float32 the
+ difference is exact, and ``2**-14`` is representable in both half dtypes.
+ """
+ A = torch.zeros(1, 3, 13, device=device, dtype=dtype)
+ A[0, 0, 3] = A[0, 1, 7] = 1.0078125
+ A[0, 0, 7] = 1.015625
+ A[0, 1, 3] = A[0, 2, 12] = 1.0
+ expected = torch.zeros(1, 11, device=device, dtype=dtype)
+ expected[0, 0] = 2**-14
+ result = solver.determinant_to_polynomial(A)
+ assert result.dtype == dtype
+ self.assert_close(result, expected, rtol=0, atol=0)
+
class TestQuarticSolver(BaseTester):
@pytest.mark.parametrize(