Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

fix(geometry): keep half-precision plane fits finite (#5783)

A Aswanth Rajed6169e026d5
diff --git a/changelog.d/5783.fixed.md b/changelog.d/5783.fixed.md
new file mode 100644
index 000000000..69673f4ca
--- /dev/null
+++ b/changelog.d/5783.fixed.md
@@ -0,0 +1 @@
+`fit_plane` now fits float16 and bfloat16 points in float32 and returns the plane in the input dtype. It used to fit them in their own dtype: a float16 point cloud in millimetres, such as a depth frame, was rejected as collinear because the largest singular value, which grows with the square root of the number of points times their spread, overflowed float16 (#5821), and half-precision offsets lost bits to cancellation (float16 returned -18.5 and bfloat16 -18.0 for an offset of -18.475). The collinearity test keeps the input dtype's tolerance but now applies it to the given points rather than to their half-precision centring, so a near-collinear half-precision set that this rounding let through now raises `ValueCheckError`. float32 and float64 results are unchanged.
diff --git a/kornia/geometry/plane.py b/kornia/geometry/plane.py
index c345509f9..108c1878e 100644
--- a/kornia/geometry/plane.py
+++ b/kornia/geometry/plane.py
@@ -324,17 +324,23 @@ def fit_plane(points: Vector3) -> Hyperplane:
"fit_plane requires at least three points that are not identical; the given points are all identical."
)
- mean = points.mean(-2, True)
- points_centered = points - mean
+ points_data = _unwrap(points)
+ # Half inputs are fitted in float32, which holds every half-precision value exactly, and only the plane is
+ # cast back. The first singular value grows with the square root of the number of points times their spread,
+ # so it overflows float16 for a point cloud in millimetres, and the offset's products cancel in half precision.
+ half = points_data.dtype in (torch.float16, torch.bfloat16)
+ points_work = points_data.float() if half else points_data
+ mean = points_work.mean(-2, True)
+ points_centered = points_work - mean
# With at least three 3D points, reduced SVD retains all right singular vectors while
# avoiding an unused N-by-N left factor, including when autograd saves it for backward.
- _, S, V = _torch_svd_cast(_unwrap(points_centered), full_matrices=False)
+ _, S, V = _torch_svd_cast(points_centered, full_matrices=False)
# The plane is determined when the centred points have rank 2: the second singular value
# must be nonzero relative to the first, a scale-invariant test that keeps a small or thin
- # valid set working. ``_torch_svd_cast`` also covers float16 and bfloat16.
- if checks and not bool((S[..., 1] > S[..., 0] * _rank_tolerance(S.dtype)).all()):
+ # valid set working. Keep the input-dtype tolerance even when the fit uses higher precision.
+ if checks and not bool((S[..., 1] > S[..., 0] * _rank_tolerance(points_data.dtype)).all()):
raise ValueCheckError(
"fit_plane requires points that are not collinear; the given points do not determine a plane."
)
@@ -342,5 +348,8 @@ def fit_plane(points: Vector3) -> Hyperplane:
# the first left eigenvector is the direction on the fited line
direction = V[..., :, -1] # BxD
origin = mean[..., 0, :] # BxD
+ if half:
+ offset = -batched_dot_product(direction, origin)
+ return Hyperplane(Vector3(direction.to(points_data.dtype)), Scalar(offset.to(points_data.dtype)))
return Hyperplane.from_vector(Vector3(direction), Vector3(origin))
diff --git a/tests/geometry/test_plane.py b/tests/geometry/test_plane.py
index 31cb4b8c3..5621960ad 100644
--- a/tests/geometry/test_plane.py
+++ b/tests/geometry/test_plane.py
@@ -119,6 +119,83 @@ class TestFitPlane(BaseTester):
assert plane.normal.shape == (3,)
assert torch.isfinite(plane.normal.unwrap()).all()
+ @pytest.mark.parametrize("wrapped", [False, True])
+ @pytest.mark.parametrize("batched", [False, True])
+ @pytest.mark.parametrize("large", [False, True])
+ def test_fit_plane_preserves_plane_at_large_scale(self, device, dtype, wrapped, batched, large):
+ scale = 4e4 if large else 1.0
+ # The rectangle lies in z=1 at either scale. Its first singular value is twice its width scale, which
+ # overflowed float16 at 4e4 once cast back (#5821); the other dtypes are controls.
+ points = (
+ torch.tensor(
+ [[-1.0, -0.5, 0.0], [-1.0, 0.5, 0.0], [1.0, -0.5, 0.0], [1.0, 0.5, 0.0]], device=device, dtype=dtype
+ )
+ * scale
+ )
+ points[:, 2] = 1.0
+ expected = torch.tensor([0.0, 0.0, 1.0], device=device, dtype=dtype)
+ if batched:
+ points = torch.stack([points, points[:, [2, 0, 1]]])
+ expected = torch.stack([expected, expected[[2, 0, 1]]])
+ points.requires_grad_()
+ plane = fit_plane(Vector3(points) if wrapped else points)
+ assert plane.normal.data.dtype == dtype
+ assert plane.normal.data.device == device
+ assert plane.offset.data.dtype == dtype
+ assert plane.offset.data.device == device
+ self.assert_close(plane.normal.data.abs(), expected)
+ self.assert_close(plane.offset.data.abs(), torch.ones(points.shape[:-2], device=device, dtype=dtype))
+ (plane.normal.data.sum() + plane.offset.data.sum()).backward()
+ assert points.grad is not None
+ assert torch.isfinite(points.grad).all()
+
+ def test_fit_plane_rank_tolerance_uses_input_dtype(self, device, dtype):
+ height = 4 * torch.finfo(dtype).eps
+ points = torch.tensor([[0.0, 0.0, 0.0], [1.0, 0.0, 0.0], [0.5, height, 0.0]], device=device, dtype=dtype)
+ with pytest.raises(ValueCheckError, match="not collinear"):
+ fit_plane(points)
+
+ @pytest.mark.parametrize("wrapped", [False, True])
+ @pytest.mark.parametrize("batched", [False, True])
+ def test_fit_plane_oblique_offset(self, device, dtype, wrapped, batched):
+ # The corners satisfy x + y - z = 32 exactly in every dtype. Half-precision products of the offset
+ # cancel: float16 returned -18.5 and bfloat16 -18.0 instead of -32 / sqrt(3) = -18.475.
+ points = torch.tensor(
+ [[256.0, 256.0, 480.0], [256.0, 512.0, 736.0], [512.0, 256.0, 736.0], [512.0, 512.0, 992.0]],
+ device=device,
+ dtype=dtype,
+ )
+ expected_normal = points.new_tensor([1.0, 1.0, -1.0]) / 3**0.5
+ expected_offset = points.new_tensor(-32.0 / 3**0.5)
+ if batched:
+ points = torch.stack([points, points[:, [2, 0, 1]]])
+ expected_normal = torch.stack([expected_normal, expected_normal[[2, 0, 1]]])
+ expected_offset = expected_offset.expand(2)
+ points.requires_grad_()
+ plane = fit_plane(Vector3(points) if wrapped else points)
+ sign = (plane.normal.data * expected_normal).sum(-1).sign()
+ self.assert_close(plane.normal.data * sign[..., None], expected_normal)
+ self.assert_close(plane.offset.data * sign, expected_offset)
+ plane.offset.data.sum().backward()
+ assert points.grad is not None
+ assert torch.isfinite(points.grad).all()
+
+ def test_dynamo_large_scale(self, device, dtype, torch_optimizer):
+ scale = 4e4
+ points = torch.tensor(
+ [[-1.0, -0.5, 1.0], [-1.0, 0.5, 1.0], [1.0, -0.5, 1.0], [1.0, 0.5, 1.0]], device=device, dtype=dtype
+ )
+ points[:, :2] *= scale
+
+ def op(x):
+ plane = fit_plane(x)
+ return plane.normal.data, plane.offset.data
+
+ actual = torch_optimizer(op)(points)
+ expected = op(points)
+ self.assert_close(actual[0].abs(), expected[0].abs())
+ self.assert_close(actual[1].abs(), expected[1].abs())
+
# TODO: implement the rest of methods
class TestHyperplane(BaseTester):