π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
fix(depth): make depth_from_plane_equation's grazing-ray guard fire at the singularity (closes #4280) (#4348)
Dipak Chaudharia033f2c033d7
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex d29633bf2..3581fce35 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -374,6 +374,17 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0radicand under the `sqrt`, as `solve_quadratic` in the same module already did. Forward valuesare unchanged. (#4339)+* `depth_from_plane_equation` returns a finite depth for a ray exactly parallel to the plane. The+ near-singular guard was `eps * torch.sign(denom)`, and `torch.sign` is zero at zero, so at the exact+ singularity the epsilon was multiplied away and the division still ran against zero, returning `inf`.+ A grazing ray is not an exotic input: it is every pixel on the horizon of a ground plane. The guard+ now picks its sign with a comparison, which has no such hole and keeps the sign the small non-zero+ denominators already got. `torch.copysign` reads the same but is not exportable, and this function+ is in the documented ONNX export surface, so the comparison form is pinned in+ `tests/onnx/test_export_coverage.py`. The finite-depth promise is bounded by the dtype: the default+ `eps=1e-8` is below float16 resolution, so half-precision callers must pass a representable `eps`.+ (#4280, #4348)+* `RenderingDeFMO` (used by `DeFMO`) no longer crashes on a half-precision forward pass. Its renderingtime-steps (`times`) were a plain Python attribute, not a registered buffer, so `nn.Module.to()` nevermoved it; `forward` re-derived `times`'s device from the input on every call but never its dtype, sodiff --git a/kornia/geometry/depth.py b/kornia/geometry/depth.pyindex 784828d2a..f6132c90a 100644--- a/kornia/geometry/depth.py+++ b/kornia/geometry/depth.py@@ -271,7 +271,17 @@ def depth_from_plane_equation(denom = torch.sum(rays * plane_normals_exp, dim=-1) # (B, N)denom_abs = torch.abs(denom)zero_mask = denom_abs < eps- denom = torch.where(zero_mask, eps * torch.sign(denom), denom)+ # The guard was `eps * sign(denom)`, and `sign` is zero at zero, so the+ # multiplication cancelled the guard at the exact singularity it exists for+ # and a ray parallel to the plane returned inf. Choose the sign with a+ # comparison instead: it has no hole at zero, and keeps the branch's sign+ # for the small non-zero denominators the guard already handled.+ # `torch.copysign` would read the same but is not exportable -- the legacy+ # ONNX exporter has no `aten::copysign` and the dynamo one has no ONNX+ # function for the `prims.signbit` it decomposes to -- and this function is+ # in the documented export surface (docs/export_support/cases_geomB.py).+ signed_eps = torch.where(denom < 0, torch.full_like(denom, -eps), torch.full_like(denom, eps))+ denom = torch.where(zero_mask, signed_eps, denom)# Compute depth from plane equationdepth = plane_offsets / denom # plane_offsets: (B, 1), denom: (B, N) -> depth: (B, N)diff --git a/tests/geometry/test_depth.py b/tests/geometry/test_depth.pyindex 76b87518a..0ef1188d2 100644--- a/tests/geometry/test_depth.py+++ b/tests/geometry/test_depth.py@@ -518,6 +518,55 @@ class TestDepthFromPlaneEquation(BaseTester):# Assert that the computed depth matches the expected depthself.assert_close(depth, depth_expected, rtol=1e-6, atol=1e-6)+ def test_grazing_ray_is_finite(self, device, dtype):+ """A ray exactly parallel to the plane must take the epsilon guard.++ The guard was `eps * sign(denom)`, and `sign` is zero at zero, so at the+ exact singularity the epsilon was multiplied away and the depth came+ back as inf. A grazing ray is not exotic: it is every pixel on the+ horizon of a ground plane.+ """+ camera_matrix = torch.tensor(+ [[100.0, 0.0, 4.0], [0.0, 100.0, 3.0], [0.0, 0.0, 1.0]], device=device, dtype=dtype+ )[None]+ # The principal point's ray is (0, 0, 1); this normal is perpendicular+ # to it, so the ray-plane dot product is exactly zero.+ plane_normals = torch.tensor([[0.0, 1.0, 0.0]], device=device, dtype=dtype)+ plane_offsets = torch.tensor([[2.0]], device=device, dtype=dtype)+ points_uv = torch.tensor([[[4.0, 3.0]]], device=device, dtype=dtype)++ # The default eps=1e-8 is below float16 resolution: it rounds to zero,+ # so `denom_abs < eps` can never hold, and 2/1e-8 is outside float16's+ # finite range anyway. Ask for an epsilon this dtype can represent.+ eps = max(1e-8, float(torch.finfo(dtype).eps))+ depth = kornia.geometry.depth.depth_from_plane_equation(+ plane_normals, plane_offsets, points_uv, camera_matrix, eps=eps+ )+ assert torch.isfinite(depth).all(), f"grazing ray returned {depth.tolist()}"++ def test_small_denominators_keep_their_sign(self, device, dtype):+ """The guard already handled small non-zero denominators; keep that.++ Two rays whose dot products differ only in sign must come back with+ depths of the same magnitude and opposite signs, rather than both+ collapsing onto one branch.+ """+ camera_matrix = torch.eye(3, device=device, dtype=dtype)[None].repeat(2, 1, 1)+ # As above: 1e-8 and eps/4 both round to zero in float16, which would+ # turn this into the grazing-ray case and lose the sign under test.+ eps = max(1e-8, float(torch.finfo(dtype).eps))+ half = eps / 4+ # Ray (0, 0, 1) for both; the normal's z carries the whole dot product.+ plane_normals = torch.tensor([[0.0, 0.0, half], [0.0, 0.0, -half]], device=device, dtype=dtype)+ plane_offsets = torch.tensor([[2.0], [2.0]], device=device, dtype=dtype)+ points_uv = torch.zeros(2, 1, 2, device=device, dtype=dtype)++ depth = kornia.geometry.depth.depth_from_plane_equation(+ plane_normals, plane_offsets, points_uv, camera_matrix, eps=eps+ )+ assert torch.isfinite(depth).all()+ self.assert_close(depth[0], -depth[1])+def test_gradcheck(self, device):B = 2N = 5diff --git a/tests/onnx/test_export_coverage.py b/tests/onnx/test_export_coverage.pyindex 2e6394beb..6ea58b947 100644--- a/tests/onnx/test_export_coverage.py+++ b/tests/onnx/test_export_coverage.py@@ -132,6 +132,21 @@ def _cases():id="distort_points",),pytest.param(_Fn(lambda v: kornia.geometry.liegroup.Se3.exp(v).matrix()), (torch.rand(2, 6),), id="Se3.exp"),+ pytest.param(+ _Fn(kornia.geometry.depth.depth_from_plane_equation),+ # A ray exactly parallel to the plane, so the grazing-ray guard is the+ # branch under export. Selecting the guard's sign with ``torch.copysign``+ # exports through neither path -- the legacy exporter has no+ # ``aten::copysign`` and the dynamo one no ONNX function for the+ # ``prims.signbit`` it decomposes to -- so this pins the comparison form.+ (+ torch.tensor([[0.0, 1.0, 0.0]]),+ torch.tensor([[2.0]]),+ torch.tensor([[[4.0, 3.0]]]),+ torch.tensor([[[100.0, 0.0, 4.0], [0.0, 100.0, 3.0], [0.0, 0.0, 1.0]]]),+ ),+ id="depth_from_plane_equation_grazing",+ ),]