Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

fix(geometry): compute the Hyperplane.through cross product in float32 for half-precision inputs (#5104)

εŒΊζ’“ηa39ca02942fa
diff --git a/changelog.d/5104.breaking.md b/changelog.d/5104.breaking.md
new file mode 100644
index 000000000..a33db1107
--- /dev/null
+++ b/changelog.d/5104.breaking.md
@@ -0,0 +1,9 @@
+`Hyperplane.through` now takes the edges and the cross product of float16 and bfloat16 points in float32 and casts the
+unit normal back, so the normal keeps the `(p2 - p0) x (p1 - p0)` orientation. Previously, in float16, the cross
+product of a small valid triangle underflowed (edges of 1e-4 give 1e-8, below the smallest subnormal) and that of a
+large one overflowed (edges of 300 give 9e4, above 65504), and the triangle took the SVD fallback, whose sign is
+arbitrary: the right triangle at the origin with legs of 1e-4 or 300 came back as `(0, 0, 1)` instead of
+`(0, 0, -1)`, which flips `signed_distance` for every point. Triangles with edges near the float16 limit were rejected
+as collinear, and an edge longer than 65504 gave nan. Without the value checks, as under `torch.compile`, a float16 or
+bfloat16 triangle now takes the SVD fallback at the float32 threshold, so a thin one keeps its orientation there too.
+The collinearity check keeps the tolerance of the input dtype. float32 and float64 results are unchanged (#5064).
diff --git a/kornia/geometry/plane.py b/kornia/geometry/plane.py
index 55161d0df..c9ec09970 100644
--- a/kornia/geometry/plane.py
+++ b/kornia/geometry/plane.py
@@ -188,7 +188,14 @@ class Hyperplane(nn.Module):
KORNIA_CHECK(p0_data.shape == p1_data.shape)
KORNIA_CHECK(p1_data.shape == p2_data.shape)
- v0, v1 = (p2_data - p0_data), (p1_data - p0_data)
+ # Half-precision points are converted to float32 before the edges are taken. In float16 the cross product of
+ # a small triangle underflows (edges of 1e-4 give 1e-8, below the smallest subnormal 6e-8), that of a large
+ # one overflows (edges of 300 give 9e4, above the largest float16 65504), and so can the edges themselves.
+ # The triangle then took the SVD fallback, whose sign is arbitrary, or came back as nan (#5064). The unit
+ # normal is cast back to the input dtype.
+ work_dtype = torch.float32 if p0_data.dtype in (torch.float16, torch.bfloat16) else p0_data.dtype
+ p0_work = p0_data.to(work_dtype)
+ v0, v1 = (p2_data.to(work_dtype) - p0_work), (p1_data.to(work_dtype) - p0_work)
normal = torch.linalg.cross(v0, v1, dim=-1)
norm = torch.linalg.vector_norm(normal, dim=-1, keepdim=True)
@@ -210,22 +217,24 @@ class Hyperplane(nn.Module):
# Collinear or coincident points do not determine a plane: raise instead of taking the SVD
# fallback, which returns an arbitrary valid-looking normal. The test is on the rank of
# (v0, v1), as in fit_plane, from singular values that ``_torch_linalg_svdvals`` computes in
- # float32 or float64. It is relative and scaled by the input's machine epsilon, so a small
- # or thin valid triangle keeps working (also one whose cross product underflows in
- # float16), and it does not depend on the fallback threshold below.
+ # float32 or float64. It is relative and scaled by the machine epsilon of the input, not of
+ # the float32 edges of a half-precision input, since the points carry the input's rounding.
+ # So a small or thin valid triangle keeps working, points that are collinear up to that
+ # rounding are rejected, and the test does not depend on the fallback threshold below.
# Skipped under torch.compile/export and by disable_checks(), like every kornia value check.
if not torch.jit.is_scripting() and not is_compiling() and are_checks_enabled():
sv = _torch_linalg_svdvals(torch.stack((_unwrap(v0), _unwrap(v1)), -2))
- if bool((sv[..., 1] <= sv[..., 0] * _rank_tolerance(sv.dtype)).any()):
+ if bool((sv[..., 1] <= sv[..., 0] * _rank_tolerance(p0_data.dtype)).any()):
raise ValueCheckError(
"Hyperplane.through requires three points that are not collinear; "
"the given points do not determine a plane."
)
- eps = torch.finfo(p0_data.dtype).eps if p0_data.is_floating_point() else 1e-6
+ eps = torch.finfo(work_dtype).eps if v0.is_floating_point() else 1e-6
normal_mask = norm <= v0_norm * v1_norm * eps
norm_safe = torch.where(normal_mask, torch.ones_like(norm), norm)
normal = torch.where(normal_mask, compute_normal_svd(v0, v1, normal_mask), normal / norm_safe)
+ normal = normal.to(p0_data.dtype)
offset = -batched_dot_product(p0_data, normal)
return Hyperplane(_wrap(normal, Vector3), _wrap(offset, Scalar))
diff --git a/tests/geometry/test_plane.py b/tests/geometry/test_plane.py
index 3aff15661..3b61cef4f 100644
--- a/tests/geometry/test_plane.py
+++ b/tests/geometry/test_plane.py
@@ -184,14 +184,56 @@ class TestHyperplane(BaseTester):
Hyperplane.through(torch.stack([p0, a]), torch.stack([p1, b]), torch.stack([p2, c]))
@pytest.mark.parametrize("scale", (1.0, 1e-4))
- def test_through_small_valid_triangle_still_fits(self, device, dtype, scale):
- # A small triangle is not collinear. In float16 the cross product of the 1e-4 triangle underflows to 0
- # (1e-8 is below the smallest subnormal), so it reaches the SVD fallback, which must not reject it.
+ def test_through_small_valid_triangle_keeps_orientation_5064(self, device, dtype, scale):
+ # A small triangle is not collinear, and it keeps the (p2 - p0) x (p1 - p0) orientation. In float16 the
+ # cross product of the 1e-4 triangle underflows to 0 (1e-8 is below the smallest subnormal), so it took the
+ # SVD fallback and came back as +z (#5064); the cross product is now computed in float32.
p0 = torch.tensor([0.0, 0.0, 0.0], device=device, dtype=dtype)
p1 = torch.tensor([scale, 0.0, 0.0], device=device, dtype=dtype)
p2 = torch.tensor([0.0, scale, 0.0], device=device, dtype=dtype)
plane = Hyperplane.through(p0, p1, p2)
- self.assert_close(plane.normal.unwrap().abs(), torch.tensor([0.0, 0.0, 1.0], device=device, dtype=dtype))
+ self.assert_close(plane.normal.unwrap(), torch.tensor([0.0, 0.0, -1.0], device=device, dtype=dtype))
+
+ @pytest.mark.parametrize("size", (300.0, 4e4))
+ def test_through_large_triangle_keeps_orientation_5064(self, device, dtype, size):
+ # The normal is (p2 - p0) x (p1 - p0) = (size, size, 0) x (2 size, 0, 0) = (0, 0, -2 size^2). In float16 that
+ # overflows for size 300 (-1.8e5 is beyond 65504), and for size 4e4 the edge p1 - p0 = 8e4 overflows too: the
+ # first took the SVD fallback and came back as +z, the second as nan. Both are now computed in float32.
+ p0 = torch.tensor([-size, 0.0, 1.0], device=device, dtype=dtype)
+ p1 = torch.tensor([size, 0.0, 1.0], device=device, dtype=dtype)
+ p2 = torch.tensor([0.0, size, 1.0], device=device, dtype=dtype)
+ plane = Hyperplane.through(p0, p1, p2)
+ self.assert_close(plane.normal.unwrap(), torch.tensor([0.0, 0.0, -1.0], device=device, dtype=dtype))
+ self.assert_close(plane.offset.data, torch.tensor(1.0, device=device, dtype=dtype))
+
+ def test_through_points_collinear_up_to_rounding_raise(self, device, dtype):
+ # The origin, (0.1, 0.2, 0.3) and (0.3, 0.6, 0.9) are collinear, but their rounded coordinates are not
+ # exactly. The collinearity tolerance scales with the input dtype, also for a float16 or bfloat16 input whose
+ # edges are taken in float32, so through() rejects these points in every dtype, as fit_plane does, instead
+ # of returning a normal fitted to the rounding error ((0.89, -0.45, 0) in float16).
+ points = torch.tensor([[0.0, 0.0, 0.0], [0.1, 0.2, 0.3], [0.3, 0.6, 0.9]], device=device, dtype=dtype)
+ with pytest.raises(ValueCheckError, match="not collinear"):
+ Hyperplane.through(points[0], points[1], points[2])
+ with pytest.raises(ValueCheckError, match="not collinear"):
+ fit_plane(points)
+
+ def test_through_thin_triangle_keeps_orientation_without_checks(self, device, dtype):
+ # Without the value checks, as under torch.compile, only the fallback threshold decides. For a float16 or
+ # bfloat16 input it uses the float32 epsilon, so this triangle, whose cross product is 2^-11 of the product of
+ # its edge lengths, below the float16 and bfloat16 epsilons, keeps the (p2 - p0) x (p1 - p0) orientation in
+ # every dtype instead of taking the SVD fallback. Both point orders are checked: the normal follows the order.
+ checks_were_enabled = are_checks_enabled()
+ disable_checks()
+ try:
+ p0 = torch.tensor([0.0, 0.0, 0.0], device=device, dtype=dtype)
+ p1 = torch.tensor([1.0, 0.0, 0.0], device=device, dtype=dtype)
+ p2 = torch.tensor([0.5, 2.0**-12, 0.0], device=device, dtype=dtype)
+ expected = torch.tensor([0.0, 0.0, -1.0], device=device, dtype=dtype)
+ self.assert_close(Hyperplane.through(p0, p1, p2).normal.unwrap(), expected)
+ self.assert_close(Hyperplane.through(p0, p2, p1).normal.unwrap(), -expected)
+ finally:
+ if checks_were_enabled:
+ enable_checks()
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
@@ -350,9 +392,8 @@ class TestHyperplane(BaseTester):
def test_through_batched_threshold_is_per_row(self, device, dtype):
# The fallback threshold compares each row's cross product with that row's own edge lengths. Measured
# against the whole batch, the 1e-4 triangle would fall below it next to the 1e4 one and take the SVD
- # fallback, whose sign differs from the cross product's for this triangle.
- if dtype in (torch.float16, torch.bfloat16):
- pytest.skip("the 1e4 triangle's cross product overflows float16")
+ # fallback, whose sign differs from the cross product's for this triangle. The 1e4 triangle's cross product
+ # overflows float16, so half-precision points are taken to float32 first (#5064).
base = [
torch.tensor([1.0, 0.0, 0.0], device=device, dtype=dtype),
torch.tensor([0.0, 2.0, 0.0], device=device, dtype=dtype),