π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
fix(geometry): get the closest point on the epipolar line outside autocast (#6179)
Saksham Sharma2818d7233793
diff --git a/changelog.d/6179.fixed.md b/changelog.d/6179.fixed.mdnew file mode 100644index 000000000..56618b1e7--- /dev/null+++ b/changelog.d/6179.fixed.md@@ -0,0 +1 @@+`get_closest_point_on_epipolar_line` runs with autocast disabled, as the solvers of #6072 do, so a caller's `torch.autocast` region no longer changes its result. Under CPU autocast it computed the epipolar lines in half precision and raised `RuntimeError: expected scalar type Float but found BFloat16` (or `Half`) for float32 points and `Fm`; under MPS autocast it returned float32 points several pixels off. `Fm` and `pts2` now take the dtype of `pts1`, as autocast used to arrange for half-precision operands: an `Fm` or `pts2` in another dtype than `pts1`, which raised outside autocast (on MPS a mixed `pts2` returned wrong values instead), now gives the result in the dtype of `pts1`. A call with all three in one dtype outside autocast is unchanged, and a TorchScript-compiled call keeps working as before.diff --git a/kornia/geometry/epipolar/fundamental.py b/kornia/geometry/epipolar/fundamental.pyindex 048f51fab..2b8ba13e7 100644--- a/kornia/geometry/epipolar/fundamental.py+++ b/kornia/geometry/epipolar/fundamental.py@@ -703,6 +703,8 @@ def get_closest_point_on_epipolar_line(pts1: torch.Tensor, pts2: torch.Tensor, FConvention:- Returns, in the second image, the point of the epipolar line of ``pts1`` closest to ``pts2``, for``Fm`` in the :math:`x_2^\top F x_1 = 0` order of :func:`find_fundamental`.+ - ``Fm`` and ``pts2`` take the dtype of ``pts1``. A caller's autocast region does not change the result,+ outside TorchScript.Args:pts1: points in the first image with shape :math:`(B, N, 2)` or :math:`(B, N, 3)`. If they are not@@ -719,6 +721,20 @@ def get_closest_point_on_epipolar_line(pts1: torch.Tensor, pts2: torch.Tensor, Fraise TypeError(f"Fm type is not a torch.Tensor. Got {type(Fm)}")if (len(Fm.shape) < 3) or not Fm.shape[-2:] == (3, 3):raise ValueError(f"Fm must be a (*, 3, 3) tensor. Got {Fm.shape}")+ # A caller's autocast region would compute the epipolar lines in half precision and hand them, with the caller's+ # float32 points, to torch.linalg.cross, which raised on the dtype mismatch. TorchScript has no context managers;+ # a scripted call keeps the caller's precision.+ if torch.jit.is_scripting():+ return _get_closest_point_on_epipolar_line(pts1, pts2, Fm)+ with _autocast_disabled(Fm.device.type):+ return _get_closest_point_on_epipolar_line(pts1, pts2, Fm)+++def _get_closest_point_on_epipolar_line(pts1: torch.Tensor, pts2: torch.Tensor, Fm: torch.Tensor) -> torch.Tensor:+ # Autocast used to unify half-precision operands with float32 ones; outside it, Fm and pts2 take the dtype of pts1.+ # (torch.linalg.cross raises for mixed dtypes on CPU and returns wrong values on MPS.)+ Fm = Fm.to(pts1.dtype)+ pts2 = pts2.to(pts1.dtype)if pts1.shape[-1] == 2:pts1 = convert_points_to_homogeneous(pts1)if pts2.shape[-1] == 2:diff --git a/tests/geometry/epipolar/test_fundamental.py b/tests/geometry/epipolar/test_fundamental.pyindex 9e37c5c30..b995a76d6 100644--- a/tests/geometry/epipolar/test_fundamental.py+++ b/tests/geometry/epipolar/test_fundamental.py@@ -1218,3 +1218,59 @@ class TestRefineFundamentalLM(BaseTester):],]self.assert_close(cauchy, torch.tensor(expected, dtype=torch.float64), atol=1e-9, rtol=0)+++class TestClosestPointOnEpipolarLineMixedPrecision(BaseTester):+ """A caller's autocast region does not reach get_closest_point_on_epipolar_line (#6177)."""++ @staticmethod+ def _inputs(device, dtype=torch.float32):+ generator = torch.Generator().manual_seed(6177)+ Fm = torch.randn(2, 3, 3, generator=generator)+ points1 = torch.rand(2, 10, 2, generator=generator) * 600+ points2 = torch.rand(2, 10, 2, generator=generator) * 600+ return points1.to(device, dtype), points2.to(device, dtype), Fm.to(device, dtype)++ @pytest.mark.parametrize("half_pts2", [False, True], ids=["float32_pts2", "half_pts2"])+ @pytest.mark.parametrize("region_dtype", [torch.bfloat16, torch.float16], ids=["bfloat16", "float16"])+ def test_a_mixed_precision_region_does_not_change_the_result_6177(self, device, region_dtype, half_pts2):+ # The epipolar lines came out of autocast in half precision and met the caller's float32 points in+ # torch.linalg.cross, which raised "expected scalar type Float but found BFloat16" on CPU and returned wrong+ # values on MPS. A half-precision pts2, which autocast used to unify with the lines, keeps working. No+ # "autocast" in the name: conftest skips those on MPS.+ if device.type not in ("cpu", "cuda", "mps"):+ pytest.skip("CPU, CUDA and MPS autocast")+ # MPS autocasts to float16, and so does a CUDA device without bfloat16, where bfloat16 autocast raises.+ bfloat16_ok = device.type == "cpu" or (device.type == "cuda" and torch.cuda.is_bf16_supported())+ if region_dtype == torch.bfloat16 and not bfloat16_ok:+ pytest.skip("no bfloat16 autocast on this device")+ points1, points2, Fm = self._inputs(device)+ if half_pts2:+ points2 = points2.to(region_dtype)+ expected = epi.get_closest_point_on_epipolar_line(points1, points2.float(), Fm)+ with torch.autocast(device.type, dtype=region_dtype):+ actual = epi.get_closest_point_on_epipolar_line(points1, points2, Fm)+ assert actual.dtype == torch.float32+ self.assert_close(actual, expected, atol=0, rtol=0)++ @pytest.mark.parametrize("operand", ["Fm", "pts2"])+ @pytest.mark.parametrize("other_dtype", [torch.float32, torch.float64])+ def test_fm_and_pts2_take_the_dtype_of_pts1_6177(self, device, dtype, other_dtype, operand):+ # Autocast used to unify half-precision operands with float32 ones; the function now casts Fm and pts2 to the+ # dtype of pts1 itself, in and out of autocast. A mixed pts2 raised on CPU and gave wrong values on MPS.+ if device.type == "mps" and other_dtype == torch.float64:+ pytest.skip("MPS does not support float64")+ points1, points2, Fm = self._inputs(device, dtype)+ expected = epi.get_closest_point_on_epipolar_line(points1, points2, Fm)+ if operand == "Fm":+ actual = epi.get_closest_point_on_epipolar_line(points1, points2, Fm.to(other_dtype))+ else:+ actual = epi.get_closest_point_on_epipolar_line(points1, points2.to(other_dtype), Fm)+ assert actual.dtype == dtype+ self.assert_close(actual, expected, atol=0, rtol=0)++ def test_still_scriptable_6177(self, device, dtype):+ # TorchScript has no context managers, so a scripted call skips the autocast guard; it must keep scripting.+ points1, points2, Fm = self._inputs(device, dtype)+ scripted = torch.jit.script(epi.get_closest_point_on_epipolar_line)+ self.assert_close(scripted(points1, points2, Fm), epi.get_closest_point_on_epipolar_line(points1, points2, Fm))