Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

fix(epipolar): return the identity fallback for a singular elimination matrix (#4766)

Leonardo Vannia564061cc630
diff --git a/changelog.d/4766.fixed.md b/changelog.d/4766.fixed.md
new file mode 100644
index 000000000..febfd3ba3
--- /dev/null
+++ b/changelog.d/4766.fixed.md
@@ -0,0 +1,8 @@
+`find_essential` and `run_5point` no longer abort with `torch._C._LinAlgError` when a
+correspondence set makes the 10x10 elimination matrix exactly singular, as a set of points all at
+the origin does. Such a sample has no solution and now returns the same fallback as any other sample
+without candidates: the identity, for all 10 candidates. Whether another degenerate set is exactly
+singular depends on the platform's LAPACK. Every other sample goes through the same solve as before
+and its result is unchanged bit for bit, including when a singular sample shares its batch, so a
+singular minimal sample inside `RANSAC(model_type="essential")` is scored like any other instead of
+raising out of `forward`. Fixes #4765.
diff --git a/kornia/geometry/epipolar/essential.py b/kornia/geometry/epipolar/essential.py
index 6f467197d..34e443e87 100644
--- a/kornia/geometry/epipolar/essential.py
+++ b/kornia/geometry/epipolar/essential.py
@@ -269,13 +269,25 @@ def _null_to_Nister_solution_script(
A10 = coeffs[:, :, :10] # (B, 10, 10)
b_poly = coeffs[:, :, 10:] # (B, 10, 10)
- # Prefer direct solve; if singular, add tiny damping (no batch compaction).
eye10 = torch.eye(10, device=device, dtype=dtype).unsqueeze(0).expand(B, 10, 10)
+ # An exactly singular A10 means the sample has no solution. torch.linalg.solve raises on such an
+ # element rather than returning NaN, so the singular elements are found first with lu_factor_ex,
+ # which reports a zero pivot through ``info`` instead of raising, and are solved against the
+ # identity so that nothing below can raise or overflow on them in the forward pass. Their
+ # candidates are set to NaN at the end, which run_5point maps to its identity fallback. Every
+ # other element keeps A10: the replacement is made in ``coeffs`` and sliced like A10, because
+ # torch.linalg.solve can round a contiguous copy differently from the strided slice.
+ _, _, info = torch.linalg.lu_factor_ex(A10)
+ singular = info > 0 # (B,)
+ A_solve = A10
+ if singular.any():
+ A_solve = torch.where(singular.view(B, 1, 1), torch.cat((eye10, b_poly), dim=-1), coeffs)[:, :, :10]
+
# Try direct solve first
- eliminated = torch.linalg.solve(A10, b_poly) # (B,10,10)
+ eliminated = torch.linalg.solve(A_solve, b_poly) # (B,10,10)
- # Detect NaN/Inf from singular solve and fix with damping solve
+ # Detect NaN/Inf from an ill-conditioned solve and fix with damping solve
bad = torch.isnan(eliminated).flatten(-2).any(-1) | torch.isinf(eliminated).flatten(-2).any(-1) # (B,)
if bad.any():
# Damped solve only for bad rows but WITHOUT compaction:
@@ -283,7 +295,8 @@ def _null_to_Nister_solution_script(
# (use per-batch scalar to avoid huge allocations)
diagA = torch.diagonal(A10, dim1=-2, dim2=-1).abs().mean(dim=-1) # (B,)
lam = (diagA * 1e-8 + 1e-8).to(dtype) # (B,)
- A_damped = A10 + eye10 * lam.view(B, 1, 1)
+ # built from A_solve, not A10, so a singular element in the same batch cannot raise here
+ A_damped = A_solve + eye10 * lam.view(B, 1, 1)
eliminated_d = torch.linalg.solve(A_damped, b_poly)
eliminated = torch.where(bad.view(B, 1, 1), eliminated_d, eliminated)
@@ -366,6 +379,9 @@ 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
+ if singular.any():
+ Es[singular] = 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 d49e3e593..99564b923 100644
--- a/tests/geometry/epipolar/test_essential.py
+++ b/tests/geometry/epipolar/test_essential.py
@@ -97,10 +97,55 @@ 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):
B, N = batch_size, num_points
- points1_deg = torch.rand(B, N, 2, device=device, dtype=dtype)
- weights = torch.ones_like(points1_deg)[..., 0]
- E_mat_deg = epi.essential.find_essential(points1_deg, points1_deg, weights)
- assert E_mat_deg.shape == (B, 10, 3, 3)
+ eye = torch.eye(3, device=device, dtype=dtype)
+
+ # Points all at the origin give a design matrix whose SVD returns unit vectors for its null
+ # space, and every basis of four unit vectors makes the 10x10 elimination matrix exactly
+ # singular. A singular sample has no solution, so find_essential returns run_5point's fallback
+ # for an element without candidates: the identity, for all 10.
+ zeros = torch.zeros(B, N, 2, device=device, dtype=dtype)
+ 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)
+
+ # 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
+ # the last bits of a result (by 4.8e-15 at float64 on macOS arm64).
+ x1 = torch.tensor(
+ [[0.0640, 0.7799], [-0.2011, 0.2836], [-0.1355, 0.2907], [0.0520, 1.0086], [-0.0361, 0.6533]],
+ device=device,
+ dtype=dtype,
+ )
+ x2 = torch.tensor(
+ [[0.3470, -0.4274], [-0.1818, -0.1281], [-0.1766, -0.1617], [0.4066, -0.0706], [0.1137, 0.0363]],
+ device=device,
+ dtype=dtype,
+ )
+ weights = torch.ones(2, 5, device=device, dtype=dtype)
+ regular = epi.essential.find_essential(torch.stack((x1, x1)), torch.stack((x2, x2)), weights)[1]
+ mixed = epi.essential.find_essential(
+ torch.stack((zeros[0, :5], x1)),
+ torch.stack((zeros[0, :5], x2)),
+ weights,
+ )
+ self.assert_close(mixed[0], eye.expand(10, 3, 3), atol=0.0, rtol=0.0)
+ 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.
+ 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):
+ weights = torch.ones(points.shape[:2], device=device, dtype=dtype)
+ assert epi.essential.find_essential(points, points, weights).shape == (B, 10, 3, 3)
+
+ # For a design matrix whose rows are unit vectors, the SVD returns a null space of unit vectors,
+ # which makes the elimination matrix exactly singular. For this one, solving against the identity
+ # leaves finite candidates that fail the essential-matrix constraints, so they must be dropped.
+ 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()
class TestEssentialFromFundamental(BaseTester):