Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

fix(geometry): homography SVD solvers give NaN, not uninitialized memory, for non-finite systems (#6103)

Dmytro Mishkinccb15b5c1120
diff --git a/changelog.d/6103.fixed.md b/changelog.d/6103.fixed.md
new file mode 100644
index 000000000..91d8f6612
--- /dev/null
+++ b/changelog.d/6103.fixed.md
@@ -0,0 +1,8 @@
+`find_homography_lines_dlt`, `find_homography_lines_dlt_iterated` and `find_homography_dlt(..., solver="svd")`
+return NaN for a batch element whose DLT system is not finite, such as one with a NaN or infinite point, endpoint or
+weight, and the usual homography for the rest of the batch, on CPU and CUDA, eager and compiled. On CPU, one such
+element made `torch.linalg.svd` raise for the whole batch; the solvers then warned "SVD did not converge" and returned
+uninitialized memory from `torch.empty`. Every homography of the batch was then garbage that changed from call to call
+and had no gradient. Compiled and exported programs raised `LinAlgError` instead. On CUDA, a non-finite weight could
+give a finite but meaningless homography. If the SVD fails on a finite system, the whole batch is now NaN, with the
+same warning.
diff --git a/kornia/geometry/homography.py b/kornia/geometry/homography.py
index 26d630b55..fa1076063 100644
--- a/kornia/geometry/homography.py
+++ b/kornia/geometry/homography.py
@@ -519,7 +519,11 @@ def find_homography_dlt(
Returns:
- the computed homography matrix with shape :math:`(B, 3, 3)`.
+ the computed homography matrix with shape :math:`(B, 3, 3)`. A batch element whose weighted DLT system is
+ not finite, because a weight or a point is not finite (zero-weight points included) or an entry overflows,
+ is NaN for both solvers and on every device; the other elements are unaffected. If the SVD of
+ ``solver="svd"`` fails to converge on a finite system, the whole batch is NaN and a ``RuntimeWarning`` is
+ issued.
"""
device, dtype = _extract_device_dtype([points1, points2])
@@ -588,6 +592,27 @@ def _rank8_null_vector(normal: torch.Tensor) -> torch.Tensor:
return torch.where(rank8[:, None], null, torch.full_like(null, float("nan")))
+def _svd_null_vector(normal: torch.Tensor) -> torch.Tensor:
+ """Right singular vector of the smallest singular value of each ``(B, 9, 9)`` matrix, NaN where it is undefined.
+
+ A matrix with a non-finite entry has no null vector, and the backends disagree on what its SVD returns:
+ CPU ``torch.linalg.svd`` raises for the whole batch, while CUDA can return a finite vector, such as a basis
+ vector, for a matrix with a single NaN entry. Such matrices are decomposed as zeros and their vectors are
+ replaced by NaN, so on every backend the finite matrices keep their vectors and the others are NaN, as with
+ the LU solver (#4770). If the SVD still fails on a finite batch, every vector is NaN and a warning is issued;
+ there is no partial result to keep.
+ """
+ finite = normal.isfinite().flatten(1).all(-1)
+ safe = torch.where(finite[:, None, None], normal, torch.zeros_like(normal))
+ try:
+ _, _, V = _torch_svd_cast(safe)
+ except RuntimeError:
+ warnings.warn("SVD did not converge", RuntimeWarning, stacklevel=1)
+ return torch.full_like(normal[..., 0], float("nan"))
+ null = V[..., -1]
+ return torch.where(finite[:, None], null, torch.full_like(null, float("nan")))
+
+
def _homography_from_dlt_system(
A: torch.Tensor,
weights: Optional[torch.Tensor],
@@ -620,12 +645,7 @@ def _homography_from_dlt_system(
A = A.transpose(-2, -1) @ A if w_full is None else (A.transpose(-2, -1) * w_full) @ A
if solver == "svd":
- try:
- _, _, V = _torch_svd_cast(A)
- except RuntimeError:
- warnings.warn("SVD did not converge", RuntimeWarning, stacklevel=1)
- return torch.empty((A.shape[0], 3, 3), device=device, dtype=dtype)
- H = V[..., -1].view(-1, 3, 3)
+ H = _svd_null_vector(A).view(-1, 3, 3)
elif solver == "lu":
if not minimal_lu:
B = torch.ones(A.shape[0], A.shape[1], device=device, dtype=dtype)
@@ -706,7 +726,8 @@ def find_homography_dlt_iterated(
n_iter: number of solves, including the initial one.
Returns:
- the computed homography matrix with shape :math:`(B, 3, 3)`.
+ the computed homography matrix with shape :math:`(B, 3, 3)`, NaN for a batch element as in
+ :func:`find_homography_dlt`.
"""
device, dtype = _extract_device_dtype([points1, points2])
@@ -794,7 +815,10 @@ def find_homography_lines_dlt(
Zero-weight segments are excluded from Hartley normalization.
Returns:
- the computed homography matrix with shape :math:`(B, 3, 3)`.
+ the computed homography matrix with shape :math:`(B, 3, 3)`. A batch element whose weighted DLT system is
+ not finite, because a weight or an endpoint is not finite (zero-weight segments included) or an entry
+ overflows, is NaN on every device; the other elements are unaffected. If the SVD fails to converge on a
+ finite system, the whole batch is NaN and a ``RuntimeWarning`` is issued.
Raises:
AssertionError: if fewer than four segments are given, as in :func:`find_homography_dlt`.
@@ -811,7 +835,8 @@ def find_homography_lines_dlt(
# homography, or NaN for none at all (#5991).
if N < 4:
raise AssertionError(f"find_homography_lines_dlt needs at least 4 line segments, got {N}: {ls1.shape}")
- device, dtype = _extract_device_dtype([ls1, ls2])
+ # Raises unless both segment sets share a device and a dtype.
+ _extract_device_dtype([ls1, ls2])
points1 = ls1.reshape(BS, 2 * N, 2)
points2 = ls2.reshape(BS, 2 * N, 2)
@@ -856,13 +881,7 @@ def find_homography_lines_dlt(
w_full = weights.repeat_interleave(2, dim=1).unsqueeze(1)
A = (A.transpose(-2, -1) * w_full) @ A
- try:
- _, _, V = _torch_svd_cast(A)
- except RuntimeError:
- warnings.warn("SVD did not converge", RuntimeWarning, stacklevel=1)
- return torch.empty((points1_norm.size(0), 3, 3), device=device, dtype=dtype)
-
- H = V[..., -1].view(-1, 3, 3)
+ H = _svd_null_vector(A).view(-1, 3, 3)
H = _inverse_normalization(transform2) @ (H @ transform1)
return normalize_transformation(H, eps)
@@ -889,7 +908,10 @@ def find_homography_lines_dlt_iterated(
n_iter: number of solves, including the initial one.
Returns:
- the computed homography matrix with shape :math:`(B, 3, 3)`.
+ the computed homography matrix with shape :math:`(B, 3, 3)`. A batch element is NaN when one of its
+ solves is, as in :func:`find_homography_lines_dlt`. In float16, segments with coordinates in the hundreds
+ of pixels overflow the re-weighting distances of :func:`line_segment_transfer_error_one_way` and give NaN
+ this way.
Raises:
AssertionError: if fewer than four segments are given, as in :func:`find_homography_lines_dlt`.
diff --git a/tests/geometry/test_homography.py b/tests/geometry/test_homography.py
index d5b6fe54b..e8b57809d 100644
--- a/tests/geometry/test_homography.py
+++ b/tests/geometry/test_homography.py
@@ -49,6 +49,21 @@ from kornia.geometry.linalg import transform_points
from testing.base import BaseTester
from testing.geometry.create import create_random_homography
+# A mild warp of the unit square and spread-out points and segments in it. Their exact correspondences give DLT
+# systems whose smallest non-zero singular value is 0.32 (points) and 0.27 (segments) of the largest, so a batched
+# fit matches the unbatched one in every dtype and on every device.
+_EXACT_H = torch.tensor([[1.05, 0.03, 0.1], [-0.02, 0.98, 0.05], [0.01, 0.02, 1.0]])
+_SPREAD_POINTS = torch.tensor([[0.1, 0.1], [0.9, 0.15], [0.85, 0.9], [0.15, 0.8]])
+_SPREAD_SEGMENTS = torch.tensor(
+ [
+ [[0.1, 0.1], [0.9, 0.2]],
+ [[0.2, 0.8], [0.8, 0.9]],
+ [[0.1, 0.9], [0.3, 0.1]],
+ [[0.7, 0.1], [0.9, 0.9]],
+ [[0.4, 0.3], [0.6, 0.7]],
+ ]
+)
+
class TestSampleValidation(BaseTester):
def test_good(self, device, dtype):
@@ -633,17 +648,50 @@ class TestFindHomographyDLT(BaseTester):
assert find_homography_lines_dlt(segments1, segments2).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)
- points2 = torch.rand(3, 4, 2, device=device, dtype=dtype)
- weights = torch.ones(3, 4, device=device, dtype=dtype)
- expected = find_homography_dlt(points1[:1], points2[:1], weights[:1])
+ @pytest.mark.parametrize("solver", ["lu", "svd"])
+ def test_nonfinite_sample_leaves_batch_intact(self, device, dtype, solver):
+ # With ``solver="svd"``, CPU's SVD raised for the whole batch, which then held uninitialized memory, and
+ # CUDA's gave the NaN-weight sample a finite homography.
+ points1 = _SPREAD_POINTS.to(device, dtype).repeat(4, 1, 1)
+ points2 = transform_points(_EXACT_H.to(device, dtype)[None], points1)
+ weights = torch.ones(4, 4, device=device, dtype=dtype)
+ expected = find_homography_dlt(points1[:1], points2[:1], weights[:1], solver)
points1[1, 0, 0] = float("nan")
weights[2, 1] = float("inf")
- H = find_homography_dlt(points1, points2, weights)
+ weights[3, 2] = float("nan")
+ H = find_homography_dlt(points1, points2, weights, solver)
assert H[1:].isnan().all().item()
self.assert_close(H[:1], expected)
+ def test_svd_failure_gives_nan(self, device, dtype, monkeypatch):
+ # An SVD that fails on finite input leaves no homography: NaN and a warning, not uninitialized memory.
+ def fail(*args, **kwargs):
+ raise RuntimeError("linalg.svd: The algorithm failed to converge")
+
+ monkeypatch.setattr("kornia.geometry.homography._torch_svd_cast", fail)
+ points1 = torch.rand(2, 6, 2, device=device, dtype=dtype)
+ points2 = torch.rand(2, 6, 2, device=device, dtype=dtype)
+ with pytest.warns(RuntimeWarning, match="SVD did not converge"):
+ H = find_homography_dlt(points1, points2, solver="svd")
+ assert H.shape == (2, 3, 3)
+ assert H.isnan().all().item()
+
+ def test_dynamo_nonfinite_sample(self, device, dtype, torch_optimizer):
+ # A compiled program has no Python ``except``: CPU's SVD raised out of it for a non-finite sample.
+ points1 = _SPREAD_SEGMENTS.to(device, dtype).reshape(1, 10, 2).repeat(3, 1, 1)
+ points2 = transform_points(_EXACT_H.to(device, dtype)[None], points1)
+ weights = torch.ones(3, 10, device=device, dtype=dtype)
+ points1[1, 0, 0] = float("nan")
+ weights[2, 1] = float("inf")
+
+ def op(p1: torch.Tensor, p2: torch.Tensor, w: torch.Tensor) -> torch.Tensor:
+ return find_homography_dlt(p1, p2, w, solver="svd")
+
+ actual, expected = torch_optimizer(op)(points1, points2, weights), op(points1, points2, weights)
+ assert expected[1:].isnan().all().item()
+ assert torch.equal(actual.isnan(), expected.isnan())
+ self.assert_close(actual[:1], expected[:1])
+
@pytest.mark.parametrize("batch_size, num_points", [(1, 4), (2, 5), (3, 6)])
def test_shape(self, batch_size, num_points, device, dtype):
B, N = batch_size, num_points
@@ -870,6 +918,64 @@ class TestFindHomographyFromLinesDLT(BaseTester):
ls2 = torch.stack([points2st, points2end], dim=2)
H = find_homography_lines_dlt(ls1, ls2, weights)
assert H.shape == (1, 3, 3)
+ # CPU's SVD raised on the NaN, and the result used to be uninitialized memory.
+ assert H.isnan().all().item()
+
+ @staticmethod
+ def _segments_with_nonfinite_samples(device, dtype):
+ # Sample 0 is exact and finite; 1 has a NaN endpoint, 2 an infinite weight and 3 a NaN weight.
+ ls1 = _SPREAD_SEGMENTS.to(device, dtype).repeat(4, 1, 1, 1)
+ ls2 = transform_points(_EXACT_H.to(device, dtype)[None], ls1.flatten(1, 2)).view_as(ls1)
+ weights = torch.ones(4, 5, device=device, dtype=dtype)
+ ls1[1, 0, 1, 0] = float("nan")
+ weights[2, 1] = float("inf")
+ weights[3, 2] = float("nan")
+ return ls1, ls2, weights
+
+ @pytest.mark.parametrize("solve", [find_homography_lines_dlt, find_homography_lines_dlt_iterated])
+ def test_nonfinite_sample_leaves_batch_intact(self, solve, device, dtype):
+ # CPU's SVD raised for the whole batch, which then held uninitialized memory, and CUDA's gave the
+ # samples with a non-finite weight finite homographies.
+ ls1, ls2, weights = self._segments_with_nonfinite_samples(device, dtype)
+ expected = solve(ls1[:1], ls2[:1], weights[:1])
+ H = solve(ls1, ls2, weights)
+ assert H[1:].isnan().all().item()
+ self.assert_close(H[:1], expected)
+
+ def test_nonfinite_sample_keeps_the_gradient_of_the_others(self, device):
+ # The uninitialized result had no autograd graph, so the finite sample had no gradient either.
+ if device.type == "mps":
+ pytest.skip("float64 is not supported on MPS")
+ ls1, ls2, weights = self._segments_with_nonfinite_samples(device, torch.float64)
+ ls1.requires_grad_(True)
+ weights.requires_grad_(True)
+ find_homography_lines_dlt(ls1, ls2, weights)[0].sum().backward()
+ ls1_0, weights_0 = ls1[:1].detach().requires_grad_(True), weights[:1].detach().requires_grad_(True)
+ find_homography_lines_dlt(ls1_0, ls2[:1], weights_0).sum().backward()
+ self.assert_close(ls1.grad[:1], ls1_0.grad)
+ self.assert_close(weights.grad[:1], weights_0.grad)
+
+ def test_svd_failure_gives_nan(self, device, dtype, monkeypatch):
+ # An SVD that fails on finite input leaves no homography: NaN and a warning, not uninitialized memory.
+ def fail(*args, **kwargs):
+ raise RuntimeError("linalg.svd: The algorithm failed to converge")
+
+ monkeypatch.setattr("kornia.geometry.homography._torch_svd_cast", fail)
+ ls1 = torch.rand(2, 5, 2, 2, device=device, dtype=dtype)
+ ls2 = torch.rand(2, 5, 2, 2, device=device, dtype=dtype)
+ with pytest.warns(RuntimeWarning, match="SVD did not converge"):
+ H = find_homography_lines_dlt(ls1, ls2)
+ assert H.shape == (2, 3, 3)
+ assert H.isnan().all().item()
+
+ @pytest.mark.parametrize("solve", [find_homography_lines_dlt, find_homography_lines_dlt_iterated])
+ def test_dynamo_nonfinite_sample(self, solve, device, dtype, torch_optimizer):
+ # A compiled program has no Python ``except``: CPU's SVD raised out of it for a non-finite sample.
+ ls1, ls2, weights = self._segments_with_nonfinite_samples(device, dtype)
+ actual, expected = torch_optimizer(solve)(ls1, ls2, weights), solve(ls1, ls2, weights)
+ assert expected[1:].isnan().all().item()
+ assert torch.equal(actual.isnan(), expected.isnan())
+ self.assert_close(actual[:1], expected[:1])
@pytest.mark.parametrize("batch_size, num_points", [(1, 4), (2, 5), (3, 6)])
def test_shape(self, batch_size, num_points, device, dtype):