π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
fix(geometry): run the essential-matrix decompositions outside autocast (#6147)
Saksham Sharma75534acbc924
diff --git a/changelog.d/6147.fixed.md b/changelog.d/6147.fixed.mdnew file mode 100644index 000000000..4f618e88d--- /dev/null+++ b/changelog.d/6147.fixed.md@@ -0,0 +1 @@+`decompose_essential_matrix`, `decompose_essential_matrix_no_svd`, `motion_from_essential`, `motion_from_essential_choose_solution` and `project_to_essential` run with autocast disabled, as the solvers of #6072 do, so a caller's `torch.autocast` region no longer changes their result. Under bfloat16 autocast a float32 essential matrix was decomposed with its matrix products in bfloat16: the rotations came back in bfloat16, about `1.6e-3` off and no longer orthogonal, next to a float32 translation, and `motion_from_essential_choose_solution` triangulated its points with bfloat16 projection matrices, which moved them by up to `0.2` at depths of 5 to 9. `motion_from_essential_choose_solution` now casts `K1` and `K2` to the dtype of `E_mat`, so half-precision intrinsics with a float32 matrix, which autocast used to cast to one dtype, still run, and run outside autocast too, where they raised. Any other call made outside autocast is unchanged, and a TorchScript-compiled call keeps the products in the caller's precision as before.diff --git a/kornia/geometry/epipolar/essential.py b/kornia/geometry/epipolar/essential.pyindex b4fd6965c..aa8bb003d 100644--- a/kornia/geometry/epipolar/essential.py+++ b/kornia/geometry/epipolar/essential.py@@ -23,7 +23,7 @@ import torchfrom kornia.core.check import KORNIA_CHECK, KORNIA_CHECK_SAME_SHAPE, KORNIA_CHECK_SHAPEfrom kornia.core.ops import eye_like, vec_like-from kornia.core.utils import _torch_svd_cast+from kornia.core.utils import _autocast_disabled, _torch_svd_castfrom kornia.geometry.solvers.homogeneous import _null_space_householderfrom kornia.geometry.solvers.polynomial_solver import T_deg1, T_deg2@@ -494,6 +494,7 @@ def project_to_essential(E_mat: torch.Tensor) -> torch.Tensor:Convention:- The result is not normalised to unit Frobenius norm, unlike the candidates of :func:`find_essential`.+ - A caller's autocast region does not change the result, outside TorchScript.Args:E_mat: The matrices to project with shape :math:`(*, 3, 3)`.@@ -504,6 +505,15 @@ def project_to_essential(E_mat: torch.Tensor) -> torch.Tensor:"""KORNIA_CHECK_SHAPE(E_mat, ["*", "3", "3"])+ # A caller's autocast region would run the products below in half precision and return a half-precision matrix.+ # TorchScript has no context managers; a scripted call keeps the products in the caller's precision.+ if torch.jit.is_scripting():+ return _project_to_essential(E_mat)+ with _autocast_disabled(E_mat.device.type):+ return _project_to_essential(E_mat)+++def _project_to_essential(E_mat: torch.Tensor) -> torch.Tensor:U, S, V = _torch_svd_cast(E_mat)S_new = torch.zeros_like(S)mean_sv = 0.5 * (S[..., 0] + S[..., 1])@@ -525,6 +535,8 @@ def decompose_essential_matrix(E_mat: torch.Tensor) -> Tuple[torch.Tensor, torchpose is not fixed: it can change when ``E_mat`` is negated or rescaled. Select by cheirality with:func:`motion_from_essential_choose_solution`; :ref:`two-view geometry <two-view-conventions>`compares OpenCV's labels.+ - A caller's autocast region does not change the result, outside TorchScript: a float32 ``E_mat`` gives+ float32 rotations.Args:E_mat: The essential matrix in the form of :math:`(*, 3, 3)`.@@ -535,7 +547,15 @@ def decompose_essential_matrix(E_mat: torch.Tensor) -> Tuple[torch.Tensor, torch"""KORNIA_CHECK_SHAPE(E_mat, ["*", "3", "3"])+ # A caller's autocast region would run the products below in half precision: half-precision rotations, no longer+ # orthogonal, next to a translation in the input dtype. TorchScript has no context managers.+ if torch.jit.is_scripting():+ return _decompose_essential_matrix(E_mat)+ with _autocast_disabled(E_mat.device.type):+ return _decompose_essential_matrix(E_mat)++def _decompose_essential_matrix(E_mat: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor]:# decompose matrix by its singular valuesU, _, V = _torch_svd_cast(E_mat)Vt = V.transpose(-2, -1)@@ -572,6 +592,7 @@ def decompose_essential_matrix_no_svd(E_mat: torch.Tensor) -> Tuple[torch.TensorConvention:- Same candidate set as :func:`decompose_essential_matrix`, with ``t`` of unit norm.+ - A caller's autocast region does not change the result, outside TorchScript.Args:E_mat: The essential matrix in the form of :math:`(*, 3, 3)`.@@ -582,6 +603,14 @@ def decompose_essential_matrix_no_svd(E_mat: torch.Tensor) -> Tuple[torch.Tensor"""KORNIA_CHECK_SHAPE(E_mat, ["*", "3", "3"])+ # A caller's autocast region would run the products below in half precision. TorchScript has no context managers.+ if torch.jit.is_scripting():+ return _decompose_essential_matrix_no_svd(E_mat)+ with _autocast_disabled(E_mat.device.type):+ return _decompose_essential_matrix_no_svd(E_mat)+++def _decompose_essential_matrix_no_svd(E_mat: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor]:if len(E_mat.shape) != 3:E_mat = E_mat.view(-1, 3, 3)@@ -677,6 +706,7 @@ def motion_from_essential(E_mat: torch.Tensor) -> Tuple[torch.Tensor, torch.TensConvention:- The candidates of :func:`decompose_essential_matrix` are stacked on dim ``-3`` in that order; whichindex is the true pose is not fixed.+ - A caller's autocast region does not change the result, as for :func:`decompose_essential_matrix`.Args:E_mat: The essential matrix in the form of :math:`(*, 3, 3)`.@@ -720,6 +750,8 @@ def motion_from_essential_choose_solution(candidate, as ``cv2.recoverPose`` returns. A count of ``0`` means no point passed, and the returnedpose is then candidate 0 of:py:meth:`~kornia.geometry.epipolar.motion_from_essential`, not a recovered motion.+ - A caller's autocast region does not change the result. ``K1`` and ``K2`` are cast to the dtype of+ ``E_mat``.Args:E_mat: The essential matrix in the form of :math:`(B, 3, 3)`, or :math:`(3, 3)` with every other input@@ -764,46 +796,53 @@ def motion_from_essential_choose_solution(if mask is not None:mask = mask[None]- # compute four possible pose solutions- Rs, ts = motion_from_essential(E_mat)-- # set reference view pose and compute projection matrix- R1 = eye_like(3, E_mat) # Bx3x3- t1 = vec_like(3, E_mat) # Bx3x1-- # compute the projection matrices for first camera- R1 = R1[:, None].expand(-1, 4, -1, -1)- t1 = t1[:, None].expand(-1, 4, -1, -1)- K1 = K1[:, None].expand(-1, 4, -1, -1)- P1 = projection_from_KRt(K1, R1, t1) # 1x4x4x4-- # compute the projection matrices for second camera- R2 = Rs- t2 = ts- K2 = K2[:, None].expand(-1, 4, -1, -1)- P2 = projection_from_KRt(K2, R2, t2) # Bx4x4x4-- # triangulate the points- x1 = x1[:, None].expand(-1, 4, -1, -1)- x2 = x2[:, None].expand(-1, 4, -1, -1)- X = triangulate_points(P1, P2, x1, x2) # Bx4xNx3-- # project points and compute their depth values- d1 = depth_from_point(R1, t1, X)- d2 = depth_from_point(R2, t2, X)-- # verify the point values that have a positive depth value- depth_mask = (d1 > 0.0) & (d2 > 0.0)- if mask is not None:- depth_mask &= mask.unsqueeze(1)+ # Autocast is off below, so the intrinsics are cast to the dtype of ``E_mat`` here, as autocast casts+ # half-precision intrinsics and a float32 ``E_mat`` to one dtype.+ K1, K2 = K1.to(E_mat.dtype), K2.to(E_mat.dtype)++ # A caller's autocast region would build the projection matrices and the depths in half precision, which moves+ # the triangulated points and can change the chosen candidate, and would return a half-precision rotation.+ with _autocast_disabled(E_mat.device.type):+ # compute four possible pose solutions+ Rs, ts = motion_from_essential(E_mat)++ # set reference view pose and compute projection matrix+ R1 = eye_like(3, E_mat) # Bx3x3+ t1 = vec_like(3, E_mat) # Bx3x1++ # compute the projection matrices for first camera+ R1 = R1[:, None].expand(-1, 4, -1, -1)+ t1 = t1[:, None].expand(-1, 4, -1, -1)+ K1 = K1[:, None].expand(-1, 4, -1, -1)+ P1 = projection_from_KRt(K1, R1, t1) # 1x4x4x4++ # compute the projection matrices for second camera+ R2 = Rs+ t2 = ts+ K2 = K2[:, None].expand(-1, 4, -1, -1)+ P2 = projection_from_KRt(K2, R2, t2) # Bx4x4x4++ # triangulate the points+ x1 = x1[:, None].expand(-1, 4, -1, -1)+ x2 = x2[:, None].expand(-1, 4, -1, -1)+ X = triangulate_points(P1, P2, x1, x2) # Bx4xNx3++ # project points and compute their depth values+ d1 = depth_from_point(R1, t1, X)+ d2 = depth_from_point(R2, t2, X)++ # verify the point values that have a positive depth value+ depth_mask = (d1 > 0.0) & (d2 > 0.0)+ if mask is not None:+ depth_mask &= mask.unsqueeze(1)- valid_count, mask_indices = torch.max(depth_mask.sum(-1), dim=-1)+ valid_count, mask_indices = torch.max(depth_mask.sum(-1), dim=-1)- # get pose and points 3d and return- batch_idx = torch.arange(mask_indices.shape[0], device=mask_indices.device)- R_out = Rs[batch_idx, mask_indices]- t_out = ts[batch_idx, mask_indices]- points3d_out = X[batch_idx, mask_indices]+ # get pose and points 3d and return+ batch_idx = torch.arange(mask_indices.shape[0], device=mask_indices.device)+ R_out = Rs[batch_idx, mask_indices]+ t_out = ts[batch_idx, mask_indices]+ points3d_out = X[batch_idx, mask_indices]if unbatched:R_out = R_out[0]diff --git a/tests/geometry/epipolar/test_essential.py b/tests/geometry/epipolar/test_essential.pyindex 5a6bbfd04..127971ed4 100644--- a/tests/geometry/epipolar/test_essential.py+++ b/tests/geometry/epipolar/test_essential.py@@ -1429,3 +1429,109 @@ class TestRefineEssentialLM(BaseTester):together = _refine_essential_lm(starts, h1, h2, None, "truncated", 1e-4, 15)alone = torch.cat([_refine_essential_lm(start[None], h1, h2, None, "truncated", 1e-4, 15) for start in starts])self.assert_close(together, alone, atol=1e-12, rtol=0)+++def _skip_without_bfloat16_autocast(device):+ # A bfloat16 autocast region raises on a CUDA device without bfloat16 support, and other devices are not covered.+ if device.type == "cuda" and not torch.cuda.is_bf16_supported():+ pytest.skip("this CUDA device does not support bfloat16")+ if device.type not in ("cpu", "cuda"):+ pytest.skip("CPU and CUDA autocast")+++def _autocast_scene(device):+ # A float32 two-view scene built outside any autocast region: K, a small motion, and 30 points in front of both+ # cameras.+ generator = torch.Generator().manual_seed(6146)+ K = torch.tensor([[[300.0, 0.0, 50.0], [0.0, 300.0, 50.0], [0.0, 0.0, 1.0]]])+ R = kornia.geometry.conversions.axis_angle_to_rotation_matrix(torch.tensor([[0.05, -0.1, 0.02]]))+ t = torch.tensor([[[0.5], [0.1], [0.0]]])+ E_mat = epi.essential_from_Rt(torch.eye(3)[None], torch.zeros(1, 3, 1), R, t)+ X = torch.rand(1, 30, 3, generator=generator) * 4 + torch.tensor([-2.0, -2.0, 5.0])+ x1 = kornia.geometry.conversions.convert_points_from_homogeneous(X @ K.mT)+ x2 = kornia.geometry.conversions.convert_points_from_homogeneous((X @ R.mT + t.mT) @ K.mT)+ return [v.to(device) for v in (E_mat, K, x1, x2, R)]+++_AUTOCAST_CALLS = {+ "decompose_essential_matrix": lambda E_mat, K, x1, x2: epi.decompose_essential_matrix(E_mat),+ "decompose_essential_matrix_no_svd": lambda E_mat, K, x1, x2: epi.decompose_essential_matrix_no_svd(E_mat),+ "motion_from_essential": lambda E_mat, K, x1, x2: epi.motion_from_essential(E_mat),+ "motion_from_essential_choose_solution": lambda E_mat, K, x1, x2: epi.motion_from_essential_choose_solution(+ E_mat, K, K, x1, x2+ ),+ "project_to_essential": lambda E_mat, K, x1, x2: epi.project_to_essential(E_mat),+}+++class TestEssentialDecompositionAutocast(BaseTester):+ """A caller's autocast region does not reach the essential-matrix decompositions (#6146), as for #6072's solvers."""++ @pytest.mark.parametrize("name", list(_AUTOCAST_CALLS))+ def test_autocast_does_not_change_the_result_6146(self, device, name):+ # Under bfloat16 autocast, a float32 essential matrix was decomposed with bfloat16 matrix products: bfloat16+ # rotations about 1.6e-3 off and no longer orthogonal, next to a float32 translation.+ _skip_without_bfloat16_autocast(device)+ E_mat, K, x1, x2, _ = _autocast_scene(device)+ call = _AUTOCAST_CALLS[name]+ expected = call(E_mat, K, x1, x2)+ with torch.autocast(device.type, dtype=torch.bfloat16):+ actual = call(E_mat, K, x1, x2)+ expected = expected if isinstance(expected, tuple) else (expected,)+ actual = actual if isinstance(actual, tuple) else (actual,)+ for out, ref in zip(actual, expected):+ assert out.dtype == ref.dtype+ self.assert_close(out, ref, atol=0, rtol=0)++ def test_chosen_rotation_stays_a_rotation_under_autocast_6146(self, device):+ _skip_without_bfloat16_autocast(device)+ E_mat, K, x1, x2, R = _autocast_scene(device)+ with torch.autocast(device.type, dtype=torch.bfloat16):+ R_out, t_out, _, count = epi.motion_from_essential_choose_solution(E_mat, K, K, x1, x2)+ assert R_out.dtype == t_out.dtype == torch.float32+ assert int(count) == 30+ self.assert_close(R_out, R, atol=1e-5, rtol=0)+ self.assert_close(R_out @ R_out.mT, torch.eye(3, device=device).expand_as(R_out), atol=1e-5, rtol=0)++ def test_half_precision_intrinsics_under_autocast_6146(self, device):+ # Autocast used to cast bfloat16 intrinsics and a float32 essential matrix to one dtype. With autocast off+ # inside, the intrinsics are cast to the matrix's dtype, so the call still runs and gives the float32 result.+ _skip_without_bfloat16_autocast(device)+ E_mat, K, x1, x2, _ = _autocast_scene(device)+ K_half = K.to(torch.bfloat16)+ expected = epi.motion_from_essential_choose_solution(E_mat, K_half.float(), K_half.float(), x1, x2)+ with torch.autocast(device.type, dtype=torch.bfloat16):+ actual = epi.motion_from_essential_choose_solution(E_mat, K_half, K_half, x1, x2)+ for out, ref in zip(actual, expected):+ assert out.dtype == ref.dtype+ self.assert_close(out, ref, atol=0, rtol=0)++ @pytest.mark.parametrize(+ "fn",+ [+ epi.decompose_essential_matrix,+ epi.decompose_essential_matrix_no_svd,+ epi.motion_from_essential,+ epi.project_to_essential,+ ],+ ids=lambda fn: fn.__name__,+ )+ def test_still_scriptable_6146(self, device, dtype, fn):+ # TorchScript has no context managers, so a scripted call skips the autocast guard; it must keep scripting.+ E_mat = epi.essential_from_Rt(+ torch.eye(3, device=device, dtype=dtype)[None],+ torch.zeros(1, 3, 1, device=device, dtype=dtype),+ kornia.geometry.conversions.axis_angle_to_rotation_matrix(+ torch.tensor([[0.05, -0.1, 0.02]], device=device, dtype=dtype)+ ),+ torch.tensor([[[0.5], [0.1], [0.0]]], device=device, dtype=dtype),+ )+ if dtype in (torch.float16, torch.bfloat16) and fn is not epi.decompose_essential_matrix_no_svd:+ pytest.skip("calls torch.det or torch.linalg.svd, which have no half-precision CPU kernel")+ scripted = torch.jit.script(fn)+ expected = fn(E_mat)+ actual = scripted(E_mat)+ expected = expected if isinstance(expected, tuple) else (expected,)+ actual = actual if isinstance(actual, tuple) else (actual,)+ for out, ref in zip(actual, expected):+ self.assert_close(out, ref)