Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

fix(epipolar): give a zero leading coefficient the identity fallback (#4888)

Leonardo Vanni2e94cb71a59f
diff --git a/changelog.d/4888.breaking.md b/changelog.d/4888.breaking.md
new file mode 100644
index 000000000..e0f3c51a0
--- /dev/null
+++ b/changelog.d/4888.breaking.md
@@ -0,0 +1,8 @@
+`find_essential` and `run_5point` now return the identity fallback for a sample whose degree-10
+polynomial has an exactly zero leading coefficient, which data with no parallax, such as the same
+points in both images, gives for about half of all samples. Such a polynomial has a lower degree.
+Before, the solver divided by `1e-8` in place of the zero and returned up to 10 candidates from the
+eigenvalues of the resulting companion matrix. None of them satisfied the essential-matrix
+constraints, and for some samples the backward raised `torch._C._LinAlgError` in the backward of
+`torch.linalg.eigvals`. Now the sample returns the identity for all 10 candidates and its backward
+completes. Samples with a nonzero leading coefficient are unchanged bit for bit. Fixes #4831.
diff --git a/kornia/geometry/epipolar/essential.py b/kornia/geometry/epipolar/essential.py
index dbda81c0e..81c6fab27 100644
--- a/kornia/geometry/epipolar/essential.py
+++ b/kornia/geometry/epipolar/essential.py
@@ -376,7 +376,8 @@ def _null_to_Nister_solution_script(
C[:, 0:9, 1:10] = torch.eye(9, device=device, dtype=dtype)
# Guard only an exactly zero leading coefficient. The roots do not depend on the polynomial's sign,
- # and a floor such as clamp_min would turn a negative coefficient positive and change them.
+ # and a floor such as clamp_min would turn a negative coefficient positive and change them. An
+ # element with a zero one is discarded below; the floor only keeps its companion matrix finite.
cs_de = torch.where(cs[:, -1] == 0, torch.full_like(cs[:, -1], 1e-8), cs[:, -1])
C[:, -1, :] = -cs[:, :-1] / cs_de.unsqueeze(-1)
@@ -384,9 +385,12 @@ def _null_to_Nister_solution_script(
# which takes the whole batch down: a RuntimeError on some platforms, a crash inside MKL on others.
# It comes from an overflow: an elimination system that is ill-conditioned without being exactly
# singular has a solution large enough for the determinant polynomial to overflow, or a finite
- # polynomial overflows when it is divided by its leading coefficient. Those elements get the
- # identity in place of C, and their candidates are set to NaN at the end, like a singular one.
- no_roots = ~torch.isfinite(C).flatten(-2).all(-1) # (B,)
+ # polynomial overflows when it is divided by its leading coefficient. Nor has a polynomial whose
+ # leading coefficient is exactly zero: its degree is below 10, the floor above scales its companion
+ # row by 1e8, and the eigenvalues are not its roots. Its eigenvector matrix can then be singular,
+ # which makes the eigvals backward raise. Those elements get the identity in place of C, and their
+ # candidates are set to NaN at the end, like a singular one.
+ no_roots = ~torch.isfinite(C).flatten(-2).all(-1) | (cs[:, -1] == 0) # (B,)
if no_roots.any():
C = torch.where(no_roots.view(B, 1, 1), eye10, C)
@@ -916,8 +920,8 @@ def find_essential(
with no real solution returns ten identity matrices instead of ``NaN``
(`#4883 <https://github.com/kornia/kornia/issues/4883>`_); in ``float32`` an exact five-point sample can
miss the true solution, which six or more correspondences recover
- (`#4884 <https://github.com/kornia/kornia/issues/4884>`_); backward raises on some degenerate samples, such
- as identical point sets (`#4831 <https://github.com/kornia/kornia/issues/4831>`_);
+ (`#4884 <https://github.com/kornia/kornia/issues/4884>`_); backward can raise on a degenerate sample whose
+ polynomial has a multiple root at zero (`#4903 <https://github.com/kornia/kornia/issues/4903>`_);
on MPS the 5-point solve needs the CPU fallback (`#4528 <https://github.com/kornia/kornia/issues/4528>`_).
Args:
diff --git a/tests/geometry/epipolar/test_essential.py b/tests/geometry/epipolar/test_essential.py
index ce2e83c55..273fc69a1 100644
--- a/tests/geometry/epipolar/test_essential.py
+++ b/tests/geometry/epipolar/test_essential.py
@@ -222,6 +222,15 @@ class TestFindEssential(BaseTester):
E_zeros = epi.essential.find_essential(zeros, zeros, torch.ones(B, N, device=device, dtype=dtype))
self.assert_close(E_zeros, eye.expand(B, 10, 3, 3), atol=0.0, rtol=0.0)
+ # Its degree-10 polynomial also has an exactly zero leading coefficient. The companion matrix
+ # built from it had a repeated eigenvalue and a singular eigenvector matrix, so the backward
+ # raised in torch.linalg.eigvals (#4831). It now completes, and since the sample's candidates are
+ # discarded its gradient is exactly zero, also through the SVD of its rank-1 design matrix (#4855).
+ origin = torch.zeros(B, N, 2, device=device, dtype=dtype, requires_grad=True)
+ weights_bn = torch.ones(B, N, device=device, dtype=dtype)
+ epi.essential.find_essential(origin, origin, weights_bn).nan_to_num().sum().backward()
+ assert (origin.grad == 0).all()
+
# A singular element does not disturb the rest of its batch: next to one, a regular sample
# returns exactly what it returns next to a regular sample, NaN candidates from complex roots
# included. The reference is a batch of the same size, because the batch size alone can change
@@ -285,6 +294,35 @@ class TestFindEssential(BaseTester):
assert torch.equal(torch.isnan(patched[1]), torch.isnan(regular))
self.assert_close(torch.nan_to_num(patched[1]), torch.nan_to_num(regular), atol=0.0, rtol=0.0)
+ # A zero leading coefficient means the polynomial has no usable companion matrix either (#4831).
+ # Which inputs give one exactly is platform-dependent, so zero it for one element: that element
+ # takes the identity fallback, the other returns exactly what it returns unpatched, and the
+ # backward through both completes with a finite gradient.
+ def degree_deficient(A, *args):
+ cs = determinant(A, *args).clone()
+ cs[0, -1] = 0.0
+ return cs
+
+ monkeypatch.setattr(epi.essential, "_determinant_to_polynomial_jit", degree_deficient)
+ points1 = torch.stack((x1, x1)).requires_grad_()
+ patched = epi.essential.find_essential(points1, torch.stack((x2, x2)), weights)
+ self.assert_close(patched[0].detach(), eye.expand(10, 3, 3), atol=0.0, rtol=0.0)
+ assert torch.equal(torch.isnan(patched[1]), torch.isnan(regular))
+ self.assert_close(torch.nan_to_num(patched[1].detach()), torch.nan_to_num(regular), atol=0.0, rtol=0.0)
+ patched.nan_to_num().sum().backward()
+ assert torch.isfinite(points1.grad).all()
+
+ # Check the backward through a zeroed element once more with 9 points, where the null space comes
+ # from torch.linalg.svd itself instead of the N < 9 path.
+ g9 = torch.Generator().manual_seed(1)
+ points9 = torch.rand(2, 9, 2, generator=g9, dtype=torch.float64).to(device=device, dtype=dtype)
+ points9.requires_grad_()
+ other9 = torch.rand(2, 9, 2, generator=g9, dtype=torch.float64).to(device=device, dtype=dtype)
+ E9 = epi.essential.find_essential(points9, other9, torch.ones(2, 9, device=device, dtype=dtype))
+ self.assert_close(E9[0].detach(), eye.expand(10, 3, 3), atol=0.0, rtol=0.0)
+ E9.nan_to_num().sum().backward()
+ assert torch.isfinite(points9.grad).all()
+
class TestEssentialFromFundamental(BaseTester):
def test_smoke(self, device, dtype):