Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

29.1 KB
Raw Blame
# LICENSE HEADER MANAGED BY add-license-header
#
# Copyright 2018 Kornia Team
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#

import pytest
import torch

import kornia
from kornia.core.exceptions import BaseError, ShapeError
from kornia.geometry.calibration.pnp import _mean_isotropic_scale_normalize

from testing.base import BaseTester


class TestSolvePnpDlt(BaseTester):
    @staticmethod
    def _get_samples(shape, low, high, device, dtype):
        """Return a tensor having the given shape and whose values are in the range [low, high)"""
        return ((high - low) * torch.rand(shape, device=device, dtype=dtype)) + low

    @staticmethod
    def _project_to_image(world_points, world_to_cam_4x4, repeated_intrinsics):
        r"""Projects points in the world coordinate system to the image coordinate system.

        Since cam_points will have shape (B, N, 3), repeated_intrinsics should have shape (B, N, 3, 3) so that
        kornia.geometry.project_points can be used.
        """
        cam_points = kornia.geometry.transform_points(world_to_cam_4x4, world_points)
        return kornia.geometry.project_points(cam_points, repeated_intrinsics)

    @staticmethod
    def _get_world_points_and_img_points(cam_points, world_to_cam_4x4, repeated_intrinsics):
        r"""Calculates world_points and img_points.

        Since cam_points will have shape (B, N, 3), repeated_intrinsics should have shape (B, N, 3, 3) so that
        kornia.geometry.project_points can be used.
        """
        cam_to_world_4x4 = kornia.geometry.inverse_transformation(world_to_cam_4x4)
        world_points = kornia.geometry.transform_points(cam_to_world_4x4, cam_points)
        img_points = kornia.geometry.project_points(cam_points, repeated_intrinsics)

        return world_points, img_points

    def _get_test_data(self, num_points, device, dtype):
        """Creates some test data.

        Batch size is fixed to 2 for all tests.
        """
        batch_size = 2
        torch.manual_seed(84)

        tau = 2 * 3.141592653589793
        axis_angle_1 = self._get_samples(shape=(1, 3), low=-tau, high=tau, dtype=dtype, device=device)
        axis_angle_2 = self._get_samples(shape=(1, 3), low=-tau, high=tau, dtype=dtype, device=device)
        rotation_1 = kornia.geometry.axis_angle_to_rotation_matrix(axis_angle_1)
        rotation_2 = kornia.geometry.axis_angle_to_rotation_matrix(axis_angle_2)

        translation_1 = self._get_samples(shape=(3,), low=-100, high=100, dtype=dtype, device=device)
        translation_2 = self._get_samples(shape=(3,), low=-100, high=100, dtype=dtype, device=device)

        temp = torch.eye(4, dtype=dtype, device=device)
        world_to_cam_mats = temp.unsqueeze(0).repeat(batch_size, 1, 1)
        world_to_cam_mats[0, :3, :3] = torch.squeeze(rotation_1)
        world_to_cam_mats[0, :3, 3] = translation_1
        world_to_cam_mats[1, :3, :3] = torch.squeeze(rotation_2)
        world_to_cam_mats[1, :3, 3] = translation_2

        intrinsic_1 = torch.tensor(
            [[500.0, 0.0, 250.0], [0.0, 500.0, 250.0], [0.0, 0.0, 1.0]], dtype=dtype, device=device
        )

        intrinsic_2 = torch.tensor(
            [[1000.0, 0.0, 550.0], [0.0, 750.0, 200.0], [0.0, 0.0, 1.0]], dtype=dtype, device=device
        )

        intrinsics = torch.stack([intrinsic_1, intrinsic_2], dim=0)

        cam_points_xy = self._get_samples(
            shape=(batch_size, num_points, 2), low=-100, high=100, dtype=dtype, device=device
        )
        cam_points_z = self._get_samples(
            shape=(batch_size, num_points, 1), low=0.5, high=100, dtype=dtype, device=device
        )
        cam_points = torch.cat([cam_points_xy, cam_points_z], dim=-1)

        repeated_intrinsics = intrinsics.unsqueeze(1).repeat(1, num_points, 1, 1)
        world_points, img_points = self._get_world_points_and_img_points(
            cam_points, world_to_cam_mats, repeated_intrinsics
        )
        world_to_cam_3x4 = world_to_cam_mats[:, :3, :]

        return intrinsics, world_to_cam_3x4, world_points, img_points

    @pytest.mark.parametrize("num_points", [6, 20])
    def test_smoke(self, num_points, device, dtype):
        intrinsics, _, world_points, img_points = self._get_test_data(num_points, device, dtype)
        batch_size = world_points.shape[0]

        pred_world_to_cam = kornia.geometry.solve_pnp_dlt(world_points, img_points, intrinsics)
        assert pred_world_to_cam.shape == (batch_size, 3, 4)

    @pytest.mark.parametrize("num_points", [6])
    def test_gradcheck(self, num_points, device):
        intrinsics, _, world_points, img_points = self._get_test_data(num_points, device, torch.float64)
        self.gradcheck(kornia.geometry.solve_pnp_dlt, (world_points, img_points, intrinsics))

    def test_backward_storage_scales_with_points(self, device):
        dtype = torch.float32 if device.type == "mps" else torch.float64
        intrinsics, _, world_points, img_points = self._get_test_data(64, device, dtype)
        world_points.requires_grad_()
        saved_sizes = []

        def pack(tensor):
            saved_sizes.append(tensor.numel())
            return tensor

        with torch.autograd.graph.saved_tensors_hooks(pack, lambda tensor: tensor):
            pose = kornia.geometry.solve_pnp_dlt(world_points, img_points, intrinsics)
            pose.square().sum().backward()

        assert torch.isfinite(world_points.grad).all()
        assert max(saved_sizes) <= 16 * world_points.numel()

    @pytest.mark.parametrize("num_points", [8])
    def test_gradcheck_weights(self, num_points, device):
        intrinsics, _, world_points, img_points = self._get_test_data(num_points, device, torch.float64)
        weights = torch.rand(*world_points.shape[:2], device=device, dtype=torch.float64).abs()
        self.gradcheck(kornia.geometry.solve_pnp_dlt, (world_points, img_points, intrinsics, weights))

    @pytest.mark.parametrize("num_points", [6, 20])
    def test_pred_world_to_cam(self, num_points, device, dtype):
        intrinsics, gt_world_to_cam, world_points, img_points = self._get_test_data(num_points, device, dtype)
        pred_world_to_cam = kornia.geometry.solve_pnp_dlt(world_points, img_points, intrinsics)
        self.assert_close(pred_world_to_cam, gt_world_to_cam, atol=1e-4, rtol=1e-4)

    @pytest.mark.parametrize("num_points", [16, 20])
    def test_pred_world_to_cam_weighted(self, num_points, device, dtype):
        intrinsics, gt_world_to_cam, world_points, img_points = self._get_test_data(num_points, device, dtype)
        weights = torch.ones(*world_points.shape[:2], device=device, dtype=dtype)
        pred_world_to_cam = kornia.geometry.solve_pnp_dlt(world_points, img_points, intrinsics, weights)
        self.assert_close(pred_world_to_cam, gt_world_to_cam, atol=1e-4, rtol=1e-4)

    @pytest.mark.parametrize("num_points", [25])
    def test_pred_world_to_cam_weighted_rand(self, num_points, device, dtype):
        torch.manual_seed(0)
        intrinsics, gt_world_to_cam, world_points, img_points = self._get_test_data(num_points, device, dtype)
        weights = torch.ones(*world_points.shape[:2], device=device, dtype=dtype)
        weights[0, 0:2] = 1e-9
        world_points[0, 0:1] *= 0.1
        world_points[0, 1:2] += 100
        pred_world_to_cam = kornia.geometry.solve_pnp_dlt(world_points, img_points, intrinsics, weights)
        self.assert_close(pred_world_to_cam, gt_world_to_cam, atol=1e-4, rtol=1e-3)

    @pytest.mark.parametrize("num_points", [6, 20])
    def test_project(self, num_points, device, dtype):
        intrinsics, _, world_points, img_points = self._get_test_data(num_points, device, dtype)

        pred_world_to_cam = kornia.geometry.solve_pnp_dlt(world_points, img_points, intrinsics)

        pred_world_to_cam_4x4 = kornia.core.ops.eye_like(4, pred_world_to_cam)
        pred_world_to_cam_4x4[:, :3, :] = pred_world_to_cam

        repeated_intrinsics = intrinsics.unsqueeze(1).repeat(1, num_points, 1, 1)
        pred_img_points = self._project_to_image(world_points, pred_world_to_cam_4x4, repeated_intrinsics)

        self.assert_close(pred_img_points, img_points, atol=1e-3, rtol=1e-3)

    @staticmethod
    def _convention_world_points(device, dtype):
        # Six non-coplanar, non-collinear points spread over x, y and z with mixed signs. A planar or collinear set
        # trips solve_pnp_dlt's own singular-value guard, and a
        # symmetric set would hide a transposed [R|t].
        return torch.tensor(
            [
                [
                    [5.0, -5.0, 10.0],
                    [0.0, 0.0, 11.5],
                    [2.5, 3.0, 16.0],
                    [9.0, -2.0, 13.0],
                    [-4.0, 5.0, 12.0],
                    [-5.0, 5.0, 11.0],
                ]
            ],
            device=device,
            dtype=dtype,
        )

    def test_convention_returns_the_world_to_camera_extrinsics(self, device, dtype):
        # The (B, 3, 4) [R | t] maps world points into the camera frame (PinholeCamera.extrinsics, OpenCV
        # solvePnP). Camera-frame world points recover [I | 0]; a camera with cam = world + (1, 0, 0) recovers
        # t = (+1, 0, 0), where a camera-to-world reading would give (-1, 0, 0).
        if dtype not in (torch.float32, torch.float64):
            pytest.skip("solve_pnp_dlt accepts float32 and float64 only (pinned below)")
        world_points = self._convention_world_points(device, dtype)
        K = torch.tensor([[[100.0, 0.0, 4.0], [0.0, 100.0, 3.0], [0.0, 0.0, 1.0]]], device=device, dtype=dtype)
        identity = torch.tensor(
            [[[1.0, 0.0, 0.0, 0.0], [0.0, 1.0, 0.0, 0.0], [0.0, 0.0, 1.0, 0.0]]], device=device, dtype=dtype
        )
        recovered = kornia.geometry.solve_pnp_dlt(world_points, kornia.geometry.project_points(world_points, K), K)
        assert recovered.shape == (1, 3, 4)
        self.assert_close(recovered, identity, atol=1e-4, rtol=1e-4)
        shift = torch.tensor([1.0, 0.0, 0.0], device=device, dtype=dtype)
        shifted = kornia.geometry.solve_pnp_dlt(
            world_points, kornia.geometry.project_points(world_points + shift, K), K
        )
        expected = torch.tensor(
            [[[1.0, 0.0, 0.0, 1.0], [0.0, 1.0, 0.0, 0.0], [0.0, 0.0, 1.0, 0.0]]], device=device, dtype=dtype
        )
        self.assert_close(shifted, expected, atol=1e-4, rtol=1e-4)

    def test_convention_validation_errors_name_the_argument(self, device, dtype):
        # solve_pnp_dlt accepts float32 and float64 only, needs N >= 6 points and a float svd_eps; each check
        # raises a kornia BaseError that names its argument.
        world_points = self._convention_world_points(device, dtype)
        K = torch.tensor([[[100.0, 0.0, 4.0], [0.0, 100.0, 3.0], [0.0, 0.0, 1.0]]], device=device, dtype=dtype)
        img_points = world_points[..., :2] / world_points[..., 2:]
        if dtype not in (torch.float32, torch.float64):
            with pytest.raises(BaseError, match="world_points must be float32 or float64"):
                kornia.geometry.solve_pnp_dlt(world_points, img_points, K)
            return
        with pytest.raises(BaseError, match="world_points must hold at least 6 points"):
            kornia.geometry.solve_pnp_dlt(world_points[:, :5], img_points[:, :5], K)
        with pytest.raises(BaseError, match="svd_eps must be a float, got int"):
            kornia.geometry.solve_pnp_dlt(world_points, img_points, K, svd_eps=1)

    def test_convention_rejects_4x4_intrinsics(self, device, dtype):
        # intrinsics is the (B, 3, 3) K: the (B, 4, 4) matrix a PinholeCamera stores is rejected rather than
        # truncated, while its upper-left block solves.
        if dtype not in (torch.float32, torch.float64):
            pytest.skip("solve_pnp_dlt accepts float32 and float64 only")
        world_points = self._convention_world_points(device, dtype)
        K = torch.tensor([[[100.0, 0.0, 4.0], [0.0, 100.0, 3.0], [0.0, 0.0, 1.0]]], device=device, dtype=dtype)
        img_points = kornia.geometry.project_points(world_points, K)
        K_4x4 = torch.eye(4, device=device, dtype=dtype)[None].clone()
        K_4x4[:, :3, :3] = K
        with pytest.raises(ShapeError, match="expected 3, got 4"):
            kornia.geometry.solve_pnp_dlt(world_points, img_points, K_4x4)
        assert kornia.geometry.solve_pnp_dlt(world_points, img_points, K_4x4[:, :3, :3]).shape == (1, 3, 4)

    def test_convention_planar_world_points_raise(self, device, dtype):
        # A coplanar point set (the six points flattened onto z = 5) raises kornia's singular-value
        # AssertionError instead of returning a wrong pose.
        if dtype not in (torch.float32, torch.float64):
            pytest.skip("solve_pnp_dlt accepts float32 and float64 only")
        world_points = self._convention_world_points(device, dtype)
        K = torch.tensor([[[100.0, 0.0, 4.0], [0.0, 100.0, 3.0], [0.0, 0.0, 1.0]]], device=device, dtype=dtype)
        planar = torch.stack(
            [world_points[0, :, 0], world_points[0, :, 1], torch.full_like(world_points[0, :, 0], 5.0)], -1
        )[None]
        with pytest.raises(AssertionError, match="last singular value"):
            kornia.geometry.solve_pnp_dlt(planar, kornia.geometry.project_points(planar, K), K)

    def test_zero_weight_points_do_not_pass_the_degeneracy_check(self, device, dtype):
        # kornia#4799: the same coplanar set plus two off-plane points recovers [I | 0]; with those two points at
        # weight 0 only the coplanar points are left, so the degeneracy check must reject it.
        if dtype not in (torch.float32, torch.float64):
            pytest.skip("solve_pnp_dlt accepts float32 and float64 only")
        world_points = self._convention_world_points(device, dtype)
        K = torch.tensor([[[100.0, 0.0, 4.0], [0.0, 100.0, 3.0], [0.0, 0.0, 1.0]]], device=device, dtype=dtype)
        planar = torch.stack(
            [world_points[0, :, 0], world_points[0, :, 1], torch.full_like(world_points[0, :, 0], 5.0)], -1
        )[None]
        off_plane = torch.tensor([[[0.0, 0.0, 8.0], [1.0, -1.0, 11.0]]], device=device, dtype=dtype)
        points = torch.cat([planar, off_plane], 1)
        img_points = kornia.geometry.project_points(points, K)
        weights = torch.ones(1, points.shape[1], device=device, dtype=dtype)
        pose = kornia.geometry.solve_pnp_dlt(points, img_points, K, weights=weights)
        assert pose[0, :, 3].abs().max() < 1e-2
        weights[0, -2:] = 0.0
        with pytest.raises(AssertionError, match="last singular value"):
            kornia.geometry.solve_pnp_dlt(points, img_points, K, weights=weights)

    def test_zero_weight_point_is_the_same_as_removing_it(self, device, dtype):
        # kornia#4799: a zero weight also kept the point in the normalization, so on noisy data the pose
        # differed from the solve without that point.
        if dtype not in (torch.float32, torch.float64):
            pytest.skip("solve_pnp_dlt accepts float32 and float64 only")
        torch.manual_seed(0)
        K = torch.tensor([[[500.0, 0.0, 320.0], [0.0, 500.0, 240.0], [0.0, 0.0, 1.0]]], device=device, dtype=dtype)
        points = torch.rand(1, 10, 3, device=device, dtype=dtype) * 4 - 2
        points[..., 2] += 10.0
        img_points = kornia.geometry.project_points(points, K)
        img_points = img_points + torch.randn_like(img_points)
        far_point = torch.tensor([[[30.0, -20.0, 60.0]]], device=device, dtype=dtype)
        far_img = torch.tensor([[[0.0, 0.0]]], device=device, dtype=dtype)
        weights = torch.ones(1, 11, device=device, dtype=dtype)
        weights[0, -1] = 0.0
        with_zero = kornia.geometry.solve_pnp_dlt(
            torch.cat([points, far_point], 1), torch.cat([img_points, far_img], 1), K, weights=weights
        )
        without = kornia.geometry.solve_pnp_dlt(points, img_points, K)
        self.assert_close(with_zero, without, rtol=1e-4, atol=1e-4)

    def test_weight_squared_is_the_point_multiplicity(self, device, dtype):
        # A weight scales the point's rows, so its square multiplies the point's residual: weight sqrt(2) is the
        # same as listing the point twice, also in the normalization. On noisy data this separates w**2 from w.
        if dtype not in (torch.float32, torch.float64):
            pytest.skip("solve_pnp_dlt accepts float32 and float64 only")
        torch.manual_seed(0)
        K = torch.tensor([[[500.0, 0.0, 320.0], [0.0, 500.0, 240.0], [0.0, 0.0, 1.0]]], device=device, dtype=dtype)
        points = torch.rand(1, 10, 3, device=device, dtype=dtype) * 4 - 2
        points[..., 2] += 10.0
        img_points = kornia.geometry.project_points(points, K)
        img_points = img_points + 3 * torch.randn_like(img_points)
        weights = torch.ones(1, 10, device=device, dtype=dtype)
        weights[0, 0] = 2.0**0.5
        weighted = kornia.geometry.solve_pnp_dlt(points, img_points, K, weights=weights)
        duplicated = kornia.geometry.solve_pnp_dlt(
            torch.cat([points, points[:, :1]], 1), torch.cat([img_points, img_points[:, :1]], 1), K
        )
        self.assert_close(weighted, duplicated, rtol=1e-4, atol=1e-4)

    def test_weights_scale_and_sign_do_not_change_the_result(self, device, dtype):
        # Only the weights' magnitudes relative to each other matter: a negative weight counts as its magnitude,
        # and scales whose squares overflow or underflow the dtype do not change the pose or the degeneracy
        # decision.
        if dtype not in (torch.float32, torch.float64):
            pytest.skip("solve_pnp_dlt accepts float32 and float64 only")
        torch.manual_seed(0)
        K = torch.tensor([[[500.0, 0.0, 320.0], [0.0, 500.0, 240.0], [0.0, 0.0, 1.0]]], device=device, dtype=dtype)
        points = torch.rand(2, 10, 3, device=device, dtype=dtype) * 4 - 2
        points[..., 2] += 10.0
        img_points = kornia.geometry.project_points(points, K[:, None])
        img_points = img_points + torch.randn_like(img_points)
        weights = torch.rand(2, 10, device=device, dtype=dtype) + 0.1
        weights[:, 0] = 0.0
        expected = kornia.geometry.solve_pnp_dlt(points, img_points, K.expand(2, 3, 3), weights=weights)
        for scale in (-1.0, 1e20, 1e-25) if dtype == torch.float32 else (-1.0, 1e160, 1e-170):
            scaled = kornia.geometry.solve_pnp_dlt(points, img_points, K.expand(2, 3, 3), weights=weights * scale)
            self.assert_close(scaled, expected, rtol=1e-4, atol=1e-4)

    def test_degeneracy_check_ignores_zero_weights_and_the_weight_scale(self, device, dtype):
        # The check sees the nonzero-weight points as if they were passed alone, with the squared weights
        # rescaled to sum to their count: the six points listed twice, the copies at half weight, have the last
        # singular value of the six listed twice (sqrt(2) times theirs), whatever the overall weight scale and
        # whatever the zero-weight points.
        if dtype not in (torch.float32, torch.float64):
            pytest.skip("solve_pnp_dlt accepts float32 and float64 only")
        world_points = self._convention_world_points(device, dtype)
        K = torch.tensor([[[100.0, 0.0, 4.0], [0.0, 100.0, 3.0], [0.0, 0.0, 1.0]]], device=device, dtype=dtype)
        last = 2.0**0.5 * torch.linalg.svdvals(_mean_isotropic_scale_normalize(world_points)[0])[0, -1].item()
        extra = world_points * torch.tensor([3.0, -2.0, 4.0], device=device, dtype=dtype)
        points = torch.cat([world_points, world_points, extra], 1)
        img_points = kornia.geometry.project_points(points, K)
        weights = torch.full((1, 18), 1e3, device=device, dtype=dtype)
        weights[0, 6:12] = 0.5e3
        weights[0, 12:] = 0.0
        kornia.geometry.solve_pnp_dlt(points, img_points, K, weights=weights, svd_eps=0.9 * last)
        with pytest.raises(AssertionError, match="last singular value"):
            kornia.geometry.solve_pnp_dlt(points, img_points, K, weights=weights, svd_eps=1.1 * last)

    def test_near_zero_weight_points_do_not_pass_the_degeneracy_check(self, device, dtype):
        # The check runs on the weighted points: off-plane points at weight 1e-8 leave the system as degenerate
        # as the coplanar points alone.
        if dtype not in (torch.float32, torch.float64):
            pytest.skip("solve_pnp_dlt accepts float32 and float64 only")
        world_points = self._convention_world_points(device, dtype)
        K = torch.tensor([[[100.0, 0.0, 4.0], [0.0, 100.0, 3.0], [0.0, 0.0, 1.0]]], device=device, dtype=dtype)
        planar = torch.stack(
            [world_points[0, :, 0], world_points[0, :, 1], torch.full_like(world_points[0, :, 0], 5.0)], -1
        )[None]
        off_plane = torch.tensor([[[0.0, 0.0, 8.0], [1.0, -1.0, 11.0]]], device=device, dtype=dtype)
        points = torch.cat([planar, off_plane], 1)
        weights = torch.ones(1, 8, device=device, dtype=dtype)
        weights[0, -2:] = 1e-8
        with pytest.raises(AssertionError, match="last singular value"):
            kornia.geometry.solve_pnp_dlt(points, kornia.geometry.project_points(points, K), K, weights=weights)

    def test_fewer_than_six_nonzero_weights_raise(self, device, dtype):
        # A zero weight removes the point, so fewer than 6 nonzero weights is rejected like fewer than 6 points.
        if dtype not in (torch.float32, torch.float64):
            pytest.skip("solve_pnp_dlt accepts float32 and float64 only")
        world_points = self._convention_world_points(device, dtype)
        points = torch.cat([world_points, world_points + 1.0], 1).repeat(2, 1, 1)
        K = torch.tensor([[[100.0, 0.0, 4.0], [0.0, 100.0, 3.0], [0.0, 0.0, 1.0]]], device=device, dtype=dtype)
        K = K.expand(2, 3, 3)
        img_points = kornia.geometry.project_points(points, K[:, None])
        weights = torch.ones(2, 12, device=device, dtype=dtype)
        weights[1, 5:] = 0.0
        with pytest.raises(BaseError, match="at least 6 nonzero"):
            kornia.geometry.solve_pnp_dlt(points, img_points, K, weights=weights)
        weights[1] = 0.0
        with pytest.raises(BaseError, match="at least 6 nonzero"):
            kornia.geometry.solve_pnp_dlt(points, img_points, K, weights=weights)


