Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

fix(geometry): prevent overflow in unweighted half-precision 2D line fits (#5684)

Anton Soloviev72d507d2b936
diff --git a/changelog.d/5684.fixed.md b/changelog.d/5684.fixed.md
new file mode 100644
index 000000000..e61a0cda2
--- /dev/null
+++ b/changelog.d/5684.fixed.md
@@ -0,0 +1 @@
+Unweighted 2D `fit_line` now fits float16 and bfloat16 points in float32, as the weighted 2D and D >= 3 paths already did, and returns the origin and direction in the input dtype. In float16 it used to return an infinite origin and a NaN direction when two coordinates differed by more than 65504 (for example points at x = -40000 and x = 40000), and a horizontal or NaN direction when a set of more than 65504 points overflowed the second moments. bfloat16 results change only by rounding.
diff --git a/kornia/geometry/line.py b/kornia/geometry/line.py
index 77b63331f..041b3c023 100644
--- a/kornia/geometry/line.py
+++ b/kornia/geometry/line.py
@@ -257,6 +257,11 @@ def _fit_line_tls_2d(points: torch.Tensor) -> ParametrizedLine:
after centring, whatever the rounding of the mean. An exactly vertical set then has ``sxy = +0`` and gets the
direction ``(0, 1)``; the float32 rounding of ``pi / 2`` can leave an x component of 1.2e-7.
"""
+ dtype = points.dtype
+ # Promote before subtracting or accumulating: finite half coordinates can have an overflowing difference,
+ # and even unit-scale second moments overflow float16 for a sufficiently large point set.
+ if dtype in (torch.float16, torch.bfloat16):
+ points = points.float()
x0 = points[..., :1, 0] # (B, 1)
y0 = points[..., :1, 1] # (B, 1)
x = points[..., 0] - x0 # (B, N)
@@ -266,7 +271,7 @@ def _fit_line_tls_2d(points: torch.Tensor) -> ParametrizedLine:
direction = _tls_direction_2d(x - x_mean, y - y_mean, None)
origin = torch.cat([x0 + x_mean, y0 + y_mean], dim=-1)
- return ParametrizedLine(origin, direction)
+ return ParametrizedLine(origin.to(dtype), direction.to(dtype))
def _fit_line_weighted_tls_2d(points: torch.Tensor, weights: torch.Tensor) -> ParametrizedLine:
diff --git a/tests/geometry/test_line.py b/tests/geometry/test_line.py
index 78f159be9..c34f8eda0 100644
--- a/tests/geometry/test_line.py
+++ b/tests/geometry/test_line.py
@@ -605,6 +605,42 @@ class TestFitLine(BaseTester):
self.assert_close(line.direction, direction)
assert line.origin.dtype == line.direction.dtype == torch.float16
+ def test_fit_line_2d_large_offsets(self, device, dtype):
+ # All coordinates fit in float16, but subtracting the first point does not.
+ points = torch.tensor([[[-40000.0, -20000.0], [0.0, 0.0], [40000.0, 20000.0]]], device=device, dtype=dtype)
+ points.requires_grad_(True)
+ line = fit_line(points)
+
+ self.assert_close(line.origin, torch.zeros(1, 2, device=device, dtype=dtype))
+ expected = torch.tensor([[2.0 / math.sqrt(5), 1.0 / math.sqrt(5)]], device=device, dtype=dtype)
+ self.assert_close(line.direction, expected)
+ assert line.origin.dtype == line.direction.dtype == dtype
+ (line.origin.sum() + line.direction.sum()).backward()
+ assert torch.isfinite(points.grad).all()
+
+ def test_fit_line_2d_repeated_points(self, device, dtype):
+ # Repeating the same two points cannot change their line. The scaled x second moment is
+ # 65536 here, which overflows float16 and used to turn this into a horizontal direction.
+ points = torch.tensor([[[-2.0, -1.0], [2.0, 1.0]]], device=device, dtype=dtype).repeat(1, 32768, 1)
+ line = fit_line(points)
+
+ self.assert_close(line.origin, torch.zeros(1, 2, device=device, dtype=dtype))
+ expected = torch.tensor([[2.0 / math.sqrt(5), 1.0 / math.sqrt(5)]], device=device, dtype=dtype)
+ self.assert_close(line.direction, expected)
+ assert line.origin.dtype == line.direction.dtype == dtype
+
+ def test_dynamo_fit_line_2d_large_offsets(self, device, dtype, torch_optimizer):
+ points = torch.tensor([[[-40000.0, -20000.0], [0.0, 0.0], [40000.0, 20000.0]]], device=device, dtype=dtype)
+
+ def op(points):
+ line = fit_line(points)
+ return line.origin, line.direction
+
+ origin, direction = torch_optimizer(op)(points)
+ self.assert_close(origin, torch.zeros(1, 2, device=device, dtype=dtype))
+ expected = torch.tensor([[2.0 / math.sqrt(5), 1.0 / math.sqrt(5)]], device=device, dtype=dtype)
+ self.assert_close(direction, expected)
+
def test_fit_line_weighted_2d_gradcheck(self, device):
points = torch.tensor([[[0.0, 0.1], [1.0, 0.4], [2.0, 0.9], [3.0, 1.2]]], device=device)
weights = torch.tensor([[1.0, 2.0, 1.0, 3.0]], device=device)