Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

fix(geometry): solve PnP and the perspective transform outside autocast (#6169)

Saksham Sharma7671b6c94dcb
diff --git a/changelog.d/6169.fixed.md b/changelog.d/6169.fixed.md
new file mode 100644
index 000000000..85b83b4cf
--- /dev/null
+++ b/changelog.d/6169.fixed.md
@@ -0,0 +1 @@
+`solve_pnp_dlt` and `get_perspective_transform` 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, `solve_pnp_dlt` raised `NotImplementedError: "lu_cpu" not implemented for 'BFloat16'` on the CPU for float32 inputs, and `get_perspective_transform` ran its closed form in bfloat16: the homography between the corners of a 640 x 480 image and four targets mapped those corners 1.36 px off. A call made outside autocast is unchanged, and a TorchScript-compiled `get_perspective_transform` keeps the caller's precision as before.
diff --git a/kornia/geometry/calibration/pnp.py b/kornia/geometry/calibration/pnp.py
index 1bd85c590..2b87ea626 100644
--- a/kornia/geometry/calibration/pnp.py
+++ b/kornia/geometry/calibration/pnp.py
@@ -22,7 +22,7 @@ from torch.linalg import qr as linalg_qr
from kornia.core.check import KORNIA_CHECK, KORNIA_CHECK_IS_TENSOR, KORNIA_CHECK_SAME_SHAPE, KORNIA_CHECK_SHAPE
from kornia.core.ops import eye_like
-from kornia.core.utils import _torch_linalg_svdvals, _torch_svd_cast
+from kornia.core.utils import _autocast_disabled, _torch_linalg_svdvals, _torch_svd_cast
from kornia.geometry.conversions import convert_points_to_homogeneous, normalize_points_with_intrinsics
from kornia.geometry.linalg import transform_points
@@ -104,6 +104,7 @@ def solve_pnp_dlt(
- fewer than 6 points or 6 nonzero ``weights``, or a ``world_points``, ``img_points`` or ``intrinsics``
in a dtype other than float32/float64, raise :class:`~kornia.core.exceptions.BaseError` naming the
argument; a degenerate ``world_points`` raises :class:`AssertionError` from the check above.
+ - a caller's autocast region does not change the result: float32 inputs are solved in float32.
Args:
world_points : A torch.Tensor with shape :math:`(B, N, 3)` representing
@@ -206,90 +207,93 @@ def solve_pnp_dlt(
num_used = num_used.to(point_weights.dtype)
check_scale = (rel_weights * torch.sqrt(num_used / point_weights.sum(dim=1, keepdim=True)))[..., None]
- # Getting normalized world points.
- world_points_norm, world_transform_norm = _mean_isotropic_scale_normalize(world_points, weights=point_weights)
-
- # Checking if world_points_norm (of any element of the batch) has rank = 3. This
- # function cannot be used if all world points (of any element of the batch) lie
- # on a line or if all world points (of any element of the batch) lie on a plane.
- s = _torch_linalg_svdvals(world_points_norm if check_scale is None else check_scale * world_points_norm)
- if torch.any(s[:, -1] < svd_eps):
- raise AssertionError(
- "The last singular value of one/more of the elements of the batch is smaller "
- f"than {svd_eps}. This function cannot be used if all world_points (of any "
- "element of the batch) lie on a line or if all world_points (of any "
- "element of the batch) lie on a plane."
- )
- world_points_norm_h = convert_points_to_homogeneous(world_points_norm)
-
- # Normalizing img_points_inv
- img_points_inv = normalize_points_with_intrinsics(img_points, intrinsics)
- img_points_norm, img_transform_norm = _mean_isotropic_scale_normalize(img_points_inv, weights=point_weights)
- inv_img_transform_norm = torch.inverse(img_transform_norm)
-
- # Setting up the system (the matrix A in Ax=0)
- system = torch.zeros((B, 2 * N, 12), dtype=world_points.dtype, device=world_points.device)
- system[:, 0::2, 0:4] = world_points_norm_h
- system[:, 1::2, 4:8] = world_points_norm_h
- system[:, 0::2, 8:12] = world_points_norm_h * (-1) * img_points_norm[..., 0:1]
- system[:, 1::2, 8:12] = world_points_norm_h * (-1) * img_points_norm[..., 1:2]
-
- # Apply weights to the system if provided
- if weights is not None:
- weights_expanded = weights.unsqueeze(-1).repeat(1, 1, 2).view(B, 2 * N, 1)
- # Multiply the system matrix by the expanded weights
- system = weights_expanded * system
-
- # Getting the solution vectors.
- # Only the right singular vectors are used; reduced SVD avoids saving the unused (2N, 2N) U.
- _, _, v = _torch_svd_cast(system, full_matrices=False)
- solution = v[..., -1]
-
- # Reshaping the solution vectors to the correct shape.
- solution = solution.reshape(B, 3, 4)
-
- # Creating solution_4x4
- solution_4x4 = eye_like(4, solution)
- solution_4x4[:, :3, :] = solution
-
- # De-normalizing the solution
- intermediate = torch.bmm(solution_4x4, world_transform_norm)
- solution = torch.bmm(inv_img_transform_norm, intermediate[:, :3, :])
-
- # We obtained one solution for each element of the batch. We may
- # need to multiply each solution with a scalar. This is because
- # if x is a solution to Ax=0, then cx is also a solution. We can
- # find the required scalars by using the properties of
- # rotation matrices. We do this in two parts:
-
- # First, we fix the sign by making sure that the determinant of
- # the all the rotation matrices are non-negative (since determinant
- # of a rotation matrix should be 1).
- det = torch.det(solution[:, :3, :3])
- ones_tensor = torch.ones_like(det)
- sign_fix = torch.where(det < 0, ones_tensor * -1, ones_tensor)
- solution = solution * sign_fix[:, None, None]
-
- # Then, we make sure that norm of the 0th columns of the rotation
- # matrices are 1. Do note that the norm of any column of a rotation
- # matrix should be 1. Here we use the 0th column to calculate norm_col.
- # We then multiply solution with mul_factor.
- norm_col = torch.norm(input=solution[:, :3, 0], p=2, dim=1)
- mul_factor = (1 / norm_col)[:, None, None]
- temp = solution * mul_factor
-
- # To make sure that the rotation matrix would be orthogonal, we apply
- # QR decomposition.
- ortho, right = linalg_qr(temp[:, :3, :3])
-
- # We may need to fix the signs of the columns of the ortho matrix.
- # If right[i, j, j] is negative, then we need to flip the signs of
- # the column ortho[i, :, j]. The below code performs the necessary
- # operations in a better way.
- mask = eye_like(3, ortho)
- col_sign_fix = torch.sign(mask * right)
- rot_mat = torch.bmm(ortho, col_sign_fix)
-
- # Preparing the final output.
- # TODO: Implement algorithm to refine the solution.
- return torch.cat([rot_mat, temp[:, :3, 3:4]], dim=-1)
+ # A caller's autocast region would run the products below in half precision: torch.det, which has no half-precision
+ # CPU kernel, then raised, and float32 inputs would no longer be solved in float32.
+ with _autocast_disabled(world_points.device.type):
+ # Getting normalized world points.
+ world_points_norm, world_transform_norm = _mean_isotropic_scale_normalize(world_points, weights=point_weights)
+
+ # Checking if world_points_norm (of any element of the batch) has rank = 3. This
+ # function cannot be used if all world points (of any element of the batch) lie
+ # on a line or if all world points (of any element of the batch) lie on a plane.
+ s = _torch_linalg_svdvals(world_points_norm if check_scale is None else check_scale * world_points_norm)
+ if torch.any(s[:, -1] < svd_eps):
+ raise AssertionError(
+ "The last singular value of one/more of the elements of the batch is smaller "
+ f"than {svd_eps}. This function cannot be used if all world_points (of any "
+ "element of the batch) lie on a line or if all world_points (of any "
+ "element of the batch) lie on a plane."
+ )
+ world_points_norm_h = convert_points_to_homogeneous(world_points_norm)
+
+ # Normalizing img_points_inv
+ img_points_inv = normalize_points_with_intrinsics(img_points, intrinsics)
+ img_points_norm, img_transform_norm = _mean_isotropic_scale_normalize(img_points_inv, weights=point_weights)
+ inv_img_transform_norm = torch.inverse(img_transform_norm)
+
+ # Setting up the system (the matrix A in Ax=0)
+ system = torch.zeros((B, 2 * N, 12), dtype=world_points.dtype, device=world_points.device)
+ system[:, 0::2, 0:4] = world_points_norm_h
+ system[:, 1::2, 4:8] = world_points_norm_h
+ system[:, 0::2, 8:12] = world_points_norm_h * (-1) * img_points_norm[..., 0:1]
+ system[:, 1::2, 8:12] = world_points_norm_h * (-1) * img_points_norm[..., 1:2]
+
+ # Apply weights to the system if provided
+ if weights is not None:
+ weights_expanded = weights.unsqueeze(-1).repeat(1, 1, 2).view(B, 2 * N, 1)
+ # Multiply the system matrix by the expanded weights
+ system = weights_expanded * system
+
+ # Getting the solution vectors.
+ # Only the right singular vectors are used; reduced SVD avoids saving the unused (2N, 2N) U.
+ _, _, v = _torch_svd_cast(system, full_matrices=False)
+ solution = v[..., -1]
+
+ # Reshaping the solution vectors to the correct shape.
+ solution = solution.reshape(B, 3, 4)
+
+ # Creating solution_4x4
+ solution_4x4 = eye_like(4, solution)
+ solution_4x4[:, :3, :] = solution
+
+ # De-normalizing the solution
+ intermediate = torch.bmm(solution_4x4, world_transform_norm)
+ solution = torch.bmm(inv_img_transform_norm, intermediate[:, :3, :])
+
+ # We obtained one solution for each element of the batch. We may
+ # need to multiply each solution with a scalar. This is because
+ # if x is a solution to Ax=0, then cx is also a solution. We can
+ # find the required scalars by using the properties of
+ # rotation matrices. We do this in two parts:
+
+ # First, we fix the sign by making sure that the determinant of
+ # the all the rotation matrices are non-negative (since determinant
+ # of a rotation matrix should be 1).
+ det = torch.det(solution[:, :3, :3])
+ ones_tensor = torch.ones_like(det)
+ sign_fix = torch.where(det < 0, ones_tensor * -1, ones_tensor)
+ solution = solution * sign_fix[:, None, None]
+
+ # Then, we make sure that norm of the 0th columns of the rotation
+ # matrices are 1. Do note that the norm of any column of a rotation
+ # matrix should be 1. Here we use the 0th column to calculate norm_col.
+ # We then multiply solution with mul_factor.
+ norm_col = torch.norm(input=solution[:, :3, 0], p=2, dim=1)
+ mul_factor = (1 / norm_col)[:, None, None]
+ temp = solution * mul_factor
+
+ # To make sure that the rotation matrix would be orthogonal, we apply
+ # QR decomposition.
+ ortho, right = linalg_qr(temp[:, :3, :3])
+
+ # We may need to fix the signs of the columns of the ortho matrix.
+ # If right[i, j, j] is negative, then we need to flip the signs of
+ # the column ortho[i, :, j]. The below code performs the necessary
+ # operations in a better way.
+ mask = eye_like(3, ortho)
+ col_sign_fix = torch.sign(mask * right)
+ rot_mat = torch.bmm(ortho, col_sign_fix)
+
+ # Preparing the final output.
+ # TODO: Implement algorithm to refine the solution.
+ return torch.cat([rot_mat, temp[:, :3, 3:4]], dim=-1)
diff --git a/kornia/geometry/transform/imgwarp.py b/kornia/geometry/transform/imgwarp.py
index 0d340d4e4..040adee07 100644
--- a/kornia/geometry/transform/imgwarp.py
+++ b/kornia/geometry/transform/imgwarp.py
@@ -25,6 +25,7 @@ import torch.nn.functional as F
from kornia.core.check import KORNIA_CHECK, KORNIA_CHECK_SHAPE
from kornia.core.ops import eye_like
from kornia.core.utils import (
+ _autocast_disabled,
_inverse_3x3_closed_form,
_normalize_to_float32_or_float64,
_torch_grid_sample,
@@ -787,6 +788,7 @@ def get_perspective_transform(points_src: torch.Tensor, points_dst: torch.Tensor
- points: ``(x, y)``, pixel centers, origin at top-left; shape :math:`(B, 4, 2)`
- returns the source→destination **pixel** homography :math:`(B, 3, 3)` that
:func:`warp_perspective` takes
+ - a caller's autocast region does not change the result, outside TorchScript
Args:
points_src: coordinates of quadrangle vertices in the source image with shape :math:`(B, 4, 2)`.
@@ -814,7 +816,12 @@ def get_perspective_transform(points_src: torch.Tensor, points_dst: torch.Tensor
# ``torch.linalg.solve``. Both yield the perspective transform mapping ``points_src`` onto
# ``points_dst``; the closed form additionally needs no LAPACK/cusolver backend (so it runs on
# the Jetson wheel, where ``linalg.solve`` dlopen-fails) and traces cleanly for ONNX.
- return _get_perspective_transform_closed_form(points_src, points_dst)
+ # A caller's autocast region would run its products in half precision: about 1 px off at the corners of a 640 x
+ # 480 image. TorchScript has no context managers; a scripted call keeps the caller's precision.
+ if torch.jit.is_scripting():
+ return _get_perspective_transform_closed_form(points_src, points_dst)
+ with _autocast_disabled(points_src.device.type):
+ return _get_perspective_transform_closed_form(points_src, points_dst)
# TODO: move to kornia.geometry.affine
diff --git a/tests/geometry/calibration/test_pnp.py b/tests/geometry/calibration/test_pnp.py
index 9b5100cd7..d5728880a 100644
--- a/tests/geometry/calibration/test_pnp.py
+++ b/tests/geometry/calibration/test_pnp.py
@@ -415,3 +415,35 @@ class TestNormalization(BaseTester):
points = torch.rand((batch_size, num_points, dimension), device=device, dtype=torch.float64)
self.gradcheck(_mean_isotropic_scale_normalize, (points,))
+
+
+class TestSolvePnpDltAutocast(BaseTester):
+ """A caller's autocast region does not reach the PnP solve (#6168), as for the solvers of #6072."""
+
+ @staticmethod
+ def _scene(device):
+ generator = torch.Generator().manual_seed(6168)
+ K = torch.tensor([[[400.0, 0.0, 160.0], [0.0, 410.0, 120.0], [0.0, 0.0, 1.0]]])
+ R = kornia.geometry.conversions.axis_angle_to_rotation_matrix(torch.tensor([[0.1, -0.2, 0.05]]))
+ t = torch.tensor([[[0.2], [-0.1], [4.0]]])
+ world = torch.rand(1, 40, 3, generator=generator) * 2 - 1
+ img = kornia.geometry.conversions.convert_points_from_homogeneous((world @ R.mT + t.mT) @ K.mT)
+ weights = torch.rand(1, 40, generator=generator) + 0.5
+ return [v.to(device) for v in (world, img, K, torch.cat([R, t], -1), weights)]
+
+ @pytest.mark.parametrize("weighted", [False, True])
+ def test_autocast_does_not_change_the_result_6168(self, device, weighted):
+ # Under bfloat16 autocast the de-normalization products ran in bfloat16, and torch.det, which has no
+ # half-precision CPU kernel, raised NotImplementedError for float32 inputs.
+ 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")
+ world, img, K, expected_pose, weights = self._scene(device)
+ weights = weights if weighted else None
+ expected = kornia.geometry.calibration.solve_pnp_dlt(world, img, K, weights)
+ with torch.autocast(device.type, dtype=torch.bfloat16):
+ actual = kornia.geometry.calibration.solve_pnp_dlt(world, img, K, weights)
+ assert actual.dtype == torch.float32
+ self.assert_close(actual, expected, atol=0, rtol=0)
+ self.assert_close(actual, expected_pose, atol=1e-4, rtol=0)
diff --git a/tests/geometry/transform/test_imgwarp.py b/tests/geometry/transform/test_imgwarp.py
index 78ff2da22..918578fba 100644
--- a/tests/geometry/transform/test_imgwarp.py
+++ b/tests/geometry/transform/test_imgwarp.py
@@ -1482,3 +1482,31 @@ class TestInvertAffineTransform(BaseTester):
actual = op_script(matrix)
expected = op(matrix)
self.assert_close(actual, expected, rtol=1e-4, atol=1e-4)
+
+
+class TestGetPerspectiveTransformAutocast(BaseTester):
+ """A caller's autocast region does not reach get_perspective_transform (#6168)."""
+
+ def test_autocast_does_not_change_the_result_6168(self, device):
+ # Under bfloat16 autocast the closed form ran its products in bfloat16: the homography between the corners of
+ # a 640 x 480 image and four targets mapped those corners about 1.4 px off.
+ 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")
+ src = torch.tensor([[[0.0, 0.0], [639.0, 0.0], [639.0, 479.0], [0.0, 479.0]]], device=device)
+ dst = torch.tensor([[[12.0, 7.0], [630.0, 15.0], [610.0, 470.0], [-5.0, 460.0]]], device=device)
+ expected = kornia.geometry.transform.get_perspective_transform(src, dst)
+ with torch.autocast(device.type, dtype=torch.bfloat16):
+ actual = kornia.geometry.transform.get_perspective_transform(src, dst)
+ assert actual.dtype == torch.float32
+ self.assert_close(actual, expected, atol=0, rtol=0)
+ mapped = kornia.geometry.linalg.transform_points(actual, src)
+ self.assert_close(mapped, dst, atol=1e-3, rtol=0)
+
+ def test_still_scriptable_6168(self, device, dtype):
+ # TorchScript has no context managers, so a scripted call skips the autocast guard; it must keep scripting.
+ src = torch.tensor([[[0.0, 0.0], [10.0, 0.0], [10.0, 8.0], [0.0, 8.0]]], device=device, dtype=dtype)
+ dst = torch.tensor([[[1.0, 0.5], [11.0, 1.0], [9.5, 8.5], [-0.5, 7.5]]], device=device, dtype=dtype)
+ scripted = torch.jit.script(kornia.geometry.transform.get_perspective_transform)
+ self.assert_close(scripted(src, dst), kornia.geometry.transform.get_perspective_transform(src, dst))