Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

fix(geometry): reject negative fit_line weights (#5108)

niukanen158315cd84aaa
diff --git a/changelog.d/5088.breaking.md b/changelog.d/5088.breaking.md
index bc760064c..92d2d1a05 100644
--- a/changelog.d/5088.breaking.md
+++ b/changelog.d/5088.breaking.md
@@ -1,6 +1,5 @@
`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)
+the weights are positive on a single point: a point with weight 0 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. A batch is rejected when any of
+its rows is degenerate. The check is skipped under `torch.compile` and after `disable_checks()`, where such a row
+still gets (1, 0, 0) in 3-D, and (1, 0) in 2-D with the total least squares fit of #5094. (#5082)
diff --git a/changelog.d/5108.breaking.md b/changelog.d/5108.breaking.md
new file mode 100644
index 000000000..c930c3f85
--- /dev/null
+++ b/changelog.d/5108.breaking.md
@@ -0,0 +1,9 @@
+`fit_line` now raises `ValueCheckError` when a weight is negative. Such weights passed the check that each row's
+weights sum to a positive value, but a negative weight can make the weighted scatter matrix indefinite, and then the
+2-D and the D β‰₯ 3 fits of the same points disagree: for the four 2-D points of #5106 with weights `(1, -3, 1, 2)`, the
+3-D fit of the points with z = 0 returned the direction (0.79, 0.62, 0), while the 2-D fit returned the vertical
+fallback (0, 1), or, with the total least squares fit of #5094, the perpendicular direction (0.62, -0.79). Any
+negative weight is rejected, also one small enough to leave the scatter without a negative eigenvalue, such as -0.01
+among weights of 1. A weight of 0 or -0.0 is still accepted and drops its point. A batch is rejected when any of its rows
+has a negative weight. The check is skipped under `torch.compile` and after `disable_checks()`, where negative
+weights are still fitted. (#5106)
diff --git a/kornia/geometry/line.py b/kornia/geometry/line.py
index 8a6ccd568..fa98481e7 100644
--- a/kornia/geometry/line.py
+++ b/kornia/geometry/line.py
@@ -280,7 +280,9 @@ def _reject_degenerate_line(points: torch.Tensor, weights: Optional[torch.Tensor
leaves 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,
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.
+ positive weight, compared with the point of largest weight. Every weight must be
+ non-negative: a negative weight can make the weighted scatter indefinite, and then the
+ 2-D and the D >= 3 branches disagree.
The value checks are skipped under ``torch.compile``/export, where they would be a
data-dependent branch, and by ``disable_checks()``, like every kornia value check.
@@ -306,6 +308,10 @@ def _reject_degenerate_line(points: torch.Tensor, weights: Optional[torch.Tensor
"fit_line requires at least two distinct points with positive weight; the points with positive "
"weight are all identical."
)
+ if bool((weights < 0).any()):
+ raise ValueCheckError(
+ "fit_line requires non-negative weights; a negative weight can make the weighted scatter indefinite."
+ )
def fit_line(points: torch.Tensor, weights: Optional[torch.Tensor] = None) -> ParametrizedLine:
@@ -327,8 +333,8 @@ def fit_line(points: torch.Tensor, weights: Optional[torch.Tensor] = None) -> Pa
Raises:
ValueCheckError: if the points do not determine a line β€” fewer than two points,
- all points identical, or (with weights) a zero weight sum or all points with
- positive weight identical.
+ all points identical, or (with weights) a zero weight sum, a negative weight, 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.py
index e6680fa83..072f13119 100644
--- a/tests/geometry/test_line.py
+++ b/tests/geometry/test_line.py
@@ -664,6 +664,32 @@ class TestFitLine(BaseTester):
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_fit_line_negative_weights_raise_5106(self, device, dtype):
+ # #5106: a negative weight passes the weight-sum check, but it can make the weighted scatter indefinite. The
+ # D >= 3 branch then takes the axis of the largest |eigenvalue| and a 2-D total least squares fit the axis of
+ # the largest eigenvalue: 90 degrees apart for weights (1, -3, 1, 2) on these points. Any negative weight is
+ # rejected, also one such as -0.01 that leaves the scatter without a negative eigenvalue.
+ points_2d = torch.tensor([[[0.0, 0.0], [1.0, 0.4], [2.5, 0.9], [3.0, 2.0]]], device=device, dtype=dtype)
+ points_3d = torch.nn.functional.pad(points_2d, (0, 1))
+ ones = torch.ones(1, 4, device=device, dtype=dtype)
+ for points in (points_2d, points_3d):
+ for w in ([1.0, -3.0, 1.0, 2.0], [1.0, -0.01, 1.0, 1.0]):
+ weights = torch.tensor([w], device=device, dtype=dtype)
+ with pytest.raises(ValueCheckError, match="non-negative weights"):
+ fit_line(points, weights)
+ # a batch is rejected as a whole when one of its rows has a negative weight
+ with pytest.raises(ValueCheckError, match="non-negative weights"):
+ fit_line(torch.cat([points, points]), torch.cat([ones, weights]))
+
+ # A zero weight, +0.0 or -0.0, is not negative: it drops its point.
+ expected = fit_line(points[:, [0, 2, 3]])
+ for zero in (0.0, -0.0):
+ line = fit_line(points, torch.tensor([[1.0, zero, 1.0, 1.0]], device=device, dtype=dtype))
+ self.assert_close(line.origin, expected.origin)
+ self.assert_close(
+ (line.direction * expected.direction).sum(-1).abs(), torch.ones(1, 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.