Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

fix(epipolar): run KRt_from_projection and triangulate_points outside autocast (#6175)

Guilherme-M-Mateusb0179afda809
diff --git a/changelog.d/6175.fixed.md b/changelog.d/6175.fixed.md
new file mode 100644
index 000000000..2383cef77
--- /dev/null
+++ b/changelog.d/6175.fixed.md
@@ -0,0 +1 @@
+`KRt_from_projection` and `triangulate_points` run with autocast disabled, as the solvers of #6072 do, so a caller's `torch.autocast` region no longer changes their result. Under float16 or bfloat16 autocast, for float32 inputs, `KRt_from_projection` returned `K` and `R` in the autocast dtype on the CPU, with `R` about 3e-3 from orthogonal in bfloat16, and raised `RuntimeError: geqrf: MPS currently supports float32 only` on MPS; `triangulate_points` with its default `solver="eigh"` raised `NotImplementedError` on MPS. A call made outside autocast is unchanged, and a TorchScript-compiled `KRt_from_projection` keeps the caller's precision as before.
diff --git a/kornia/geometry/epipolar/projection.py b/kornia/geometry/epipolar/projection.py
index f77dfe764..0220711ad 100644
--- a/kornia/geometry/epipolar/projection.py
+++ b/kornia/geometry/epipolar/projection.py
@@ -24,7 +24,7 @@ from torch.linalg import qr as linalg_qr
from kornia.core.check import KORNIA_CHECK_SHAPE
from 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_cast
from .numeric import cross_product_matrix
@@ -167,6 +167,7 @@ def KRt_from_projection(P: torch.Tensor, eps: float = 1e-6) -> Tuple[torch.Tenso
determinant and ``-P`` when it has negative determinant (``-P`` gives the factors of ``P``). ``K`` is
not normalised to ``K[2, 2] = 1``; divide by ``K[..., 2:, 2:]`` to normalise.
- ``P`` must have exactly one batch dimension. float16 and bfloat16 raise.
+ - A caller's autocast region does not change the result, outside TorchScript.
Args:
P: the projection matrix with shape :math:`(B, 3, 4)`.
@@ -180,6 +181,15 @@ def KRt_from_projection(P: torch.Tensor, eps: float = 1e-6) -> Tuple[torch.Tenso
"""
KORNIA_CHECK_SHAPE(P, ["*", "3", "4"])
+ # A caller's autocast region would run the products below in half precision, which torch.linalg.det (CPU) and
+ # qr (MPS) have no kernel for. TorchScript has no context managers; a scripted call keeps the caller's precision.
+ if torch.jit.is_scripting():
+ return _KRt_from_projection(P)
+ with _autocast_disabled(P.device.type):
+ return _KRt_from_projection(P)
+
+
+def _KRt_from_projection(P: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
submat_3x3 = P[:, 0:3, 0:3]
last_column = P[:, 0:3, 3].unsqueeze(-1)
diff --git a/kornia/geometry/epipolar/triangulation.py b/kornia/geometry/epipolar/triangulation.py
index 8bf8654e4..07a075e12 100644
--- a/kornia/geometry/epipolar/triangulation.py
+++ b/kornia/geometry/epipolar/triangulation.py
@@ -22,7 +22,12 @@ from __future__ import annotations
import torch
from kornia.core.check import KORNIA_CHECK_SHAPE
-from kornia.core.utils import _normalize_to_float32_or_float64, _torch_svd_cast, is_mps_tensor_safe
+from kornia.core.utils import (
+ _autocast_disabled,
+ _normalize_to_float32_or_float64,
+ _torch_svd_cast,
+ is_mps_tensor_safe,
+)
from kornia.geometry.conversions import convert_points_from_homogeneous
# https://github.com/opencv/opencv_contrib/blob/master/modules/sfm/src/triangulation.cpp#L68
@@ -122,6 +127,7 @@ def triangulate_points(
- ``"svd"`` and ``"eigh"`` solve in float64, or in float32 for float16 and bfloat16 input and on MPS;
``"cofactor"`` solves in float32, or in float64 for float64 input. All return the input dtype;
``solver`` below compares their accuracy.
+ - A caller's autocast region does not change the result.
Args:
P1: The projection matrix for the first camera with shape :math:`(*, 3, 4)`.
@@ -171,7 +177,15 @@ def triangulate_points(
KORNIA_CHECK_SHAPE(P2, ["*", "3", "4"])
KORNIA_CHECK_SHAPE(points1, ["*", "N", "2"])
KORNIA_CHECK_SHAPE(points2, ["*", "N", "2"])
+ # A caller's autocast region would run the solvers' products in half precision: eigh then has no kernel on MPS,
+ # and cofactor loses accuracy.
+ with _autocast_disabled(P1.device.type):
+ return _triangulate_points(P1, P2, points1, points2, solver)
+
+def _triangulate_points(
+ P1: torch.Tensor, P2: torch.Tensor, points1: torch.Tensor, points2: torch.Tensor, solver: str
+) -> torch.Tensor:
# Build the four DLT constraint rows (each (*, N, 4)) via vectorized broadcasting.
# P[..., r:r+1, :] broadcasts with points[..., c:c+1] β†’ (*, N, 4).
row0 = points1[..., 0:1] * P1[..., 2:3, :] - P1[..., 0:1, :] # (*, N1, 4)
diff --git a/tests/geometry/epipolar/test_projection.py b/tests/geometry/epipolar/test_projection.py
index 6a5653054..b393f83ca 100644
--- a/tests/geometry/epipolar/test_projection.py
+++ b/tests/geometry/epipolar/test_projection.py
@@ -230,6 +230,37 @@ class TestKRtFromProjection(BaseTester):
P_mat = torch.rand(1, 3, 4, device=device, dtype=torch.float64, requires_grad=True)
assert self.gradcheck(epi.KRt_from_projection, (P_mat,), raise_exception=True, fast_mode=True)
+ def test_a_mixed_precision_region_does_not_reach_the_decomposition(self, device):
+ # A caller's autocast region ran the products in half precision, and torch.linalg.det (CPU) or qr (MPS)
+ # raised for the half-precision result (#6174). 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())
+ P = torch.tensor(
+ [[[308.0, 139.0, 231.0, 84.0], [481.0, 161.0, 358.0, 341.0], [384.0, 387.0, 459.0, 102.0]]],
+ device=device,
+ )
+ expected = epi.KRt_from_projection(P)
+ with torch.autocast(device.type, dtype=torch.bfloat16 if bfloat16_ok else torch.float16):
+ actual = epi.KRt_from_projection(P)
+ for a, e in zip(actual, expected):
+ assert a.dtype == torch.float32
+ self.assert_close(a, e, atol=0, rtol=0)
+
+ def test_still_scriptable(self, device, dtype):
+ # TorchScript has no context managers, so a scripted call skips the autocast guard (#6174); it must keep
+ # scripting and give the eager result.
+ _skip_half(dtype, _NO_HALF_QR)
+ P = torch.tensor(
+ [[[308.0, 139.0, 231.0, 84.0], [481.0, 161.0, 358.0, 341.0], [384.0, 387.0, 459.0, 102.0]]],
+ device=device,
+ dtype=dtype,
+ )
+ scripted = torch.jit.script(epi.KRt_from_projection)
+ for a, e in zip(scripted(P), epi.KRt_from_projection(P)):
+ self.assert_close(a, e)
+
_NO_HALF_QR = "KRt_from_projection does not upcast half input, and torch.linalg.qr has no float16/bfloat16 kernel"
diff --git a/tests/geometry/epipolar/test_triangulation.py b/tests/geometry/epipolar/test_triangulation.py
index 3d5c8c736..3399e8026 100644
--- a/tests/geometry/epipolar/test_triangulation.py
+++ b/tests/geometry/epipolar/test_triangulation.py
@@ -317,6 +317,23 @@ class TestTriangulation(BaseTester):
atol = 1e-4 if dtype == torch.float64 else 1e-3
self.assert_close(X_kornia, X_expected, atol=atol, rtol=0.0)
+ @pytest.mark.parametrize("solver", SOLVERS)
+ def test_a_mixed_precision_region_does_not_reach_the_solver(self, solver, device):
+ # A caller's autocast region ran the solvers' products in half precision: cofactor lost accuracy, and eigh
+ # raised on MPS, which has no half-precision eigh (#6174). 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())
+ scene = _make_scene(device, torch.float32)
+ args = (scene["P"][0:1], scene["P"][1:2], scene["points2d"][0:1], scene["points2d"][1:2])
+ expected = epi.triangulate_points(*args, solver=solver)
+ with torch.autocast(device.type, dtype=torch.bfloat16 if bfloat16_ok else torch.float16):
+ actual = epi.triangulate_points(*args, solver=solver)
+ assert actual.dtype == torch.float32
+ self.assert_close(actual, expected, atol=0, rtol=0)
+
# ------------------------------------------------------------------
# Module-level import check
# ------------------------------------------------------------------