Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

fix(geometry): stabilize 3D line fitting across scales (#5498)

Devulapalli Naga Sri Vaishnavi11df867051fc
diff --git a/changelog.d/5498.fixed.md b/changelog.d/5498.fixed.md
new file mode 100644
index 000000000..a16c82558
--- /dev/null
+++ b/changelog.d/5498.fixed.md
@@ -0,0 +1 @@
+`fit_line` now fits points of dimension 3 and higher at large and small coordinate scales, and in float16 and bfloat16, without overflowing the scatter matrix. A fit with float32 points and float16 weights, or float64 points and float32 weights, no longer raises a dtype error: the line comes back in the promoted dtype, as in 2-D.
diff --git a/kornia/geometry/line.py b/kornia/geometry/line.py
index 2ecb71ec4..2b4ce2678 100644
--- a/kornia/geometry/line.py
+++ b/kornia/geometry/line.py
@@ -377,23 +377,40 @@ def fit_line(points: torch.Tensor, weights: Optional[torch.Tensor] = None) -> Pa
return _fit_line_weighted_tls_2d(points, weights)
return _fit_line_tls_2d(points)
+ # The scatter matrix is quadratic in the coordinates. Form it from centred, unit-scale
+ # offsets in a compute dtype before SVD; casting an already-overflowed half matrix cannot recover it.
if weights is not None:
KORNIA_CHECK_IS_TENSOR(weights, "weights must be a tensor")
KORNIA_CHECK_SHAPE(weights, ["B", "N"])
KORNIA_CHECK(points.shape[0] == weights.shape[0])
+ # The output keeps the promoted dtype of points and weights, as in the D = 2 branch.
+ out_dtype = points.dtype if weights is None else torch.promote_types(points.dtype, weights.dtype)
+ compute_dtype = torch.float32 if out_dtype in (torch.float16, torch.bfloat16) else out_dtype
+ work_points = points.to(compute_dtype)
+
+ if weights is not None:
+ work_weights = weights.to(compute_dtype)
+ weight_scale = work_weights.abs().amax(dim=-1, keepdim=True)
+ work_weights = work_weights / torch.where(weight_scale > 0, weight_scale, torch.ones_like(weight_scale))
# Weighted total least squares: centre on the weighted centroid, as the D = 2 branch does. A row whose
# weights sum to 0 keeps the unweighted mean instead of 0 / 0, whose NaN would make the SVD raise.
- w_sum = weights.sum(-1)[..., None, None]
+ w_sum = work_weights.sum(-1)[..., None, None]
has_weight = w_sum != 0
w_sum = torch.where(has_weight, w_sum, torch.ones_like(w_sum))
mean = torch.where(
- has_weight, (weights[..., None] * points).sum(-2, keepdim=True) / w_sum, points.mean(-2, True)
+ has_weight,
+ (work_weights[..., None] * work_points).sum(-2, keepdim=True) / w_sum,
+ work_points.mean(-2, True),
)
- A = points - mean
- A = A.transpose(-2, -1) @ torch.diag_embed(weights) @ A
else:
- mean = points.mean(-2, True)
- A = points - mean
+ mean = work_points.mean(-2, True)
+
+ A = work_points - mean
+ scale = 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
+ else:
A = A.transpose(-2, -1) @ A
# NOTE: not optimal for 2d points, but for now works for other dimensions
@@ -401,7 +418,7 @@ def fit_line(points: torch.Tensor, weights: Optional[torch.Tensor] = None) -> Pa
V = V.transpose(-2, -1)
# the first left eigenvector is the direction on the fitted line
- direction = V[..., 0, :] # BxD
- origin = mean[..., 0, :] # BxD
+ direction = V[..., 0, :].to(out_dtype) # BxD
+ origin = mean[..., 0, :].to(out_dtype) # BxD
return ParametrizedLine(origin, direction)
diff --git a/tests/geometry/test_line.py b/tests/geometry/test_line.py
index b4529de21..8e17d0562 100644
--- a/tests/geometry/test_line.py
+++ b/tests/geometry/test_line.py
@@ -626,6 +626,80 @@ class TestFitLine(BaseTester):
self.assert_close(scaled.direction, line.direction.expand(2, 2))
self.assert_close(scaled.origin / scales[..., 0], line.origin.expand(2, 2))
+ @pytest.mark.parametrize("weighted", [False, True])
+ @pytest.mark.parametrize(
+ "dtype,scales", [(torch.float16, (256.0, 1.0 / 256.0)), (torch.float32, (2.0**64, 2.0**-64))]
+ )
+ def test_fit_line_3d_scale_invariance(self, device, weighted, dtype, scales):
+ points = torch.tensor(
+ [[[10.0, -5.0, 2.0], [11.0, -3.0, 5.0], [12.0, -0.5, 8.0], [13.0, 1.0, 11.0]]],
+ device=device,
+ dtype=dtype,
+ )
+ weights = torch.tensor([[1.0, 2.0, 1.0, 3.0]], device=device, dtype=points.dtype) if weighted else None
+ expected = fit_line(points.float(), None if weights is None else weights.float())
+
+ for scale in scales:
+ actual = fit_line(points * scale, weights)
+ self.assert_close(actual.direction.abs().float(), expected.direction.abs(), atol=1e-3, rtol=1e-3)
+ self.assert_close(actual.origin.float() / scale, expected.origin, atol=1e-3, rtol=1e-3)
+
+ if weighted and dtype == torch.float32:
+ # 2**124 * 13 overflows float32 in sum(w p) unless the weights are normalised first.
+ actual = fit_line(points, weights * 2.0**124)
+ self.assert_close(actual.direction.abs(), expected.direction.abs())
+ self.assert_close(actual.origin, expected.origin)
+
+ def test_fit_line_3d_rows_rescaled_on_their_own(self, device):
+ # Two rows of one batch, at coordinate scales 2**64 and 2**-64 and weight scales 2**100 and 2**-100: a scale
+ # shared by the batch would underflow the second row's scatter matrix, or its weights to a zero sum.
+ points = torch.tensor(
+ [[10.0, -5.0, 2.0], [11.0, -3.0, 5.0], [12.0, -0.5, 8.0], [13.0, 1.0, 11.0]], device=device
+ )
+ weights = torch.tensor([1.0, 2.0, 1.0, 3.0], device=device)
+ expected = fit_line(points[None], weights[None])
+ s = torch.tensor([2.0**64, 2.0**-64], device=device)[:, None, None]
+ ws = torch.tensor([2.0**100, 2.0**-100], device=device)[:, None]
+ actual = fit_line(points * s, weights * ws)
+ self.assert_close(actual.direction.abs(), expected.direction.abs().expand(2, 3))
+ self.assert_close(actual.origin / s[..., 0], expected.origin.expand(2, 3))
+
+ def test_fit_line_3d_weighted_float16_centroid_in_float32(self, device):
+ # 128 float16 points near x = 1000: sum(w p) is 1.3e5, past the float16 maximum 65504, so the weighted
+ # centroid is accumulated in float32. The output stays float16.
+ # The float64 oracle is fitted on the CPU (MPS has no float64) from the float16-rounded points.
+ t = torch.linspace(-1.0, 1.0, 128, dtype=torch.float64)
+ points = torch.stack([1000.0 + 8.0 * t, 4.0 * t, -2.0 * t], -1)[None].half()
+ expected = fit_line(points.double(), torch.ones(1, 128, dtype=torch.float64))
+ actual = fit_line(points.to(device), torch.ones(1, 128, device=device, dtype=torch.float16))
+ assert actual.origin.dtype == actual.direction.dtype == torch.float16
+ self.assert_close(actual.direction.abs().cpu().double(), expected.direction.abs(), atol=1e-3, rtol=1e-3)
+ self.assert_close(actual.origin.cpu().double(), expected.origin, atol=0.5, rtol=1e-3)
+
+ def test_fit_line_3d_float16_centred_in_float32(self, device):
+ # Unweighted float16 points near 1500, where the float16 spacing is 1: their centroid rounded to float16 is
+ # about 0.45 off, which tilts the direction by about 6e-3. The centroid and the offsets are formed in float32.
+ # The float64 oracle is fitted on the CPU (MPS has no float64) from the float16-rounded points.
+ t = torch.linspace(-0.7, 1.0, 64, dtype=torch.float64)
+ points = torch.stack([1500.0 + 6.0 * t, 1500.0 - 3.0 * t, 1500.0 + 2.0 * t], -1)[None].half()
+ expected = fit_line(points.double())
+ actual = fit_line(points.to(device))
+ assert actual.direction.dtype == torch.float16
+ self.assert_close(actual.direction.abs().cpu().double(), expected.direction.abs(), atol=1e-3, rtol=1e-3)
+
+ def test_fit_line_3d_keeps_promoted_dtype(self, device):
+ # Like the D = 2 branch, the line is returned in the promoted dtype of points and weights.
+ points = torch.tensor(
+ [[[0.0, 0.1, 0.3], [1.0, 0.4, 0.2], [2.0, 0.9, 0.1], [3.0, 1.6, 0.4], [4.0, 1.7, 0.3]]], device=device
+ )
+ f16, f32 = torch.float16, torch.float32
+ for pdt, wdt in ((f16, f32), (f32, f16), (f16, f16)):
+ weights = torch.ones(1, 5, device=device, dtype=wdt)
+ line = fit_line(points.to(pdt), weights)
+ expected = torch.promote_types(pdt, wdt)
+ assert line.origin.dtype == line.direction.dtype == expected
+ assert fit_line(points[..., :2].to(pdt), weights).origin.dtype == expected
+
def test_fit_line_2d_degenerate_row_with_checks_disabled(self, device, dtype):
# With checks disabled, as under torch.compile, identical 2-D points are not rejected: their scatter is 0,
# and they get the direction (1, 0) rather than NaN, without touching the other rows.
@@ -644,6 +718,26 @@ class TestFitLine(BaseTester):
if checks_were_enabled:
enable_checks()
+ def test_fit_line_3d_degenerate_row_with_checks_disabled(self, device, dtype):
+ # With checks disabled, as under torch.compile, a row of identical 3-D points has a zero scatter matrix: it
+ # is not divided by its zero scale, whose NaN would make the batched SVD raise for every row.
+ points = torch.tensor(
+ [[[0.0, 0.0, 0.0], [1.0, 3.0, 2.0], [2.0, 5.0, 3.0]], [[1.0, 2.0, 3.0]] * 3], device=device, dtype=dtype
+ )
+ weights = torch.tensor([[1.0, 2.0, 1.0], [1.0, 1.0, 1.0]], device=device, dtype=dtype)
+ checks_were_enabled = are_checks_enabled()
+ disable_checks()
+ try:
+ for w in (None, weights):
+ line = fit_line(points, w)
+ expected = fit_line(points[:1], None if w is None else w[:1])
+ self.assert_close(line.direction[:1].abs(), expected.direction.abs())
+ self.assert_close(line.origin[1], points[1, 0])
+ assert torch.isfinite(line.direction[1]).all()
+ finally:
+ if checks_were_enabled:
+ enable_checks()
+
def test_fit_line_2d_steep_float16_5040(self, device, dtype):
# #5040 (comment): a slope of 1e5 overflowed the float16 slope, giving NaN, or (1, 0) with weights.
x = torch.linspace(0, 1e-3, 20, dtype=torch.float64)