π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
fix: prevent float16 overflow in fundamental_from_projections (#5097)
Arc00000722d7b11373fd
diff --git a/changelog.d/5097.breaking.md b/changelog.d/5097.breaking.mdnew file mode 100644index 000000000..e7f0803ea--- /dev/null+++ b/changelog.d/5097.breaking.md@@ -0,0 +1,6 @@+`fundamental_from_projections` now divides a float16 result by its largest absolute entry before casting it back+to float16, so pixel-unit projection matrices no longer give `inf` (#4877). It used to cast the unnormalised+float32 determinants back, which overflowed for ordinary cameras (5 of 9 entries `inf` for focal lengths of+700-800 px) and flushed projection matrices with entries of order `1e-2` to all zeros. float16 results that used+to be finite now differ from before by a positive scale factor, up to rounding; an all-zero result stays zero.+float32, float64 and bfloat16 results are unchanged.diff --git a/kornia/geometry/epipolar/fundamental.py b/kornia/geometry/epipolar/fundamental.pyindex 5ee57e6be..4e7354be2 100644--- a/kornia/geometry/epipolar/fundamental.py+++ b/kornia/geometry/epipolar/fundamental.py@@ -742,8 +742,10 @@ def fundamental_from_projections(P1: torch.Tensor, P2: torch.Tensor) -> torch.Te- The result satisfies :math:`x_2^\top F x_1 = 0` for ``(P1, P2)``, the order of :func:`find_fundamental`.It is not normalised, and for ``P1 = [I | 0]``, ``P2 = [R | t]`` it is the negative of:func:`~kornia.geometry.epipolar.essential_from_Rt` for the same motion.- - Known defects: float16 overflows to ``inf`` for pixel-unit projection matrices- (`#4877 <https://github.com/kornia/kornia/issues/4877>`_).+ - float16 and bfloat16 inputs are computed in float32. A float16 ``F`` is then divided by its largest+ absolute entry before the cast back, because pixel-unit projection matrices give entries of order ``1e10``,+ above float16's maximum of 65504; an all-zero ``F`` (coincident camera centres) stays zero. bfloat16 has+ float32's exponent range and is cast back unnormalised.Args:P1: The projection matrix from first camera with shape :math:`(*, 3, 4)`.@@ -792,4 +794,11 @@ def fundamental_from_projections(P1: torch.Tensor, P2: torch.Tensor) -> torch.Tedim=1,)- return F_vec.view(*P1.shape[:-2], 3, 3).to(input_dtype)+ F = F_vec.view(*P1.shape[:-2], 3, 3)++ if input_dtype == torch.float16:+ # F is defined up to scale: divide by the largest absolute entry so it fits float16; F = 0 stays 0.+ scale = F.abs().amax(dim=(-2, -1), keepdim=True)+ F = F / torch.where(scale > 0, scale, torch.ones_like(scale))++ return F.to(input_dtype)diff --git a/testing/half_precision_xfails/cpu_float16.txt b/testing/half_precision_xfails/cpu_float16.txtindex 822ba9a0a..13d68a950 100644--- a/testing/half_precision_xfails/cpu_float16.txt+++ b/testing/half_precision_xfails/cpu_float16.txt@@ -226,7 +226,6 @@ call builtins.NotImplementedError tests/geometry/epipolar/test_essential.py::Tescall builtins.NotImplementedError tests/geometry/epipolar/test_essential.py::TestDecomposeEssentialMatrix::test_shape[cpu-float16-batch_shape2]call builtins.NotImplementedError tests/geometry/epipolar/test_essential.py::TestDecomposeEssentialMatrix::test_shape[cpu-float16-batch_shape3]call builtins.NotImplementedError tests/geometry/epipolar/test_essential.py::TestDecomposeEssentialMatrix::test_smoke[cpu-float16]-call builtins.AssertionError tests/geometry/epipolar/test_essential.py::TestEssentialFromFundamental::test_from_fundamental[cpu-float16]call builtins.AssertionError tests/geometry/epipolar/test_essential.py::TestFindEssential::test_synthetic_sampson[cpu-float16]call builtins.NotImplementedError tests/geometry/epipolar/test_essential.py::TestMotionFromEssential::test_shape[cpu-float16-batch_shape0]call builtins.NotImplementedError tests/geometry/epipolar/test_essential.py::TestMotionFromEssential::test_shape[cpu-float16-batch_shape1]@@ -255,7 +254,6 @@ call builtins.NotImplementedError tests/geometry/epipolar/test_fundamental.py::Tcall builtins.NotImplementedError tests/geometry/epipolar/test_fundamental.py::TestFindFundamental::test_synthetic_sampson[cpu-float16]call builtins.AssertionError tests/geometry/epipolar/test_fundamental.py::TestFindFundamental::test_synthetic_sampson_7point[cpu-float16]call builtins.AssertionError tests/geometry/epipolar/test_fundamental.py::TestFundamentalFromProjections::test_batch_support_check[cpu-float16]-call builtins.AssertionError tests/geometry/epipolar/test_fundamental.py::TestFundamentlFromEssential::test_from_to_essential[cpu-float16]call builtins.AssertionError tests/geometry/epipolar/test_projection.py::TestKRtFromProjection::test_projection_from_krt[cpu-float16]call builtins.NotImplementedError tests/geometry/epipolar/test_projection.py::TestKRtFromProjection::test_shape[cpu-float16-1]call builtins.NotImplementedError tests/geometry/epipolar/test_projection.py::TestKRtFromProjection::test_shape[cpu-float16-2]diff --git a/tests/geometry/epipolar/test_fundamental.py b/tests/geometry/epipolar/test_fundamental.pyindex 914facbdb..bbcd10449 100644--- a/tests/geometry/epipolar/test_fundamental.py+++ b/tests/geometry/epipolar/test_fundamental.py@@ -715,8 +715,6 @@ class TestConventionFundamental(BaseTester):def test_convention_fundamental_from_projections_direction_and_scale(self, device, dtype):two_view = two_view_scene(device, dtype)- if dtype == torch.float16:- pytest.skip("float16 overflows to inf on pixel-unit projection matrices (#4877)")_skip_half(dtype, _HALF_PIXEL_F)x1, x2 = two_view["x1"], two_view["x2"]F = epi.fundamental_from_projections(two_view["P1"], two_view["P2"])@@ -862,14 +860,20 @@ class TestConventionFundamental(BaseTester):F_dropped = epi.find_fundamental(x1, x2)self.assert_close(F_weighted, F_dropped, rtol=1e-3, atol=1e-3)- def test_wart_fundamental_from_projections_float16_overflow_4877(self, device, dtype):- two_view = two_view_scene(device, dtype)- if dtype != torch.float16:- pytest.skip("the overflow is float16's: bfloat16, float32 and float64 hold pixel-unit 4x4 determinants")- # #4877: the 4x4 determinants of pixel-unit projection matrices exceed float16's range, so F holds inf.- F = epi.fundamental_from_projections(two_view["P1"], two_view["P2"])+ def test_convention_fundamental_from_projections_float16_unit_max_4877(self, device):+ # #4877: pixel-unit projection matrices give entries of ~1e10, above float16's maximum, so a float16 F is+ # divided by its own largest absolute entry. Three batch rows on different scales: pixel units, normalised+ # cameras (largest entry negative, below 1) and coincident camera centres (F = 0, which stays 0).+ two_view = two_view_scene(device, torch.float16)+ eye = torch.eye(3, 4, device=device, dtype=torch.float16)[None]+ P1 = torch.cat([two_view["P1"], eye, two_view["P1"]])+ P2 = torch.cat([two_view["P2"], torch.cat([two_view["R"], two_view["t"]], -1), two_view["P1"]])+ F = epi.fundamental_from_projections(P1, P2)assert F.dtype == torch.float16- assert torch.isinf(F).any()+ F_ref = epi.fundamental_from_projections(P1.cpu().double(), P2.cpu().double())+ assert F_ref[:2].abs().amax() > 1e9 and F_ref[1].abs().amax() < 1 and (F_ref[2] == 0).all()+ F_ref[:2] = F_ref[:2] / F_ref[:2].abs().amax(dim=(-2, -1), keepdim=True)+ self.assert_close(F.cpu().double(), F_ref, rtol=0.0, atol=1e-3)def _rotation(axis_angle):