Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

fix(geometry): return max_num instead of NaN for singular H in symmetric_transfer_error (#4227)

abhijeet sharmaa8f1d9e0a8cc
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 0ebe47381..d424d007a 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -448,6 +448,16 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
`N < 3` raised an incidental `IndexError`, while `N >= 3` silently returned `(B, 2)` extents computed from the
wrong vertices. (#4218)
+* Fix `symmetric_transfer_error` returning `NaN` instead of `max_num` for singular homographies.
+ When `safe_inverse_with_mask` flags an input as non-invertible, the unshielded inverse matrix containing
+ non-finite values propagated `NaN` through `oneway_transfer_error` and the arithmetic mask
+ `(there + back) * mask + max_num * (~mask)`, poisoning both the forward error and autograd gradients.
+ Singular rows are now replaced by the identity *before* the differentiable inverse is taken, so the
+ gradients with respect to both the correspondences and `H` itself stay finite (zero on the singular
+ rows), and the final masking uses `torch.where` to cleanly assign `max_num`. Values for invertible
+ homographies are unchanged; for `squared=False` a singular row now scores `max_num` rather than the
+ previous `(max_num + eps).sqrt()`, matching the documented contract. (#4203)
+
* Constructing `ScaleSpaceDetector` with `compile_modules` no longer permanently mutates the process-global
`torch._dynamo.config.capture_dynamic_output_shape_ops` setting. (#4134)
diff --git a/kornia/geometry/homography.py b/kornia/geometry/homography.py
index f66a3c030..df92d3b3c 100644
--- a/kornia/geometry/homography.py
+++ b/kornia/geometry/homography.py
@@ -109,7 +109,8 @@ def symmetric_transfer_error(
eps: Small constant for safe sqrt.
Returns:
- the computed distance with shape :math:`(B, N)`.
+ the computed distance with shape :math:`(B, N)`. Rows whose homography is not invertible
+ score ``max_num``, i.e. ``torch.finfo(pts1.dtype).max``, for both values of ``squared``.
"""
KORNIA_CHECK_SHAPE(H, ["B", "3", "3"])
@@ -122,15 +123,24 @@ def symmetric_transfer_error(
max_num = torch.finfo(pts1.dtype).max
# From Hartley and Zisserman, Symmetric transfer error (4.7)
# dist = \sum_{i} (d(x, H^-1 x')**2 + d(x', Hx)**2)
- H_inv, good_H = safe_inverse_with_mask(H)
-
- there: torch.Tensor = oneway_transfer_error(pts1, pts2, H, True, eps)
- back: torch.Tensor = oneway_transfer_error(pts2, pts1, H_inv, True, eps)
+ # Shield the *input* of the inverse, not its output: ``inv_ex`` backward is
+ # ``-H_inv^T @ grad @ H_inv^T`` over a saved ``H_inv`` full of non-finite values, so masking the
+ # result afterwards still leaves ``0 * nan = nan`` in ``H.grad``. The mask is taken on a detached
+ # copy so it carries no graph, and the differentiable inverse then only ever sees a valid matrix.
+ _, good_H = safe_inverse_with_mask(H.detach())
+ eye = torch.eye(3, device=H.device, dtype=H.dtype).expand_as(H)
+ H_safe = torch.where(good_H.view(-1, 1, 1), H, eye)
+ H_inv_safe, _ = safe_inverse_with_mask(H_safe)
+
+ there: torch.Tensor = oneway_transfer_error(pts1, pts2, H_safe, True, eps)
+ back: torch.Tensor = oneway_transfer_error(pts2, pts1, H_inv_safe, True, eps)
good_H_reshape: torch.Tensor = good_H.view(-1, 1).expand_as(there)
- out = (there + back) * good_H_reshape.to(there.dtype) + max_num * (~good_H_reshape).to(there.dtype)
- if squared:
- return out
- return (out + eps).sqrt()
+
+ out = there + back
+ if not squared:
+ out = (out + eps).sqrt()
+ max_tensor = torch.full_like(out, max_num)
+ return torch.where(good_H_reshape, out, max_tensor)
def line_segment_transfer_error_one_way(
diff --git a/tests/geometry/test_homography.py b/tests/geometry/test_homography.py
index b01395ef5..18707c1fa 100644
--- a/tests/geometry/test_homography.py
+++ b/tests/geometry/test_homography.py
@@ -154,6 +154,56 @@ class TestSymmetricTransferError(BaseTester):
expected = torch.tensor([0.0, 2.0, 10.0], device=device, dtype=dtype)[None]
self.assert_close(symmetric_transfer_error(pts1, pts2, H), expected, atol=1e-4, rtol=1e-4)
+ def test_singular(self, device, dtype):
+ max_num = torch.finfo(dtype).max
+ pts1 = torch.rand(2, 5, 2, device=device, dtype=dtype, requires_grad=True)
+ pts2 = torch.rand(2, 5, 2, device=device, dtype=dtype)
+ H = torch.eye(3, device=device, dtype=dtype).unsqueeze(0).repeat(2, 1, 1)
+ # Make second homography in the batch singular
+ H[1] = 0.0
+ H[1, 0, 0] = 1.0
+
+ for squared in (True, False):
+ err = symmetric_transfer_error(pts1, pts2, H, squared=squared)
+ assert not torch.isnan(err).any()
+ assert torch.isfinite(err[0]).all()
+ expected_singular = torch.full_like(err[1], max_num)
+ self.assert_close(err[1], expected_singular)
+
+ # Check gradient finiteness across mixed batch
+ err = symmetric_transfer_error(pts1, pts2, H)
+ err[0].sum().backward()
+ assert pts1.grad is not None
+ assert not torch.isnan(pts1.grad).any()
+ assert torch.isfinite(pts1.grad[0]).all()
+ assert (pts1.grad[1] == 0.0).all()
+
+ def test_singular_gradient_wrt_homography(self, device, dtype):
+ pts1 = torch.rand(2, 5, 2, device=device, dtype=dtype)
+ pts2 = torch.rand(2, 5, 2, device=device, dtype=dtype)
+ H = torch.eye(3, device=device, dtype=dtype).unsqueeze(0).repeat(2, 1, 1)
+ H[1] = 0.0
+ H[1, 0, 0] = 1.0
+ H.requires_grad_(True)
+
+ symmetric_transfer_error(pts1, pts2, H)[0].sum().backward()
+ assert H.grad is not None
+ assert torch.isfinite(H.grad).all()
+ assert (H.grad[1] == 0.0).all()
+
+ def test_singular_gradient_through_estimated_homography(self, device, dtype):
+ # ``find_homography_dlt_iterated`` differentiates the error through an estimated ``H``, so a
+ # singular intermediate must not poison the gradient of the correspondences that produced it.
+ pts1 = torch.rand(2, 5, 2, device=device, dtype=dtype, requires_grad=True)
+ pts2 = torch.rand(2, 5, 2, device=device, dtype=dtype)
+ eye = torch.eye(3, device=device, dtype=dtype)
+ zeros = torch.zeros(3, 3, device=device, dtype=dtype)
+ H = torch.stack([eye * pts1[0, 0, 0], zeros * pts1[1, 0, 0]])
+
+ symmetric_transfer_error(pts1, pts2, H).sum().backward()
+ assert pts1.grad is not None
+ assert torch.isfinite(pts1.grad).all()
+
class TestFindHomographyDLT(BaseTester):
def test_smoke(self, device, dtype):