Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

fix(epipolar): keep a non-finite companion matrix away from eigvals (#4846)

Leonardo Vanni14475e356f5c
diff --git a/changelog.d/4846.fixed.md b/changelog.d/4846.fixed.md
new file mode 100644
index 000000000..390aebbb9
--- /dev/null
+++ b/changelog.d/4846.fixed.md
@@ -0,0 +1,8 @@
+`find_essential` and `run_5point` no longer abort when a degenerate sample makes the companion matrix
+of the 5-point solver non-finite. That happens at float32 when the elimination system is
+ill-conditioned without being exactly singular and its solution overflows the determinant
+polynomial, or when a finite polynomial overflows on division by its leading coefficient.
+`torch.linalg.eigvals` rejected that matrix for the whole batch: with a `RuntimeError` on macOS, and
+by crashing the process inside MKL on Linux x86. Such a sample has no usable roots and now returns
+the same identity fallback as a singular one. Every other sample is unchanged bit for bit, including
+one that shares its batch. Which inputs reach this path depends on the platform's LAPACK.
diff --git a/kornia/geometry/epipolar/essential.py b/kornia/geometry/epipolar/essential.py
index 34e443e87..37e34286e 100644
--- a/kornia/geometry/epipolar/essential.py
+++ b/kornia/geometry/epipolar/essential.py
@@ -323,6 +323,16 @@ def _null_to_Nister_solution_script(
cs_de = cs[:, -1].clamp_min(1e-8)
C[:, -1, :] = -cs[:, :-1] / cs_de.unsqueeze(-1)
+ # A companion matrix that is not finite has no usable roots, and torch.linalg.eigvals aborts on it,
+ # 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,)
+ if no_roots.any():
+ C = torch.where(no_roots.view(B, 1, 1), eye10, C)
+
roots_eig = torch.linalg.eigvals(C) # (B,10), complex
roots = torch.real(roots_eig)
is_real = torch.abs(torch.imag(roots_eig)) < 1e-10
@@ -379,9 +389,11 @@ def _null_to_Nister_solution_script(
# after Es is created (B,10,3,3)
if bad2.any():
Es[bad2] = torch.nan
- # a singular elimination matrix has no candidates
+ # a singular elimination matrix has no candidates, and neither has a non-finite companion matrix
if singular.any():
Es[singular] = torch.nan
+ if no_roots.any():
+ Es[no_roots] = torch.nan
# mark complex roots as NaN (keeps shape, no compaction)
if is_real.logical_not().any():
Es[~is_real] = torch.nan
diff --git a/tests/geometry/epipolar/test_essential.py b/tests/geometry/epipolar/test_essential.py
index 99564b923..595a065e8 100644
--- a/tests/geometry/epipolar/test_essential.py
+++ b/tests/geometry/epipolar/test_essential.py
@@ -95,7 +95,7 @@ class TestFindEssential(BaseTester):
)
@pytest.mark.parametrize("batch_size, num_points", [(5, 5), (10, 5)])
- def test_degenerate_case(self, batch_size, num_points, device, dtype):
+ def test_degenerate_case(self, batch_size, num_points, device, dtype, monkeypatch):
B, N = batch_size, num_points
eye = torch.eye(3, device=device, dtype=dtype)
@@ -132,12 +132,18 @@ class TestFindEssential(BaseTester):
assert torch.equal(torch.isnan(mixed[1]), torch.isnan(regular))
self.assert_close(torch.nan_to_num(mixed[1]), torch.nan_to_num(regular), atol=0.0, rtol=0.0)
- # Whether any other degenerate set is exactly singular depends on the platform's LAPACK. This
- # L-shaped set and a random draw with the same points in both images exercise that path where
- # it occurs, and must return the documented shape either way.
+ # Whether any other degenerate set is exactly singular, or ill-conditioned enough to make the
+ # companion matrix non-finite, depends on the platform's LAPACK. These sets and a random draw
+ # with the same points in both images exercise those paths where they occur, and must return the
+ # documented shape either way. The last two give a non-finite companion matrix at float32 on
+ # Linux x86 and on macOS arm64 respectively.
lshape = torch.tensor([[1.0, 0.0], [0.5, 0.0], [0.0, 1.0], [0.0, 0.0], [0.0, 0.5]], device=device, dtype=dtype)
draw = torch.rand(B, N, 2, generator=torch.Generator().manual_seed(79)).to(device=device, dtype=dtype)
- for points in (lshape.expand(B, 5, 2), draw):
+ on_axis = torch.tensor([[0.0, 0.0], [0.0, 0.0], [0.0, 0.0], [0.0, 0.0], [1.0, 0.0]], device=device, dtype=dtype)
+ repeated = torch.tensor(
+ [[2.0, 0.0], [2.0, 2.0], [2.0, 2.0], [2.0, 2.0], [2.0, 1.0]], device=device, dtype=dtype
+ )
+ for points in (lshape.expand(B, 5, 2), draw, on_axis.expand(B, 5, 2), repeated.expand(B, 5, 2)):
weights = torch.ones(points.shape[:2], device=device, dtype=dtype)
assert epi.essential.find_essential(points, points, weights).shape == (B, 10, 3, 3)
@@ -147,6 +153,23 @@ class TestFindEssential(BaseTester):
design = torch.eye(9, device=device, dtype=dtype)[[0, 1, 3, 5, 6]].expand(B, 5, 9)
assert torch.isnan(epi.essential.null_to_Nister_solution(design, B)).all()
+ # A companion matrix that is not finite has no roots, and torch.linalg.eigvals aborts on one, which
+ # used to take the whole batch down. Which inputs produce it is platform-dependent, so make the
+ # determinant polynomial of one element non-finite instead: that element takes the identity
+ # fallback, and the other returns exactly what it returns in the unpatched batch above.
+ determinant = epi.essential._determinant_to_polynomial_jit
+
+ def overflowed(A, *args):
+ cs = determinant(A, *args).clone()
+ cs[0] = float("nan")
+ return cs
+
+ monkeypatch.setattr(epi.essential, "_determinant_to_polynomial_jit", overflowed)
+ patched = epi.essential.find_essential(torch.stack((x1, x1)), torch.stack((x2, x2)), weights)
+ self.assert_close(patched[0], 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]), torch.nan_to_num(regular), atol=0.0, rtol=0.0)
+
class TestEssentialFromFundamental(BaseTester):
def test_smoke(self, device, dtype):