Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

fix(geometry): avoid quadratic SVD storage when fitting planes (#5718)

Anton Soloviev90aae356f16b
diff --git a/changelog.d/5718.fixed.md b/changelog.d/5718.fixed.md
new file mode 100644
index 000000000..03dc02517
--- /dev/null
+++ b/changelog.d/5718.fixed.md
@@ -0,0 +1 @@
+Fit planes with reduced SVD factors, avoiding an unused quadratic-size matrix for large point clouds and their backward passes.
diff --git a/kornia/core/utils.py b/kornia/core/utils.py
index b41ec1292..443957277 100644
--- a/kornia/core/utils.py
+++ b/kornia/core/utils.py
@@ -362,7 +362,7 @@ def _torch_histc_cast(input: torch.Tensor, bins: int, min: Union[float, bool], m
return torch.histc(input.to(dtype), bins, min, max)
-def _torch_svd_cast(input: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
+def _torch_svd_cast(input: torch.Tensor, full_matrices: bool = True) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
"""Make torch.svd work with other than fp32/64.
The function torch.svd is only implemented for fp32/64 which makes
@@ -375,6 +375,7 @@ def _torch_svd_cast(input: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor, to
An MPS input past the shader-compilation ceiling is decomposed on the CPU and moved back, which
is what keeps the batched minimal solvers behind ``RANSAC`` working on Apple silicon.
+ ``full_matrices`` selects full or reduced factors, as in ``torch.linalg.svd``.
"""
if is_mps_tensor_safe(input):
dtype = torch.float32
@@ -393,10 +394,10 @@ def _torch_svd_cast(input: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor, to
if is_mps_tensor_safe(x) and x.numel() >= 8192:
# SVD is per-matrix, so decomposing the whole batch on the CPU gives the same result; the
# casts back to the MPS device keep the autograd graph intact.
- U, S, Vh = torch.linalg.svd(x.cpu())
+ U, S, Vh = torch.linalg.svd(x.cpu(), full_matrices=full_matrices)
out1, out2, out3H = U.to(x.device), S.to(x.device), Vh.to(x.device)
else:
- out1, out2, out3H = torch.linalg.svd(x)
+ out1, out2, out3H = torch.linalg.svd(x, full_matrices=full_matrices)
# Since kornia requires torch>=2.5.1, we can always use .mH
out3 = out3H.mH
return (out1.to(input.dtype), out2.to(input.dtype), out3.to(input.dtype))
diff --git a/kornia/geometry/plane.py b/kornia/geometry/plane.py
index 202b1de38..5c6254c18 100644
--- a/kornia/geometry/plane.py
+++ b/kornia/geometry/plane.py
@@ -304,8 +304,9 @@ def fit_plane(points: Vector3) -> Hyperplane:
mean = points.mean(-2, True)
points_centered = points - mean
- # NOTE: not optimal for 2d points, but for now works for other dimensions
- _, S, V = _torch_svd_cast(_unwrap(points_centered))
+ # With at least three 3D points, reduced SVD retains all right singular vectors while
+ # avoiding an unused N-by-N left factor, including when autograd saves it for backward.
+ _, S, V = _torch_svd_cast(_unwrap(points_centered), full_matrices=False)
# The plane is determined when the centred points have rank 2: the second singular value
# must be nonzero relative to the first, a scale-invariant test that keeps a small or thin
diff --git a/tests/core/test_helpers.py b/tests/core/test_helpers.py
index ab61f1cee..8a08e480a 100644
--- a/tests/core/test_helpers.py
+++ b/tests/core/test_helpers.py
@@ -487,6 +487,21 @@ class TestInverse3x3ClosedForm(BaseTester):
class TestSvdCast:
+ @pytest.mark.parametrize("shape", [(2, 5, 3), (2, 3, 5), (3, 32, 128)])
+ @pytest.mark.parametrize("full_matrices", [False, True])
+ def test_rectangular_factors(self, device, dtype, shape, full_matrices):
+ a = torch.randn(*shape, device=device, dtype=dtype)
+ # The largest batch also exercises the CPU fallback on MPS (8192 input elements).
+ u, s, v = _torch_svd_cast(a, full_matrices=full_matrices)
+ batch, m, n = shape
+ rank = min(m, n)
+ assert u.shape == (batch, m, m if full_matrices else rank)
+ assert s.shape == (batch, rank)
+ assert v.shape == (batch, n, n if full_matrices else rank)
+ assert all(t.dtype == dtype and t.device == a.device for t in (u, s, v))
+ tol_val = 1e-1 if dtype in (torch.float16, torch.bfloat16) else 1e-3
+ assert_close(a, u[..., :rank] @ torch.diag_embed(s) @ v[..., :rank].mT, atol=tol_val, rtol=tol_val)
+
def test_smoke(self, device, dtype):
a = torch.randn(5, 3, 3, device=device, dtype=dtype)
u, s, v = _torch_svd_cast(a)
diff --git a/tests/geometry/test_plane.py b/tests/geometry/test_plane.py
index c1abd4441..55e82f04a 100644
--- a/tests/geometry/test_plane.py
+++ b/tests/geometry/test_plane.py
@@ -56,9 +56,37 @@ class TestFitPlane(BaseTester):
def test_module(self, device, dtype):
pass
- @pytest.mark.skip(reason="not implemented yet")
def test_gradcheck(self, device):
- pass
+ t = torch.linspace(-1.0, 1.0, 6, device=device, dtype=torch.float64)
+ points = torch.stack([t, t**2, 0.2 * t**3], dim=-1)
+
+ def project(x):
+ return fit_plane(x).projection(Vector3(x)).data
+
+ self.gradcheck(project, (points,))
+
+ @pytest.mark.parametrize("n", [64, 256])
+ @pytest.mark.parametrize("batch", [False, True])
+ def test_backward_storage_scales_with_points(self, device, dtype, n, batch):
+ # Fitting an N-by-3 cloud must not retain an unused N-by-N singular-vector matrix.
+ t = torch.linspace(-1.0, 1.0, n, device=device, dtype=dtype)
+ points = torch.stack([t, t**2, 0.2 * t**3], dim=-1)
+ if batch:
+ points = torch.stack([points, points + 1.0])
+ points.requires_grad_()
+ saved_sizes = []
+
+ def pack(tensor):
+ saved_sizes.append(tensor.numel())
+ return tensor
+
+ with torch.autograd.graph.saved_tensors_hooks(pack, lambda tensor: tensor):
+ projection = fit_plane(points).projection(Vector3(points[..., 0, :])).data
+ projection.square().mean().backward()
+
+ assert points.grad is not None
+ assert torch.isfinite(points.grad).all()
+ assert max(saved_sizes) <= 4 * points.numel()
def test_fit_plane_degenerate_raises_5041(self, device, dtype):
# #5041: fewer than three points, collinear points or identical points used to