🐍 Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
fix(epipolar): return NaN slots from find_essential for a sample without a real root (#4922)
Rızgar Ozand54b134d37fa
diff --git a/changelog.d/4766.fixed.md b/changelog.d/4766.fixed.mdindex febfd3ba3..78544cb38 100644--- a/changelog.d/4766.fixed.md+++ b/changelog.d/4766.fixed.md@@ -1,8 +1,8 @@`find_essential` and `run_5point` no longer abort with `torch._C._LinAlgError` when acorrespondence 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.+the origin does. Such a sample has no solution and now returns `NaN` for all 10 candidates, like+any other sample without 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 dropped like any other sample without candidates+instead of raising out of `forward`. Fixes #4765.diff --git a/changelog.d/4846.fixed.md b/changelog.d/4846.fixed.mdindex 390aebbb9..88095914b 100644--- a/changelog.d/4846.fixed.md+++ b/changelog.d/4846.fixed.md@@ -4,5 +4,5 @@ ill-conditioned without being exactly singular and its solution overflows the depolynomial, 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, andby 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.+`NaN` for all 10 candidates, like 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/changelog.d/4888.breaking.md b/changelog.d/4888.breaking.mdindex e0f3c51a0..bb518022d 100644--- a/changelog.d/4888.breaking.md+++ b/changelog.d/4888.breaking.md@@ -1,8 +1,8 @@-`find_essential` and `run_5point` now return the identity fallback for a sample whose degree-10+`find_essential` and `run_5point` now return `NaN` for all 10 candidates of a sample whose degree-10polynomial has an exactly zero leading coefficient, which data with no parallax, such as the samepoints 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 theeigenvalues of the resulting companion matrix. None of them satisfied the essential-matrixconstraints, 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+`torch.linalg.eigvals`. Now the sample returns `NaN` for all 10 candidates and its backwardcompletes. Samples with a nonzero leading coefficient are unchanged bit for bit. Fixes #4831.diff --git a/changelog.d/4922.breaking.md b/changelog.d/4922.breaking.mdnew file mode 100644index 000000000..c39563d9c--- /dev/null+++ b/changelog.d/4922.breaking.md@@ -0,0 +1,8 @@+`find_essential` and `run_5point` now return `NaN` for all 10 candidates of a five-point sample whose+degree-10 polynomial has no real root, the same as the complex slots of any other sample, so an+`isfinite` filter and `RANSAC` drop it. Before, such a sample returned ten 3x3 identity matrices,+which are finite but not essential matrices. Code that detected a failed sample by comparing its+candidates with the identity should test `torch.isnan(E).flatten(-3).all(-1)` instead. The samples+that the fixes for #4765, #4820 and #4831 route to the same path (a singular elimination matrix, a+non-finite companion matrix, a zero leading coefficient) return `NaN` for all 10 candidates as well.+Every other sample, and every gradient taken through `nan_to_num`, is unchanged bit for bit. Fixes #4883.diff --git a/docs/source/get-started/conventions.rst b/docs/source/get-started/conventions.rstindex acc2688f4..9fac7ba53 100644--- a/docs/source/get-started/conventions.rst+++ b/docs/source/get-started/conventions.rst@@ -493,8 +493,7 @@ normalised camera coordinates, and :func:`~kornia.geometry.homography.find_homog``(3k, 3)``* - essential matrix- ``find_essential`` takes normalised camera coordinates :math:`K^{-1} [u, v, 1]^\top` and returns ten- slots, ``NaN`` for complex roots; a sample with no real solution returns ten identity matrices- (`#4883 <https://github.com/kornia/kornia/issues/4883>`_)+ slots, ``NaN`` for complex roots (all ten for a sample with no real solution)- ``findEssentialMat`` takes pixels and ``cameraMatrix`` (or one matrix per camera); with exactly 5 points itstacks the real solutions as ``(3k, 3)``, with more it returns the single ``E`` its RANSAC or LMedS selects* - homographydiff --git a/kornia/geometry/epipolar/essential.py b/kornia/geometry/epipolar/essential.pyindex 100cff7e4..6ec77fcac 100644--- a/kornia/geometry/epipolar/essential.py+++ b/kornia/geometry/epipolar/essential.py@@ -72,12 +72,8 @@ def run_5point(points1: torch.Tensor, points2: torch.Tensor, weights: Optional[t# BxNx9X = torch.cat([x1 * x2, x1 * y2, x1, y1 * x2, y1 * y2, y1, x2, y2, ones], dim=-1)# use Nister's 5PC to solve essential matrix- E = null_to_Nister_solution(X, batch_size)- bad = torch.isnan(E).flatten(-2).all(-1).all(-1) # (B,)- if bad.any():- eye3 = torch.eye(3, device=E.device, dtype=E.dtype).view(1, 1, 3, 3).expand(batch_size, 10, 3, 3)- E = torch.where(bad.view(batch_size, 1, 1, 1), eye3, E)- return E+ # A sample without a real root keeps ten NaN slots, like the complex slots of any other sample.+ return null_to_Nister_solution(X, batch_size)def _multiply_deg_one_poly(a: torch.Tensor, b: torch.Tensor, T_deg1: torch.Tensor) -> torch.Tensor:@@ -330,7 +326,7 @@ def _null_to_Nister_solution_script(# 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+ # candidates are set to NaN at the end, so all ten of their slots are NaN. 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)@@ -913,11 +909,9 @@ def find_essential(:math:`K^{-1} [u, v, 1]^\top`, not pixels; each real candidate satisfies :math:`x_2^\top E x_1 = 0`in them. :ref:`Two-view geometry <two-view-conventions>` maps this onto OpenCV.- All ten slots are always returned: each real root gives a candidate of unit Frobenius norm, and each- complex root a ``NaN`` slot.- - Known defects: ``weights`` is ignored (`#4876 <https://github.com/kornia/kornia/issues/4876>`_); a sample- 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+ complex root a ``NaN`` slot, so a sample with no real solution returns ten ``NaN`` slots.+ - Known defects: ``weights`` is ignored (`#4876 <https://github.com/kornia/kornia/issues/4876>`_); 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 can raise on a degenerate sample whosepolynomial 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>`_).diff --git a/tests/geometry/epipolar/test_essential.py b/tests/geometry/epipolar/test_essential.pyindex 82e698274..7a6899df8 100644--- a/tests/geometry/epipolar/test_essential.py+++ b/tests/geometry/epipolar/test_essential.py@@ -212,15 +212,14 @@ 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, monkeypatch):B, N = batch_size, num_points- 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.+ # singular. A singular sample has no solution, so all 10 of its slots are NaN (#4883).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)+ assert E_zeros.shape == (B, 10, 3, 3)+ assert torch.isnan(E_zeros).all()# 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@@ -252,7 +251,7 @@ class TestFindEssential(BaseTester):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.isnan(mixed[0]).all()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)@@ -279,8 +278,8 @@ class TestFindEssential(BaseTester):# 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 polynomial of one element non-finite instead: that element returns NaN slots, and the+ # other returns exactly what it returns in the unpatched batch above.determinant = epi.essential._determinant_to_polynomial_jitdef overflowed(A, *args):@@ -290,13 +289,13 @@ class TestFindEssential(BaseTester):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.isnan(patched[0]).all()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+ # returns NaN slots, 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()@@ -306,7 +305,7 @@ class TestFindEssential(BaseTester):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.isnan(patched[0]).all()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()@@ -319,7 +318,7 @@ class TestFindEssential(BaseTester):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)+ assert torch.isnan(E9[0]).all()E9.nan_to_num().sum().backward()assert torch.isfinite(points9.grad).all()@@ -1042,13 +1041,23 @@ class TestConventionEssential(BaseTester):assert not is_truth(R_b[1], t_b[1])assert (X_b[1, :, 2] < 0).any()- def test_wart_find_essential_no_real_root_identity_4883(self, device, dtype):+ def test_convention_find_essential_no_real_root_nan_4883(self, device, dtype):_skip_find_essential(device, dtype)- # #4883: a five-point sample with no real root returns ten identity matrices instead of NaN slots. Sample:+ # #4883: a five-point sample with no real root returns ten NaN slots, like the complex slots of any other+ # sample, so an isfinite filter drops it. Sample:# g = torch.Generator().manual_seed(0)# p1 = torch.randn(4000, 5, 2, generator=g, dtype=torch.float64) * 0.5 # then p2 from the same g# p1[1371], p2[1371]- p1 = torch.tensor(_NO_REAL_ROOT_P1, device=device, dtype=dtype)[None]- p2 = torch.tensor(_NO_REAL_ROOT_P2, device=device, dtype=dtype)[None]+ # Batched with an ordinary sample, which keeps its real candidates and finite gradients.+ g = torch.Generator().manual_seed(0)+ q1, q2 = (torch.randn(1, 5, 2, generator=g, dtype=torch.float64) * 0.5 for _ in range(2))+ p1 = torch.cat([torch.tensor(_NO_REAL_ROOT_P1, dtype=torch.float64)[None], q1]).to(device, dtype)+ p2 = torch.cat([torch.tensor(_NO_REAL_ROOT_P2, dtype=torch.float64)[None], q2]).to(device, dtype)+ p1.requires_grad_()E = epi.find_essential(p1, p2)- assert torch.equal(E, torch.eye(3, device=device, dtype=dtype).expand(1, 10, 3, 3))+ assert torch.isnan(E[0]).all()+ real = torch.isfinite(E[1]).flatten(1).all(1)+ assert real.any()+ (grad,) = torch.autograd.grad(E[1][real].sum(), p1)+ assert torch.isfinite(grad).all()+ assert (grad[0] == 0).all()