π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
fix(geometry): keep weighted 2D line fits finite across weight scales (#5641)
A Aswanth Raj10dee360ac7a
diff --git a/changelog.d/5641.fixed.md b/changelog.d/5641.fixed.mdnew file mode 100644index 000000000..3eaa5e33a--- /dev/null+++ b/changelog.d/5641.fixed.md@@ -0,0 +1,7 @@+`fit_line` with weights now fits 2-D points at any weight scale, and float16 points whose weighted sums exceed the+float16 range, as the D β₯ 3 branch already did: each row's weights are divided by their largest value, and float16 and+bfloat16 fits are computed in float32. Previously, float32 weights of 5e36, and 256 float16 points near x = 1500 with+unit weights, gave an `inf` or NaN origin and direction, and float32 weights of 1e30 or 1e-30 gave a finite line whose+direction had a zero gradient with respect to the points. The returned line keeps the dtype promoted from points and+weights. Other float32 and float64 fits change only by rounding, and are bit-identical when the largest weight of each+row is a power of two, as with unit weights; float16 and bfloat16 fits can change in the last bits.diff --git a/kornia/geometry/line.py b/kornia/geometry/line.pyindex 2b4ce2678..77b63331f 100644--- a/kornia/geometry/line.py+++ b/kornia/geometry/line.py@@ -274,6 +274,14 @@ def _fit_line_weighted_tls_2d(points: torch.Tensor, weights: torch.Tensor) -> PaCentred relative to the first point, like :func:`_fit_line_tls_2d`."""+ out_dtype = torch.promote_types(points.dtype, weights.dtype)+ compute_dtype = torch.float32 if out_dtype in (torch.float16, torch.bfloat16) else out_dtype+ points, weights = points.to(compute_dtype), weights.to(compute_dtype)+ # Uniform weight scaling preserves the centroid and direction. Normalise before the sums,+ # and accumulate half-precision inputs in float32, as in the D >= 3 branch.+ weight_scale = weights.abs().amax(dim=-1, keepdim=True)+ weights = weights / torch.where(weight_scale > 0, weight_scale, torch.ones_like(weight_scale))+x0 = points[..., :1, 0] # (B, 1)y0 = points[..., :1, 1] # (B, 1)x = points[..., 0] - x0 # (B, N)@@ -284,7 +292,7 @@ def _fit_line_weighted_tls_2d(points: torch.Tensor, weights: torch.Tensor) -> Padirection = _tls_direction_2d(x - x_mean, y - y_mean, weights)origin = torch.cat([x0 + x_mean, y0 + y_mean], dim=-1)- return ParametrizedLine(origin, direction)+ return ParametrizedLine(origin.to(out_dtype), direction.to(out_dtype))def _reject_degenerate_line(points: torch.Tensor, weights: Optional[torch.Tensor]) -> None:diff --git a/tests/geometry/test_line.py b/tests/geometry/test_line.pyindex 8e17d0562..78f159be9 100644--- a/tests/geometry/test_line.py+++ b/tests/geometry/test_line.py@@ -577,6 +577,59 @@ class TestFitLine(BaseTester):self.assert_close(line.direction, expected_direction)self.assert_close(line.origin, torch.stack([x_mean, y_mean])[None])+ def test_fit_line_2d_weight_scale_invariance(self, device, dtype):+ # Scaling all weights in a row changes neither its centroid nor the TLS direction.+ points = torch.tensor([[[2.0, 4.0], [4.0, 8.0], [6.0, 12.0]]], device=device, dtype=dtype)+ weights = torch.tensor([[1.0, 2.0, 1.0]], device=device, dtype=dtype)+ # The largest weight is 2**(e - 1), so the weight sum 2**e overflows the dtype: normalising by the sum would not+ # help, normalising by the largest weight does.+ exponent = math.frexp(torch.finfo(dtype).max)[1] - 2+ scales = torch.tensor([2.0**exponent, 2.0**-exponent], device=device, dtype=dtype)[:, None]++ line = fit_line(points.expand(2, 3, 2), weights * scales)++ expected_origin = torch.tensor([[4.0, 8.0]], device=device, dtype=dtype).expand(2, 2)+ expected_direction = torch.tensor([[1.0 / math.sqrt(5), 2.0 / math.sqrt(5)]], device=device, dtype=dtype)+ self.assert_close(line.origin, expected_origin)+ self.assert_close(line.direction, expected_direction.expand(2, 2))+ assert line.origin.dtype == line.direction.dtype == dtype++ def test_fit_line_weighted_2d_float16_centroid(self, device):+ # Unit weights still overflow sum(w * offsets) for 256 float16 points in pixel coordinates.+ t = torch.arange(256, device=device, dtype=torch.float16)+ points = torch.stack([1000.0 + 4.0 * t, -500.0 + 2.0 * t], -1)[None]+ line = fit_line(points, torch.ones(1, 256, device=device, dtype=torch.float16))++ self.assert_close(line.origin, torch.tensor([[1510.0, -245.0]], device=device, dtype=torch.float16))+ direction = torch.tensor([[2.0 / math.sqrt(5), 1.0 / math.sqrt(5)]], device=device, dtype=torch.float16)+ self.assert_close(line.direction, direction)+ assert line.origin.dtype == line.direction.dtype == torch.float16++ 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)++ def op(points, weights):+ return fit_line(points, weights).projection(points[:, 0])++ self.gradcheck(op, (points, weights), requires_grad=(True, True))++ @pytest.mark.parametrize("scale", [2.0**100, 2.0**-100], ids=["2**100", "2**-100"])+ def test_fit_line_weighted_2d_gradient_weight_scale_invariance(self, device, scale):+ # Scaling the weights changes neither the fit nor its gradient. Unnormalised float32 weights at these scales+ # gave a finite direction whose gradient with respect to the points was exactly zero.+ 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)++ def direction_grad(weights):+ points_ = points.clone().requires_grad_(True)+ fit_line(points_, weights).direction.sum().backward()+ return points_.grad++ expected = direction_grad(weights)+ assert expected.abs().amax() > 0.1+ self.assert_close(direction_grad(weights * scale), expected)+@pytest.mark.parametrize("weighted", [False, True])def test_fit_line_2d_exactly_vertical_is_0_1_5040(self, device, dtype, weighted):# #5040: the direction of an exactly vertical line is (0, 1). Rounding in the mean used to leave a tiny