Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

fix(core)!: keep gradients finite past a singular matrix in safe_inverse_with_mask and safe_solve_with_mask (#5459)

Mohammad Hijjawia73c1ee48178
diff --git a/changelog.d/5459.breaking.md b/changelog.d/5459.breaking.md
new file mode 100644
index 000000000..bd0e23788
--- /dev/null
+++ b/changelog.d/5459.breaking.md
@@ -0,0 +1 @@
+`safe_inverse_with_mask` and `safe_solve_with_mask` no longer turn the gradient NaN when one matrix in the batch is singular. Validity is decided on a detached pass and the invalid matrices are replaced by the identity before inverting or solving. An invalid row used to hold NaN in eager mode (a finite adjugate under tracing or export); it now holds the identity inverse (or `B` for the solve) in every mode. A float16 inverse that overflows is now reported invalid instead of `inf` with `mask=True`. `find_homography_dlt`, `find_homography_dlt_iterated`, `find_homography_lines_dlt` and `fundamental_from_essential` still return NaN for degenerate input.
diff --git a/kornia/core/utils.py b/kornia/core/utils.py
index b83715f21..baaa6e1ff 100644
--- a/kornia/core/utils.py
+++ b/kornia/core/utils.py
@@ -378,10 +378,29 @@ def _torch_solve_cast(A: torch.Tensor, B: torch.Tensor) -> torch.Tensor:
return out.to(A.dtype)
+def _rows_finite(x: torch.Tensor) -> torch.Tensor:
+ """Whether every entry of each trailing matrix of ``x`` is finite, as a mask over its batch."""
+ return x.isfinite().all(-1).all(-1)
+
+
def safe_solve_with_mask(B: torch.Tensor, A: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
r"""Solves the system of equations.
Avoids crashing because of singular matrix input and outputs the mask of valid solution.
+
+ A system is valid when the LU factorization of ``A`` has no zero pivot and the solution is finite in
+ the dtype of ``B``. An invalid system is solved with the identity in place of ``A``, so its row of
+ ``X`` holds ``B`` and its row of the returned LU factor is the identity's. The differentiated solve
+ therefore never sees a singular matrix, and the gradient with respect to the valid systems (and to
+ any parameter they share with an invalid one) stays finite.
+
+ Args:
+ B: right-hand side of shape :math:`(*, N, K)` or :math:`(*, N)`.
+ A: square matrices of shape :math:`(*, N, N)`.
+
+ Returns:
+ The solution :math:`(*, N, K)`, the LU factor of the solved matrices :math:`(*, N, N)` and the
+ validity mask :math:`(*)`.
"""
# Based on https://github.com/pytorch/pytorch/issues/31546#issuecomment-694135622
KORNIA_CHECK_IS_TENSOR(B, "B must be torch.Tensor")
@@ -390,16 +409,26 @@ def safe_solve_with_mask(B: torch.Tensor, A: torch.Tensor) -> Tuple[torch.Tensor
if dtype not in (torch.float32, torch.float64):
dtype = torch.float32
- # Since kornia requires torch>=2.5.1, we can always use torch.linalg.lu_factor_ex and torch.linalg.lu_solve
- A_LU, pivots, info = torch.linalg.lu_factor_ex(A.to(dtype))
-
- valid_mask: torch.Tensor = info == 0
n_dim_B = len(B.shape)
n_dim_A = len(A.shape)
if n_dim_A - n_dim_B == 1:
B = B.unsqueeze(-1)
- X = torch.linalg.lu_solve(A_LU, pivots, B.to(dtype))
+ A_cast = A.to(dtype)
+ B_cast = B.to(dtype)
+
+ # Decide validity on a detached pass, then solve a system whose invalid matrices are replaced by the
+ # identity. Masking the output instead is not enough: the backward of ``lu_factor`` / ``lu_solve`` at
+ # a singular matrix is non-finite, and ``0 * nan`` leaks it into every shared parameter.
+ # Since kornia requires torch>=2.5.1, we can always use torch.linalg.lu_factor_ex and torch.linalg.lu_solve
+ LU_detached, pivots_detached, info = torch.linalg.lu_factor_ex(A_cast.detach())
+ X_detached = torch.linalg.lu_solve(LU_detached, pivots_detached, B_cast.detach())
+ valid_mask: torch.Tensor = (info == 0) & _rows_finite(X_detached.to(B.dtype))
+
+ eye = torch.eye(A_cast.shape[-1], device=A_cast.device, dtype=dtype)
+ A_safe = torch.where(valid_mask[..., None, None], A_cast, eye)
+ A_LU, pivots, _ = torch.linalg.lu_factor_ex(A_safe)
+ X = torch.linalg.lu_solve(A_LU, pivots, B_cast)
return X.to(B.dtype), A_LU.to(A.dtype), valid_mask
@@ -408,22 +437,42 @@ def safe_inverse_with_mask(A: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor]
r"""Perform inverse.
Avoids crashing because of non-invertable matrix input and outputs the mask of valid solution.
+
+ A matrix is valid when it is invertible (no zero pivot in eager mode, a non-zero determinant under
+ graph capture) and its inverse is finite in the dtype of ``A``. An invalid matrix is inverted as the
+ identity, so its row of the output is the identity. The differentiated inverse therefore never sees a
+ singular matrix, and the gradient with respect to the valid matrices (and to any parameter they
+ share with an invalid one) stays finite.
+
+ Args:
+ A: square matrices of shape :math:`(*, N, N)`.
+
+ Returns:
+ The inverse :math:`(*, N, N)` and the validity mask :math:`(*)`.
"""
KORNIA_CHECK_IS_TENSOR(A, "A must be torch.Tensor")
dtype_original = A.dtype
dtype = _normalize_to_float32_or_float64(dtype_original)
+ A_cast = A.to(dtype)
+ eye = torch.eye(A_cast.shape[-1], device=A_cast.device, dtype=dtype)
+ # Decide validity on a detached pass, then invert a batch whose invalid matrices are replaced by the
+ # identity. Masking the output instead is not enough: the backward of ``inv`` reuses its non-finite
+ # output, and ``0 * nan`` leaks it into every shared parameter.
if _is_tracing_or_exporting() and _has_closed_form_inverse(A):
# ``linalg_inv_ex`` has no ONNX lowering; the adjugate form is basic arithmetic, and a
# zero determinant is exactly the singularity ``inv_ex`` flags through ``info``.
- adj, det = _adjugate_closed_form(A.to(dtype))
- mask = det != 0
- safe_det = torch.where(mask, det, torch.ones_like(det))
- return (adj / safe_det[..., None, None]).to(dtype_original), mask
-
- inverse, info = inv_ex(A.to(dtype))
- mask = info == 0
+ adj_detached, det_detached = _adjugate_closed_form(A_cast.detach())
+ mask = det_detached != 0
+ safe_det = torch.where(mask, det_detached, torch.ones_like(det_detached))
+ mask = mask & _rows_finite((adj_detached / safe_det[..., None, None]).to(dtype_original))
+ adj, det = _adjugate_closed_form(torch.where(mask[..., None, None], A_cast, eye))
+ return (adj / det[..., None, None]).to(dtype_original), mask
+
+ inverse_detached, info = inv_ex(A_cast.detach())
+ mask = (info == 0) & _rows_finite(inverse_detached.to(dtype_original))
+ inverse, _ = inv_ex(torch.where(mask[..., None, None], A_cast, eye))
return inverse.to(dtype_original), mask
diff --git a/kornia/geometry/epipolar/fundamental.py b/kornia/geometry/epipolar/fundamental.py
index 9793c624d..840d811aa 100644
--- a/kornia/geometry/epipolar/fundamental.py
+++ b/kornia/geometry/epipolar/fundamental.py
@@ -743,7 +743,13 @@ def fundamental_from_essential(E_mat: torch.Tensor, K1: torch.Tensor, K2: torch.
if not len(E_mat.shape[:-2]) == len(K1.shape[:-2]) == len(K2.shape[:-2]):
raise AssertionError
- return (safe_inverse_with_mask(K2)[0]).transpose(-2, -1) @ E_mat @ (safe_inverse_with_mask(K1)[0])
+ K1_inv, valid1 = safe_inverse_with_mask(K1)
+ K2_inv, valid2 = safe_inverse_with_mask(K2)
+ F_mat = K2_inv.transpose(-2, -1) @ E_mat @ K1_inv
+ # A singular camera matrix has no fundamental matrix: keep it NaN rather than using the identity
+ # that ``safe_inverse_with_mask`` substitutes for the inverse.
+ valid = (valid1 & valid2)[..., None, None]
+ return torch.where(valid, F_mat, torch.full_like(F_mat, float("nan")))
# adapted from:
diff --git a/kornia/geometry/homography.py b/kornia/geometry/homography.py
index a5cfee9d2..91f4dd48a 100644
--- a/kornia/geometry/homography.py
+++ b/kornia/geometry/homography.py
@@ -528,10 +528,20 @@ def find_homography_dlt(
device, dtype = _extract_device_dtype([points1, points2])
A, transform1, transform2 = _homography_dlt_system(points1, points2, weights)
return _homography_from_dlt_system(
- A, weights, transform1, safe_inverse_with_mask(transform2)[0], solver, device, dtype
+ A, weights, transform1, _inverse_normalization(transform2), solver, device, dtype
)
+def _inverse_normalization(transform: torch.Tensor) -> torch.Tensor:
+ """Invert a Hartley normalization, NaN where it is singular.
+
+ A point set whose mean radius overflows gets a zero scale and a singular normalization. Its homography
+ is undefined, so it is NaN rather than built from the identity ``safe_inverse_with_mask`` substitutes.
+ """
+ inverse, valid = safe_inverse_with_mask(transform)
+ return torch.where(valid[..., None, None], inverse, torch.full_like(inverse, float("nan")))
+
+
def _homography_dlt_system(
points1: torch.Tensor, points2: torch.Tensor, weights: Optional[torch.Tensor] = None
) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
@@ -593,7 +603,10 @@ def _homography_from_dlt_system(
elif solver == "lu":
if not minimal_lu:
B = torch.ones(A.shape[0], A.shape[1], device=device, dtype=dtype)
- sol, _, _ = safe_solve_with_mask(B, A)
+ sol, _, valid = safe_solve_with_mask(B, A)
+ # A singular normal matrix (degenerate points) has no solution: report it as NaN rather
+ # than the identity system's solution that ``safe_solve_with_mask`` leaves in its place.
+ sol = torch.where(valid[:, None, None], sol, torch.full_like(sol, float("nan")))
else:
# A four-point sample gives eight equations for nine unknowns, so the normal matrix
# is singular and LU-factoring it is what produced all-NaN homographies. Work from
@@ -668,13 +681,13 @@ def find_homography_dlt_iterated(
device, dtype = _extract_device_dtype([points1, points2])
# Weighted Hartley normalization changes with each set of IRLS weights.
A, transform1, transform2 = _homography_dlt_system(points1, points2, weights)
- transform2_inv = safe_inverse_with_mask(transform2)[0]
+ transform2_inv = _inverse_normalization(transform2)
H: torch.Tensor = _homography_from_dlt_system(A, weights, transform1, transform2_inv, "lu", device, dtype)
for _ in range(n_iter - 1):
squared_errors: torch.Tensor = symmetric_transfer_error(points1, points2, H, True)
weights_new: torch.Tensor = torch.exp(-squared_errors / (2.0 * (soft_inl_th**2)))
A, transform1, transform2 = _homography_dlt_system(points1, points2, weights_new)
- transform2_inv = safe_inverse_with_mask(transform2)[0]
+ transform2_inv = _inverse_normalization(transform2)
H = _homography_from_dlt_system(A, weights_new, transform1, transform2_inv, "lu", device, dtype)
return H
@@ -807,7 +820,7 @@ def find_homography_lines_dlt(
return torch.empty((points1_norm.size(0), 3, 3), device=device, dtype=dtype)
H = V[..., -1].view(-1, 3, 3)
- H = safe_inverse_with_mask(transform2)[0] @ (H @ transform1)
+ H = _inverse_normalization(transform2) @ (H @ transform1)
return normalize_transformation(H, eps)
diff --git a/tests/core/test_helpers.py b/tests/core/test_helpers.py
index 75fb47cd7..fb99b064f 100644
--- a/tests/core/test_helpers.py
+++ b/tests/core/test_helpers.py
@@ -468,6 +468,47 @@ class TestSolveWithMask:
_X, _, mask = safe_solve_with_mask(B, A)
assert torch.equal(mask, torch.zeros_like(mask))
+ @pytest.mark.parametrize("masking", ["mul", "where"])
+ def test_singular_matrix_keeps_shared_gradient_finite(self, masking, device, dtype):
+ # kornia#5194: one singular matrix in the batch made the gradient of a parameter shared by all
+ # of them NaN, however the caller masked the output.
+ if dtype in (torch.float16, torch.bfloat16):
+ pytest.skip("the reference gradient needs full precision")
+ M = torch.stack([torch.eye(3), torch.zeros(3, 3), 2 * torch.eye(3)]).to(device, dtype)
+ B = torch.ones(3, 3, device=device, dtype=dtype)
+
+ def grad(M: torch.Tensor, B: torch.Tensor) -> torch.Tensor:
+ W = torch.eye(3, device=device, dtype=dtype) + 0.1 * torch.arange(9.0, device=device, dtype=dtype).view(
+ 3, 3
+ )
+ W.requires_grad_()
+ X, _, mask = safe_solve_with_mask(B, W @ M)
+ m = mask[:, None, None]
+ loss = (X * m).sum() if masking == "mul" else torch.where(m, X, torch.zeros_like(X)).sum()
+ loss.backward()
+ return W.grad
+
+ _, _, mask = safe_solve_with_mask(B, M)
+ assert mask.tolist() == [True, False, True]
+ # The singular system contributes nothing, so the gradient is the one of the valid systems alone.
+ assert_close(grad(M, B), grad(M[[0, 2]], B[[0, 2]]))
+
+ def test_singular_matrix_solves_identity(self, device, dtype):
+ A = torch.stack([2 * torch.eye(3), torch.ones(3, 3)]).to(device, dtype)
+ B = torch.arange(6.0, device=device, dtype=dtype).view(2, 3)
+ X, _, mask = safe_solve_with_mask(B, A)
+ assert mask.tolist() == [True, False]
+ assert_close(X[0, :, 0], B[0] / 2)
+ assert torch.equal(X[1, :, 0], B[1])
+
+ def test_overflowing_solution_is_invalid(self, device):
+ # The solution of (1e-5 * I) x = 1 is 1e5, which float16 cannot hold although the float32 solve can.
+ A = torch.eye(2, device=device, dtype=torch.float16)[None] * 1e-5
+ B = torch.ones(1, 2, 1, device=device, dtype=torch.float16)
+ X, _, mask = safe_solve_with_mask(B, A)
+ assert mask.tolist() == [False]
+ assert torch.equal(X, B)
+
class TestBatchedForwardBatchSize:
def test_rejects_zero_batch_size(self):
@@ -508,6 +549,46 @@ class TestInverseWithMask:
_X, mask = safe_inverse_with_mask(A)
assert torch.equal(mask, torch.zeros_like(mask))
+ @pytest.mark.parametrize("masking", ["mul", "where"])
+ def test_singular_matrix_keeps_shared_gradient_finite(self, masking, device, dtype):
+ # kornia#5194: one singular matrix in the batch made the gradient of a parameter shared by all
+ # of them NaN, however the caller masked the output.
+ if dtype in (torch.float16, torch.bfloat16):
+ pytest.skip("the reference gradient needs full precision")
+ M = torch.stack([torch.eye(3), torch.zeros(3, 3), 2 * torch.eye(3)]).to(device, dtype)
+
+ def grad(M: torch.Tensor) -> torch.Tensor:
+ W = torch.eye(3, device=device, dtype=dtype) + 0.1 * torch.arange(9.0, device=device, dtype=dtype).view(
+ 3, 3
+ )
+ W.requires_grad_()
+ inverse, mask = safe_inverse_with_mask(W @ M)
+ m = mask[:, None, None]
+ loss = (inverse * m).sum() if masking == "mul" else torch.where(m, inverse, torch.zeros_like(inverse)).sum()
+ loss.backward()
+ return W.grad
+
+ _, mask = safe_inverse_with_mask(M)
+ assert mask.tolist() == [True, False, True]
+ # The singular matrix contributes nothing, so the gradient is the one of the valid matrices alone.
+ assert_close(grad(M), grad(M[[0, 2]]))
+
+ def test_singular_matrix_is_identity_in_eager_and_trace(self, device, dtype):
+ A = torch.stack([2 * torch.eye(3), torch.zeros(3, 3)]).to(device, dtype)
+ expected = torch.stack([0.5 * torch.eye(3), torch.eye(3)]).to(device, dtype)
+ for fn in (safe_inverse_with_mask, torch.jit.trace(safe_inverse_with_mask, (A,), check_trace=False)):
+ inverse, mask = fn(A)
+ assert mask.tolist() == [True, False]
+ assert_close(inverse, expected)
+
+ def test_overflowing_inverse_is_invalid(self, device):
+ # The inverse of 1e-5 * I is 1e5 * I, which float16 cannot hold, in eager mode and under capture.
+ A = torch.eye(2, device=device, dtype=torch.float16) * 1e-5
+ for fn in (safe_inverse_with_mask, torch.jit.trace(safe_inverse_with_mask, (A,), check_trace=False)):
+ inverse, mask = fn(A)
+ assert not mask.item()
+ assert torch.equal(inverse, torch.eye(2, device=device, dtype=torch.float16))
+
def test_is_autocast_enabled_cpu():
assert not is_autocast_enabled()
diff --git a/tests/geometry/epipolar/test_fundamental.py b/tests/geometry/epipolar/test_fundamental.py
index bbcd10449..fb15ed646 100644
--- a/tests/geometry/epipolar/test_fundamental.py
+++ b/tests/geometry/epipolar/test_fundamental.py
@@ -452,6 +452,20 @@ class TestFundamentlFromEssential(BaseTester):
F_mat = epi.fundamental_from_essential(E_mat, K1, K2)
assert F_mat.shape == (1, 2, 3, 3)
+ def test_singular_camera_gives_nan(self, device, dtype):
+ # kornia#5194: safe_inverse_with_mask returns the identity for a singular matrix, which must not
+ # turn a singular camera into a finite fundamental matrix.
+ E_mat = torch.rand(2, 3, 3, device=device, dtype=dtype)
+ K = torch.stack([torch.eye(3), torch.zeros(3, 3)]).to(device, dtype)
+ F_mat = epi.fundamental_from_essential(E_mat, K, K)
+ self.assert_close(F_mat[0], E_mat[0])
+ assert F_mat[1].isnan().all()
+ # a singular K2 alone is enough
+ eye = torch.eye(3, device=device, dtype=dtype).expand(2, 3, 3)
+ F_mat = epi.fundamental_from_essential(E_mat, eye, K)
+ self.assert_close(F_mat[0], E_mat[0])
+ assert F_mat[1].isnan().all()
+
def test_from_to_essential(self, device, dtype):
scene = generate_two_view_random_scene(device, dtype)
diff --git a/tests/geometry/test_homography.py b/tests/geometry/test_homography.py
index 8dec29e6f..ca775dcdf 100644
--- a/tests/geometry/test_homography.py
+++ b/tests/geometry/test_homography.py
@@ -529,6 +529,30 @@ class TestFindHomographyDLT(BaseTester):
assert H.shape == (1, 3, 3)
assert H.isnan().all().item()
+ def test_degenerate_points_lu_give_nan(self, device, dtype):
+ # Coincident points make the normal equations singular: no homography, so NaN rather than the
+ # identity system's solution that safe_solve_with_mask leaves for an invalid system (kornia#5194).
+ points = torch.zeros(1, 6, 2, device=device, dtype=dtype)
+ H = find_homography_dlt(points, points, solver="lu")
+ assert H.isnan().all().item()
+
+ @pytest.mark.parametrize("solver", ["svd", "lu"])
+ def test_singular_normalization_gives_nan(self, device, dtype, solver):
+ # A spread whose squared radius overflows gives points2 a zero Hartley scale and a singular
+ # normalization: NaN rather than a homography built from the identity that safe_inverse_with_mask
+ # substitutes for its inverse (kornia#5194).
+ if dtype in (torch.float16, torch.bfloat16):
+ pytest.skip("the half-precision norm accumulates in float32 and does not overflow")
+ points1 = torch.tensor(
+ [[[0.0, 0.0], [1.0, 0.0], [0.0, 1.0], [1.0, 1.0], [0.5, 0.2], [0.3, 0.7]]], device=device, dtype=dtype
+ )
+ points2 = points1 * (torch.finfo(dtype).max / 4)
+ assert find_homography_dlt(points1, points2, solver=solver).isnan().all().item()
+ weights = torch.ones(1, 6, device=device, dtype=dtype)
+ assert find_homography_dlt_iterated(points1, points2, weights, n_iter=1).isnan().all().item()
+ # the segment endpoints share the normalization
+ assert find_homography_lines_dlt(points1.view(1, 3, 2, 2), points2.view(1, 3, 2, 2)).isnan().all().item()
+
@pytest.mark.timeout(120, method="thread")
def test_nonfinite_sample_leaves_batch_intact(self, device, dtype):
points1 = torch.rand(3, 4, 2, device=device, dtype=dtype)