π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
fix(geometry): reject fit_line weights that are positive on a single point (#5088)
Mohammad Hijjawiccece34df0c2
diff --git a/changelog.d/5088.breaking.md b/changelog.d/5088.breaking.mdnew file mode 100644index 000000000..bc760064c--- /dev/null+++ b/changelog.d/5088.breaking.md@@ -0,0 +1,6 @@+`fit_line` now raises `ValueCheckError` when the points with positive weight are all the same point, for example when+the weights are positive on a single point: a point whose weight is 0 or negative does not count, so such a row does+not determine a line. It used to return the fallback direction (0, 1) in 2-D and (1, 0, 0) in 3-D, except that with a+negative weight on another point, as in weights `(2, -1, 0)`, the 3-D fit returned the line through the two points.+A batch is rejected when any of its rows is degenerate. The check is skipped under `torch.compile` and after+`disable_checks()`, where the previous results come back. (#5082)diff --git a/kornia/geometry/line.py b/kornia/geometry/line.pyindex dd8307a75..da7c61b86 100644--- a/kornia/geometry/line.py+++ b/kornia/geometry/line.py@@ -262,7 +262,9 @@ def _reject_degenerate_line(points: torch.Tensor, weights: Optional[torch.TensorA line needs at least two points that are not all identical. Comparing every point withthe first one is exact at any scale; comparing with the mean is not, because its roundingleaves a nonzero residual for identical points such as three copies of (0.1, 0.7). With- weights, the weighted mean is undefined unless the weight sum of every row is positive.+ weights, the weighted mean is undefined unless the weight sum of every row is positive,+ and a point with weight 0 does not count, so the same rule applies to the points with+ positive weight, compared with the point of largest weight.The value checks are skipped under ``torch.compile``/export, where they would be adata-dependent branch, and by ``disable_checks()``, like every kornia value check.@@ -280,6 +282,14 @@ def _reject_degenerate_line(points: torch.Tensor, weights: Optional[torch.Tensorraise ValueCheckError("fit_line requires a positive sum of weights; the given weights do not sum to a positive value.")+ # A point with weight 0 does not count: some point with positive weight must differ from the point of+ # largest weight, which is positive once the weight sum is.+ ref = points.gather(-2, weights.argmax(-1)[:, None, None].expand(-1, 1, points.shape[-1]))+ if not bool(((points != ref).any(-1) & (weights > 0)).any(-1).all()):+ raise ValueCheckError(+ "fit_line requires at least two distinct points with positive weight; the points with positive "+ "weight are all identical."+ )def fit_line(points: torch.Tensor, weights: Optional[torch.Tensor] = None) -> ParametrizedLine:@@ -296,7 +306,8 @@ def fit_line(points: torch.Tensor, weights: Optional[torch.Tensor] = None) -> PaRaises:ValueCheckError: if the points do not determine a line β fewer than two points,- all points identical, or (with weights) a zero weight sum.+ all points identical, or (with weights) a zero weight sum or all points with+ positive weight identical.Example:>>> points = torch.rand(2, 10, 3)diff --git a/tests/geometry/test_line.py b/tests/geometry/test_line.pyindex d12b5003d..80f30dd61 100644--- a/tests/geometry/test_line.py+++ b/tests/geometry/test_line.py@@ -493,6 +493,41 @@ class TestFitLine(BaseTester):with pytest.raises(TypeCheckError, match="weights must be a tensor"):fit_line(points_3d, [[1.0, 1.0, 1.0]])+ def test_fit_line_weighted_identical_points_raise_5082(self, device, dtype):+ # #5082: a point with weight 0 does not count, so weights that are positive on a single point, or only on+ # copies of one point, leave nothing to fit. Such a row used to return the fallback direction, (0, 1) in 2-D+ # and (1, 0, 0) in 3-D, whatever the points were.+ points_3d = torch.tensor([[[0.0, 0.0, 0.3], [1.0, 0.4, -0.2], [2.5, 0.9, 0.1]]], device=device, dtype=dtype)+ copies_3d = torch.tensor([[[1.0, 2.0, 3.0], [0.0, 5.0, -1.0], [1.0, 2.0, 3.0]]], device=device, dtype=dtype)+ single = ([1.0, 0.0, 0.0], [0.0, 0.0, 2.0], [-1.0, 0.0, 2.0])+ for points in (points_3d[..., :2], points_3d):+ for w in single:+ weights = torch.tensor([w], device=device, dtype=dtype)+ with pytest.raises(ValueCheckError, match="two distinct points with positive weight"):+ fit_line(points, weights)+ # a batch is rejected as a whole when one of its rows is degenerate+ with pytest.raises(ValueCheckError, match="two distinct points with positive weight"):+ fit_line(torch.cat([points, points]), torch.cat([torch.ones_like(weights), weights]))+ # two distinct points with positive weight determine the line through them+ line = fit_line(points, torch.tensor([[1.0, 0.0, 1.0]], device=device, dtype=dtype))+ expected = fit_line(points[:, [0, 2]])+ self.assert_close(line.origin, expected.origin)+ self.assert_close(+ (line.direction * expected.direction).sum(-1).abs(), torch.ones(1, device=device, dtype=dtype)+ )++ for points in (copies_3d[..., :2], copies_3d):+ with pytest.raises(ValueCheckError, match="two distinct points with positive weight"):+ fit_line(points, torch.tensor([[1.0, 0.0, 3.0]], device=device, dtype=dtype))+ fit_line(points, torch.tensor([[1.0, 0.5, 3.0]], device=device, dtype=dtype))++ # Two points with positive weight that differ in one coordinate only are distinct: they give the vertical+ # line in 2-D and the line along z in 3-D.+ axis_3d = torch.tensor([[[1.0, 2.0, 3.0], [9.0, 9.0, 9.0], [1.0, 2.0, 4.0]]], device=device, dtype=dtype)+ for points, direction in ((axis_3d[..., [0, 2]], [0.0, 1.0]), (axis_3d, [0.0, 0.0, 1.0])):+ line = fit_line(points, torch.tensor([[1.0, 0.0, 1.0]], device=device, dtype=dtype))+ self.assert_close(line.direction.abs(), torch.tensor([direction], device=device, dtype=dtype))+def test_dynamo_skips_degenerate_checks(self, device, dtype, torch_optimizer):# The degeneracy checks depend on tensor values, so they are skipped under torch.compile: a compiled call# on identical points returns what an eager call returns with checks disabled.