class TestNormalization(BaseTester):
    @pytest.mark.parametrize("dimension", [2, 3, 5])
    def test_smoke(self, dimension, device, dtype):
        batch_size = 10
        num_points = 100
        points = torch.rand((batch_size, num_points, dimension), device=device, dtype=dtype)
        points_norm, transform = _mean_isotropic_scale_normalize(points)

        assert points_norm.shape == (batch_size, num_points, dimension)
        assert transform.shape == (batch_size, dimension + 1, dimension + 1)

    @pytest.mark.parametrize("dimension", [2, 3, 5])
    def test_gradcheck(self, dimension, device):
        batch_size = 3
        num_points = 5
        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)


class TestSolvePnpDltGradient(BaseTester):
    """``solve_pnp_dlt``'s gradient is finite when other singular values of the system are equal (#6213)."""

    def test_cube_corners_have_the_central_difference_gradient_6213(self, device):
        # The corners of a cube and its centre make singular values of the DLT system equal in some poses, where
        # torch's SVD backward made the gradient with respect to the image points NaN. Which poses tie depends on
        # the SVD backend: 4 to 6 of these 64 on the CPUs measured, and none in float64 on CUDA, so this test pins
        # the fix on CPU.
        if device.type == "mps":
            pytest.skip("MPS has no float64")
        from kornia.geometry.conversions import axis_angle_to_rotation_matrix

        dtype = torch.float64
        g = torch.Generator().manual_seed(0)
        corners = [[x, y, z] for x in (-1.0, 1.0) for y in (-1.0, 1.0) for z in (-1.0, 1.0)] + [[0.0, 0.0, 0.0]]
        cube = torch.tensor(corners, dtype=dtype)
        batch = 64
        rotation = axis_angle_to_rotation_matrix(torch.rand(batch, 3, generator=g, dtype=dtype) - 0.5)
        translation = torch.tensor([0.0, 0.0, 6.0], dtype=dtype) + torch.rand(batch, 1, 3, generator=g, dtype=dtype)
        intrinsics = torch.tensor([[500.0, 0.0, 320.0], [0.0, 500.0, 240.0], [0.0, 0.0, 1.0]], dtype=dtype)
        camera = cube @ rotation.mT + translation - 0.5
        projected = camera @ intrinsics.T
        img_points = (projected[..., :2] / projected[..., 2:]).to(device)
        world_points = cube.expand(batch, -1, -1).to(device)
        intrinsics = intrinsics.expand(batch, -1, -1).to(device)

        def solve(u):
            return kornia.geometry.solve_pnp_dlt(world_points, u, intrinsics).reshape(batch, -1)

        u = img_points.clone().requires_grad_(True)
        out = solve(u)
        # Each pose depends only on its own points, so one backward per output entry gives every pose's Jacobian.
        jac = torch.stack([torch.autograd.grad(out[:, j].sum(), u, retain_graph=True)[0] for j in range(12)], 1)
        assert torch.isfinite(jac).all()
        eps = 1e-5
        columns = []
        for i in range(img_points[0].numel()):
            step = torch.zeros(img_points[0].numel(), device=device, dtype=dtype)
            step[i] = eps
            step = step.view_as(img_points[0])
            columns.append((solve(img_points + step) - solve(img_points - step)) / (2 * eps))
        self.assert_close(jac.reshape(batch, 12, -1), torch.stack(columns, -1), rtol=1e-5, atol=1e-7)

    def test_dynamo_gradient_matches_eager_6213(self, device, dtype, torch_optimizer):
        # The kept vector's own gap is excluded by position: CUDA Inductor evaluated (S / scale)^2 differently at its
        # two reads, a gap of 1e-20 instead of 0, and the compiled gradient of solve_pnp_dlt was up to 1e11 times off.
        if dtype not in (torch.float32, torch.float64):
            pytest.skip("solve_pnp_dlt accepts float32 and float64 only")
        from kornia.geometry.conversions import axis_angle_to_rotation_matrix

        g = torch.Generator().manual_seed(0)
        batch = 2
        world = torch.rand(batch, 10, 3, generator=g, dtype=torch.float64) * 2 - 1
        rotation = axis_angle_to_rotation_matrix(torch.rand(batch, 3, generator=g, dtype=torch.float64) - 0.5)
        camera = world @ rotation.mT + torch.tensor([0.0, 0.0, 6.0], dtype=torch.float64)
        intrinsics = torch.tensor([[500.0, 0.0, 320.0], [0.0, 500.0, 240.0], [0.0, 0.0, 1.0]], dtype=torch.float64)
        projected = camera @ intrinsics.T
        img_points = (projected[..., :2] / projected[..., 2:]).to(device, dtype)
        world = world.to(device, dtype)
        intrinsics = intrinsics.expand(batch, -1, -1).to(device, dtype)
        weights = torch.randn(batch, 3, 4, generator=g, dtype=torch.float64).to(device, dtype)

        def op(u):
            return kornia.geometry.solve_pnp_dlt(world, u, intrinsics)

        u_eager = img_points.clone().requires_grad_(True)
        u_compiled = img_points.clone().requires_grad_(True)
        (expected,) = torch.autograd.grad((op(u_eager) * weights).sum(), u_eager)
        (actual,) = torch.autograd.grad((torch_optimizer(op)(u_compiled) * weights).sum(), u_compiled)
        self.assert_close(actual, expected)