π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
fix(epipolar): weight run_8point's normal matrix without a square root (#4961)
Miral Amin624c2bb21f32
diff --git a/changelog.d/4961.fixed.md b/changelog.d/4961.fixed.mdnew file mode 100644index 000000000..73e7510bf--- /dev/null+++ b/changelog.d/4961.fixed.md@@ -0,0 +1 @@+A weight of exactly 0, the documented way to drop a correspondence, now gets its derivative from above in `find_fundamental`, `run_8point` and the weighted `normalize_points`, and so in the weighted `find_homography_dlt` and `find_homography_lines_dlt`, on every supported torch. `find_fundamental` and `run_8point` used to return `NaN` for it on torch 2.5.1 and 2.9.1, and on torch 2.14 `clamp_min(0)` masked the gradient to 0 in `run_8point` and dropped the Hartley-normalization part of it in `normalize_points`.diff --git a/kornia/geometry/epipolar/fundamental.py b/kornia/geometry/epipolar/fundamental.pyindex e8d320247..963cda64a 100644--- a/kornia/geometry/epipolar/fundamental.py+++ b/kornia/geometry/epipolar/fundamental.py@@ -66,7 +66,10 @@ def normalize_points(# Accumulate in at least float32: in half precision a sum followed by a division rounds twice where# ``mean`` rounds once, and uniform weights would then not reproduce the unweighted statistics.acc_dtype = torch.promote_types(dtype, torch.float32)- positive_weights = weights.to(acc_dtype).clamp_min(0)+ # Negative weights count as zero. ``where`` rather than ``clamp_min(0)``: the clamp's derivative at the bound+ # depends on the torch version (#4229), and a weight of exactly 0 is how a correspondence is dropped.+ positive_weights = weights.to(acc_dtype)+ positive_weights = torch.where(positive_weights < 0, 0.0, positive_weights)total_weight = positive_weights.sum(dim=1, keepdim=True)# A fully de-weighted sample is degenerate; keep its normalization finite and batched.effective_weights = torch.where(total_weight > 0, positive_weights, torch.ones_like(positive_weights))@@ -327,11 +330,16 @@ def run_8point(# Accumulate via einsum (saves bandwidth for huge N)M = torch.einsum("bni,bnj->bij", A, A)else:- w = weights.clamp_min(0)+ # Negative weights count as zero. A weight of exactly 0 is the documented way to drop a correspondence, and+ # its gradient should be the one-sided derivative from above. ``clamp_min(0)`` passes the gradient through+ # at the bound on torch 2.5.1 and 2.9.1 but returns 0 on 2.14 (#4229); ``where`` passes it on every version.+ w = torch.where(weights < 0, 0.0, weights)if N < use_einsum_at_more_than_points:- # Row-scale by sqrt(w) then GEMM- Aw = A * w.unsqueeze(-1).sqrt()- M = Aw.transpose(-2, -1).contiguous() @ Aw+ # Scale one factor by w instead of both by sqrt(w). Both build the same A^T W A, but the derivative+ # of sqrt is unbounded at 0, so a zero weight got a NaN gradient. This form is linear in w, like the+ # einsum branch below.+ Aw = A * w.unsqueeze(-1)+ M = Aw.transpose(-2, -1).contiguous() @ Aelse:# Weighted einsumM = torch.einsum("bni,bnj,bn->bij", A, A, w)diff --git a/tests/geometry/epipolar/test_fundamental.py b/tests/geometry/epipolar/test_fundamental.pyindex d2253637c..38f1c7be7 100644--- a/tests/geometry/epipolar/test_fundamental.py+++ b/tests/geometry/epipolar/test_fundamental.py@@ -331,6 +331,30 @@ class TestFindFundamental(BaseTester):weights = torch.ones(1, 10, device=device, dtype=torch.float64)self.gradcheck(epi.find_fundamental, (points1, points2, weights))+ def test_zero_weight_backward_is_the_one_sided_derivative(self, device, dtype):+ """The gradient of a weight of exactly 0 is finite and is the derivative from above (#4912).++ A zero weight is the documented way to drop a correspondence. ``run_8point`` used to row-scale by+ ``w.sqrt()``, whose derivative is unbounded at 0: the gradient was NaN on torch 2.5.1 and 2.9.1, and 0 on+ 2.14, where ``clamp_min(0)`` masks it at the bound. Both differ from the derivative at a tiny positive weight.+ """+ _skip_half(dtype, _NO_HALF_EIGH)+ two_view = two_view_scene(device, dtype)+ x1 = two_view["x1"]+ x2 = two_view["x2"] + torch.tensor([_NOISE], device=device, dtype=dtype)+ grads = []+ for w3 in (0.0, 1e-6):+ weights = torch.ones(1, x1.shape[1], device=device, dtype=dtype)+ weights[0, 3] = w3+ weights.requires_grad_()+ F_mat = epi.find_fundamental(x1, x2, weights)+ (F_mat * F_mat.detach().sign()).sum().backward()+ grads.append(weights.grad)+ assert torch.isfinite(grads[0]).all()+ tol = {"rtol": 1e-3, "atol": 1e-5} if dtype == torch.float64 else {"rtol": 5e-2, "atol": 1e-4} # f32 eigh: CPU+ assert grads[1][0, 3].abs() > 1e-3 # control: the dropped match moves F, so a zero gradient would be wrong+ self.assert_close(grads[0], grads[1], **tol)+class TestComputeCorrespondEpilines(BaseTester):def test_smoke(self, device, dtype):