π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
fix(geometry): avoid quadratic weight storage in line fitting (#5685)
Anton Soloviev3711d19994ba
diff --git a/changelog.d/5685.fixed.md b/changelog.d/5685.fixed.mdnew file mode 100644index 000000000..360446768--- /dev/null+++ b/changelog.d/5685.fixed.md@@ -0,0 +1 @@+Weighted `geometry.fit_line` in three or more dimensions no longer allocates a quadratic-size diagonal weight matrix, reducing memory use for large point sets.diff --git a/kornia/geometry/line.py b/kornia/geometry/line.pyindex 041b3c023..5876b1d23 100644--- a/kornia/geometry/line.py+++ b/kornia/geometry/line.py@@ -422,7 +422,8 @@ def fit_line(points: torch.Tensor, weights: Optional[torch.Tensor] = None) -> Pascale = A.abs().amax(dim=(-2, -1), keepdim=True)A = A / torch.where(scale > 0, scale, torch.ones_like(scale))if weights is not None:- A = A.transpose(-2, -1) @ torch.diag_embed(work_weights) @ A+ # Scale the columns directly instead of allocating an N-by-N diagonal weight matrix.+ A = (A.transpose(-2, -1) * work_weights[..., None, :]) @ Aelse:A = A.transpose(-2, -1) @ Adiff --git a/tests/geometry/test_line.py b/tests/geometry/test_line.pyindex c34f8eda0..60de64dd0 100644--- a/tests/geometry/test_line.py+++ b/tests/geometry/test_line.py@@ -972,7 +972,65 @@ class TestFitLine(BaseTester):pts = torch.rand(2, 5, dim, device=device)weights = torch.rand(2, 5, device=device)- self.gradcheck(proxy_func, (pts, weights), requires_grad=(True, False))+ self.gradcheck(proxy_func, (pts, weights), requires_grad=(True, True))++ @pytest.mark.parametrize("dim", [3, 4])+ def test_weighted_fit_saves_linear_storage(self, device, dtype, dim):+ # A differentiable fit needs storage proportional to the points, not an N-by-N weight matrix.+ points = torch.rand(2, 128, dim, device=device, dtype=dtype, requires_grad=True)+ weights = torch.rand(2, 128, device=device, dtype=dtype, requires_grad=True)+ saved_sizes = []++ def pack(tensor):+ saved_sizes.append(tensor.numel())+ return tensor++ with torch.autograd.graph.saved_tensors_hooks(pack, lambda tensor: tensor):+ line = fit_line(points, weights)+ loss = line.projection(points[:, 0]).square().sum()+ loss.backward()++ assert max(saved_sizes) <= 8 * points.numel()+ assert torch.isfinite(points.grad).all()+ assert torch.isfinite(weights.grad).all()++ def test_dynamo_weighted_fit_3d(self, device, dtype, torch_optimizer):+ points = torch.rand(2, 32, 3, device=device, dtype=dtype)+ weights = torch.rand(2, 32, device=device, dtype=dtype)++ def op(points, weights):+ line = fit_line(points, weights)+ return line.projection(points[:, 0])++ self.assert_close(torch_optimizer(op)(points, weights), op(points, weights))++ @pytest.mark.parametrize("dim", [3, 4])+ def test_fit_line_weighted_principal_axis_of_weighted_scatter(self, device, dtype, dim):+ # For D >= 3 the direction is the principal axis of sum_i w_i (p_i - c)(p_i - c)^T about the weighted+ # centroid c. The weights are uneven, so a scatter weighted by w**2, sqrt(w) or 1 tilts the axis by 0.08 or+ # more in some component. The float64 oracle is computed on the CPU (MPS has no float64) from the+ # dtype-rounded inputs; the sign of a D >= 3 direction is unspecified.+ points = torch.tensor(+ [+ [0.0, 0.0, 0.3, 1.0],+ [1.0, 0.4, -0.2, 0.5],+ [2.5, 0.9, 0.1, -0.4],+ [3.0, 1.6, 0.4, 0.2],+ [4.2, 1.7, -0.3, 0.9],+ [0.5, 2.0, 1.0, -1.0],+ ],+ device=device,+ dtype=dtype,+ )[None, :, :dim]+ weights = torch.tensor([[0.25, 1.0, 1.0, 1.0, 0.25, 8.0]], device=device, dtype=dtype)++ p, w = points[0].cpu().double(), weights[0].cpu().double()+ centred = p - (w[:, None] * p).sum(0) / w.sum()+ axis = torch.linalg.eigh((w[:, None] * centred).T @ centred).eigenvectors[:, -1]++ direction = fit_line(points, weights).direction[0]+ axis = axis * torch.sign(direction.cpu().double() @ axis)+ self.assert_close(direction, axis.to(device=device, dtype=dtype))@pytest.mark.skip(reason="not implemented yet")def test_cardinality(self, device, dtype):