π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
fix(geometry): keep Hyperplane.through gradients finite when p1 - p0 and p2 - p0 are orthogonal and of equal length (#5058)
εΊζ’ηa30540a8422e
diff --git a/changelog.d/5058.fixed.md b/changelog.d/5058.fixed.mdnew file mode 100644index 000000000..16449af61--- /dev/null+++ b/changelog.d/5058.fixed.md@@ -0,0 +1,3 @@+`Hyperplane.through` no longer returns NaN gradients when `p2 - p0` and `p1 - p0` are orthogonal and of equal+length: the SVD fallback, which runs on every row, now sees a constant matrix with distinct singular values in the+rows that take the cross product, so its backward no longer divides by a zero singular-value gap (#5056).diff --git a/kornia/geometry/plane.py b/kornia/geometry/plane.pyindex e94e8203b..55161d0df 100644--- a/kornia/geometry/plane.py+++ b/kornia/geometry/plane.py@@ -196,8 +196,14 @@ class Hyperplane(nn.Module):v1_norm = torch.linalg.vector_norm(v1, dim=-1, keepdim=True)# https://gitlab.com/libeigen/eigen/-/blob/master/Eigen/src/Geometry/Hyperplane.h#L108- def compute_normal_svd(v0: torch.Tensor, v1: torch.Tensor) -> torch.Tensor:+ def compute_normal_svd(v0: torch.Tensor, v1: torch.Tensor, use_svd: torch.Tensor) -> torch.Tensor:m = torch.stack((v0, v1), -2) # Bx2x3+ # The SVD runs on every row and torch.where only zeroes the gradient of the rows that take the cross+ # product. Its backward divides by the difference of the squared singular values, which is 0 when v0 and+ # v1 are orthogonal and of equal length, and 0 * inf is nan (#5056). Rows that do not use the fallback+ # get a constant matrix with distinct singular values instead.+ safe = torch.tensor([[1.0, 0.0, 0.0], [0.0, 2.0, 0.0]], device=m.device, dtype=m.dtype)+ m = torch.where(use_svd[..., None], m, safe)_, _, V = _torch_svd_cast(m) # kornia solution lies in the last rowreturn V[..., :, -1] # Bx3@@ -219,7 +225,7 @@ class Hyperplane(nn.Module):eps = torch.finfo(p0_data.dtype).eps if p0_data.is_floating_point() else 1e-6normal_mask = norm <= v0_norm * v1_norm * epsnorm_safe = torch.where(normal_mask, torch.ones_like(norm), norm)- normal = torch.where(normal_mask, compute_normal_svd(v0, v1), normal / norm_safe)+ normal = torch.where(normal_mask, compute_normal_svd(v0, v1, normal_mask), normal / norm_safe)offset = -batched_dot_product(p0_data, normal)return Hyperplane(_wrap(normal, Vector3), _wrap(offset, Scalar))diff --git a/tests/geometry/test_plane.py b/tests/geometry/test_plane.pyindex 874a23228..3aff15661 100644--- a/tests/geometry/test_plane.py+++ b/tests/geometry/test_plane.py@@ -133,6 +133,39 @@ class TestHyperplane(BaseTester):assert p0.normal.shape == shape or (3,)assert p0.offset.shape == ((*shape,) if shape is not None else ())+ def test_through_orthogonal_equal_length_gradient_5056(self, device, dtype):+ # #5056: the SVD fallback ran on every row and torch.where only zeroed its gradient. When p2 - p0 and+ # p1 - p0 are orthogonal and of equal length the two singular values coincide, the SVD backward divides by+ # their difference, and 0 * inf turned every input gradient into nan although the plane came from the cross+ # product. Row 0: v0 = (2, 1, -2) and v1 = (1, 2, 2), orthogonal and both of length 3. Row 1: the+ # axis-aligned plane z = 1, whose unit edges are orthogonal too. Row 2: a general triangle.+ p0 = torch.tensor([[0.0, 0.0, 0.0], [0.0, 0.0, 1.0], [0.1, 0.2, 0.3]], device=device, dtype=dtype)+ p1 = torch.tensor([[1.0, 2.0, 2.0], [1.0, 0.0, 1.0], [1.5, -0.4, 0.8]], device=device, dtype=dtype)+ p2 = torch.tensor([[2.0, 1.0, -2.0], [0.0, 1.0, 1.0], [-0.7, 1.1, 2.0]], device=device, dtype=dtype)+ for p in (p0, p1, p2):+ p.requires_grad_(True)+ plane = Hyperplane.through(p0, p1, p2)+ expected = torch.tensor([[4.0, -4.0, 2.0], [0.0, 0.0, -1.0]], device=device, dtype=dtype)+ self.assert_close(plane.normal.data[:2], expected / expected.norm(dim=-1, keepdim=True))+ # detect_anomaly also rejects a nan inside the backward that torch.where would discard, so this pins the+ # distinct singular values of the substituted matrix and not only the final gradient.+ with torch.autograd.detect_anomaly():+ (plane.normal.data.sum() + plane.offset.data.sum()).backward()+ for p in (p0, p1, p2):+ assert torch.isfinite(p.grad).all(), p.grad++ def test_through_orthogonal_equal_length_gradcheck_5056(self, device):+ # The three rows of the test above through gradcheck; the two orthogonal rows failed on main with nan.+ p0 = torch.tensor([[0.0, 0.0, 0.0], [0.0, 0.0, 1.0], [0.1, 0.2, 0.3]], device=device, dtype=torch.float64)+ p1 = torch.tensor([[1.0, 2.0, 2.0], [1.0, 0.0, 1.0], [1.5, -0.4, 0.8]], device=device, dtype=torch.float64)+ p2 = torch.tensor([[2.0, 1.0, -2.0], [0.0, 1.0, 1.0], [-0.7, 1.1, 2.0]], device=device, dtype=torch.float64)++ def through(p0: torch.Tensor, p1: torch.Tensor, p2: torch.Tensor) -> torch.Tensor:+ plane = Hyperplane.through(p0, p1, p2)+ return torch.cat([plane.normal.data, plane.offset.data[..., None]], dim=-1)++ self.gradcheck(through, (p0, p1, p2))+def test_through_collinear_points_raises_5041(self, device, dtype):# #5041: collinear (or coincident) points used to take the SVD fallback and return an# arbitrary plane containing the line instead of raising.@@ -346,6 +379,12 @@ class TestHyperplane(BaseTester):norm = torch.linalg.vector_norm(plane.normal.data, dim=-1)self.assert_close(norm, torch.tensor(1.0, device=device, dtype=dtype))+ # The fallback normal is the SVD null vector of the edges, so it is orthogonal to the line through the+ # collinear points. A unit norm alone does not pin that: (0, 0, 1) has one and is 3 off here.+ normal = Hyperplane.through(*collinear).normal.data+ zero = torch.tensor(0.0, device=device, dtype=dtype)+ self.assert_close((normal * (b - a)).sum(-1), zero, rtol=0.0, atol=0.1)+# A degenerate row does not send the other rows of its batch to the fallback.tilted = [torch.tensor([1.0, 0.0, 0.0], device=device, dtype=dtype),