Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

52.5 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 math

import pytest
import torch

from kornia.core.exceptions import DeviceError, ShapeError, TypeCheckError
from kornia.geometry.conversions import euler_from_quaternion, rotation_matrix_to_quaternion
from kornia.geometry.liegroup import Se3, So3
from kornia.geometry.pose import NamedPose
from kornia.geometry.quaternion import Quaternion
from kornia.geometry.vector import Vector3

from testing.base import DYNAMO_UNAVAILABLE_REASON, BaseTester, dynamo_is_available


class TestSe3(BaseTester):
    def _make_rand_se3d(self, device, dtype, batch_size) -> Se3:
        q = Quaternion.random(batch_size, device, dtype)
        t = self._make_rand_data(device, dtype, batch_size, dims=3)
        return Se3(q, t)

    def _make_rand_se3d_vec(self, device, dtype, batch_size) -> Se3:
        q = Quaternion.random(batch_size, device, dtype)
        shape = () if batch_size is None else (batch_size,)
        t = Vector3.random(shape, device, dtype)
        return Se3(So3(q), t)

    def _make_rand_data(self, device, dtype, batch_size, dims):
        shape = [] if batch_size is None else [batch_size]
        return torch.rand([*shape, dims], device=device, dtype=dtype)

    def _assert_chains_agree(self, actual, expected, p, t1, t2):
        """Compare two chains of point transforms through poses with translations t1 and t2 that meet at one point."""
        if actual.dtype not in (torch.float16, torch.bfloat16):
            self.assert_close(actual, expected)
            return
        # Every Se3 operation computes in float32 and rounds once (TestSe3HalfPrecision pins that). A rounded point or
        # translation v moves the end of its chain by at most u |v| (u = eps / 2), since only rotations and sums follow
        # it, and the rounded quaternion of s12 = s1^-1 * s2 turns each vector it rotates by at most 2 u |v|. For the
        # longer pair, pt_in_s2 against s12^-1 * pt_in_s1, the roundings cost: s2^-1.t, u |t2|; pt_in_s2,
        # u (|p| + |t2|); s1^-1.t, computed for pt_in_s1 and for s12, 2 u |t1|; pt_in_s1, u (|p| + |t1|); s12.t and
        # s12^-1.t, u (|t1| + |t2|) each; the result, u (|p| + |t2|); and s12's quaternion, applied to pt_in_s1 and
        # s12.t, 2 u (|p| + 2 |t1| + |t2|). That sums to u (5 |p| + 9 |t1| + 7 |t2|) <= 9 u S with
        # S = |p| + |t1| + |t2|; the other pair sums to u (5 |p| + 5 |t1| + 5 |t2|). The default half tolerance, about
        # 2 u, does not cover either.
        u = torch.finfo(actual.dtype).eps / 2
        s = sum(x.detach().cpu().double().norm(dim=-1) for x in (p, t1, t2)).max().item()
        self.assert_close(actual.detach().cpu().double(), expected.detach().cpu().double(), rtol=0.0, atol=9 * u * s)

    def test_smoke(self, device, dtype):
        q = Quaternion.from_coeffs(1.0, 0.0, 0.0, 0.0)
        q = q.to(device, dtype)
        t = torch.rand(1, 3, device=device, dtype=dtype)
        s = Se3(So3(q), t)
        assert isinstance(s, Se3)
        assert isinstance(s.r, So3)
        self.assert_close(s.r.q.data, q.data)
        self.assert_close(s.t, t)

    @pytest.mark.parametrize("batch_size", [1, 2, 5])
    def test_cardinality(self, device, dtype, batch_size):
        se: Se3 = self._make_rand_se3d(device, dtype, batch_size)
        assert se.r.q.shape[0] == batch_size

    def test_exception(self, device, dtype):
        with pytest.raises(ShapeError, match=r"Shape mismatch at dimension 1: expected 3, got 2"):
            Se3(So3.identity(1, device, dtype), torch.zeros(1, 2, device=device, dtype=dtype))

        with pytest.raises(ShapeError, match=r"Shape mismatch at dimension 1: expected 6, got 5"):
            Se3.exp(torch.zeros(1, 5, device=device, dtype=dtype))

        with pytest.raises(ShapeError, match=r"Shape mismatch at dimension 1: expected 4, got 3"):
            Se3.from_matrix(torch.eye(3, device=device, dtype=dtype).repeat(1, 1, 1))

        with pytest.raises(TypeError, match=r"Unsupported type"):
            Se3(So3.identity(1, device, dtype), torch.zeros(1, 3, device=device, dtype=dtype)) * 4

    def test_gradcheck(self, device):
        v = torch.tensor([[1.0, 2.0, 3.0, 0.3, -0.4, 0.5]], device=device, dtype=torch.float64)
        self.gradcheck(lambda x: Se3.exp(x).matrix(), (v,))

    def test_gradient_is_finite_at_the_identity_4404(self, device, dtype):
        # #4404: at omega = 0 autograd walks V, whose sqrt has an unbounded derivative there and
        # whose closed-form terms divide by theta**2 and theta**3.
        # log has the same defect through its own theta, where clamp_min(1e-12) guards the value
        # and not the gradient (#4229) and underflows to 0 in float16 besides.
        v = torch.zeros(1, 6, device=device, dtype=dtype, requires_grad=True)
        Se3.exp(v).matrix().sum().backward()
        assert bool(torch.isfinite(v.grad).all()), v.grad

        data = torch.tensor([[1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]], device=device, dtype=dtype, requires_grad=True)
        Se3(So3(Quaternion(data[:, :4])), data[:, 4:]).log().sum().backward()
        assert bool(torch.isfinite(data.grad).all()), data.grad

    def test_exp_matches_float64_above_40_rad_4965(self, device, dtype):
        # #4965: _so3_small_angle_coefficients divided by theta**3, which overflows float16 above 40.3 rad, so the
        # [omega]_x^2 term of V dropped out and the float16 exp(v).t was off by 0.18 from 41 rad. The reference
        # is the float64 path on the CPU, run on the same rounded input.
        eps = torch.finfo(dtype).eps
        axis = torch.tensor([0.48, 0.6, 0.64], dtype=torch.float64)
        for theta in (41.0, 60.0):
            v = torch.cat((torch.ones(3, dtype=torch.float64), theta * axis)).to(device=device, dtype=dtype)
            t_ref = Se3.exp(v.cpu().double()).t.to(device=device, dtype=dtype)
            self.assert_close(Se3.exp(v).t, t_ref, rtol=8 * eps, atol=8 * eps)

    def test_gradient_at_the_identity_couples_rotation_and_translation_4953(self, device, dtype):
        # #4953: exp fell back to t = upsilon and log to upsilon = t at omega = 0. The values were
        # right, V(0) = I, but the fallback did not depend on omega, so autograd returned
        # d t / d omega = 0 at the identity, the standard initialisation for pose optimisation.
        # The derivative of V(omega) upsilon = upsilon + 0.5 omega x upsilon + O(|omega|^2) is
        # -0.5 [upsilon]_x, and d upsilon / d q_vec of log at the identity is [t]_x.
        v = torch.tensor([[1.0, 2.0, 3.0, 0.0, 0.0, 0.0]], device=device, dtype=dtype)
        jac = torch.autograd.functional.jacobian(lambda x: Se3.exp(x).t, v)[0, :, 0, :]
        upsilon = v[0, :3]
        self.assert_close(jac[:, :3], torch.eye(3, device=device, dtype=dtype))
        self.assert_close(jac[:, 3:], -0.5 * So3.hat(upsilon))
        qt = torch.tensor([[1.0, 0.0, 0.0, 0.0, 1.0, 2.0, 3.0]], device=device, dtype=dtype)
        jac = torch.autograd.functional.jacobian(lambda x: Se3(So3(Quaternion(x[:, :4])), x[:, 4:]).log(), qt)
        jac = jac[0, :, 0, :]
        self.assert_close(jac[:3, 4:], torch.eye(3, device=device, dtype=dtype))
        self.assert_close(jac[:3, 1:4], So3.hat(qt[0, 4:]))

    # TODO: implement me
    def test_jit(self, device, dtype):
        pass

    # TODO: implement me
    def test_module(self, device, dtype):
        pass

    @pytest.mark.parametrize("batch_size", [None, 1, 2, 5])
    def test_init(self, device, dtype, batch_size):
        s1: Se3 = self._make_rand_se3d(device, dtype, batch_size)
        s2 = Se3(s1.r, s1.t)
        assert isinstance(s2, Se3)
        self.assert_close(s1.r.q.data, s2.r.q.data)
        self.assert_close(s1.t, s2.t)

    @pytest.mark.parametrize("batch_size", [1, 2, 5])
    def test_getitem(self, device, dtype, batch_size):
        q = Quaternion.random(batch_size, device, dtype)
        t = torch.rand(batch_size, 3, device=device, dtype=dtype)
        s = Se3(q, t)
        for i in range(batch_size):
            s1 = s[i]
            self.assert_close(s1.r.q.data, q.data[i])
            self.assert_close(s1.t, t[i])

    @pytest.mark.parametrize("batch_size", [None, 1, 2, 5])
    def test_mul(self, device, dtype, batch_size):
        s1 = Se3.identity(batch_size, device, dtype)
        s2: Se3 = self._make_rand_se3d(device, dtype, batch_size)
        s1s2 = s1 * s2
        s2s2inv = s2 * s2.inverse()
        zeros_vec = torch.zeros(3, device=device, dtype=dtype)
        if batch_size is not None:
            zeros_vec = zeros_vec.repeat(batch_size, 1)
        so3_expected = So3.identity(batch_size, device, dtype)
        self.assert_close(s1s2.r.q.data, s2.r.q.data)
        self.assert_close(s1s2.t, s2.t)
        self.assert_close(s2s2inv.r.q.data, so3_expected.q.data)
        self.assert_close(s2s2inv.t, zeros_vec)

    @pytest.mark.parametrize("batch_size", [None, 1, 2, 5])
    def test_mul_point(self, device, dtype, batch_size):
        world_pose_s1: Se3 = self._make_rand_se3d(device, dtype, batch_size)
        world_pose_s2: Se3 = self._make_rand_se3d(device, dtype, batch_size)
        pt_in_world = self._make_rand_data(device, dtype, batch_size, dims=3)
        s1_pose_s2: Se3 = world_pose_s1.inverse() * world_pose_s2
        pt_in_s1 = world_pose_s1.inverse() * pt_in_world
        pt_in_s2 = world_pose_s2.inverse() * pt_in_world
        pt_in_s1_in_s2 = s1_pose_s2.inverse() * pt_in_s1
        pt_in_s2_in_s1 = s1_pose_s2 * pt_in_s2
        translations = (world_pose_s1.t, world_pose_s2.t)
        self._assert_chains_agree(pt_in_s1, pt_in_s2_in_s1, pt_in_world, *translations)
        self._assert_chains_agree(pt_in_s2, pt_in_s1_in_s2, pt_in_world, *translations)

    @pytest.mark.parametrize("points_shape", [(7, 3), (1, 3)])
    def test_unbatched_pose_transforms_a_point_set(self, points_shape, device, dtype):
        # #6426: an unbatched Se3 maps every point of a point set, as Se2 does for (N, 2); it used to raise in
        # torch.linalg.cross. Expected: R p + t for each point.
        torch.manual_seed(0)
        g = Se3.exp(torch.tensor([0.3, -0.5, 0.2, 1.0, -2.0, 0.5], device=device, dtype=dtype))
        p = (2 * torch.rand(points_shape) - 1).to(device, dtype)

        out = g * p

        assert out.shape == p.shape
        self.assert_close(out, torch.stack([g * q for q in p.reshape(-1, 3)]).reshape(points_shape))
        # R p + t in float64, on the CPU, from the same rounded pose and points: only the output is rounded
        r = So3(Quaternion(g.so3.q.data.cpu().double())).matrix()
        self.assert_close(out.cpu(), (p.cpu().double() @ r.mT + g.t.cpu().double()).to(dtype))

    # #6426: a pose maps (3,) or (N, 3) unbatched and one point per pose for a batch; other layouts, such as a
    # batch of poses with a point set, raise a ValueError that names the accepted layouts.
    @pytest.mark.parametrize(
        ("batch_size", "points_shape"), [(None, (2, 5, 3)), (2, (3,)), (2, (7, 3)), (2, (2, 7, 3)), (1, (1, 7, 3))]
    )
    def test_point_layout_outside_the_contract_raises(self, batch_size, points_shape, device, dtype):
        pose = Se3.identity(batch_size, device, dtype)
        with pytest.raises(ValueError, match=r"Expected points of shape \(3,\) or \(N, 3\)"):
            pose * torch.zeros(points_shape, device=device, dtype=dtype)

    @pytest.mark.parametrize(
        ("batch_size", "points_shape", "out_shape"),
        [(None, (3,), (3,)), (None, (7, 3), (7, 3)), (1, (7, 3), (7, 3)), (2, (2, 3), (2, 3)), (2, (1, 3), (2, 3))],
    )
    def test_point_layout_in_the_contract_maps(self, batch_size, points_shape, out_shape, device, dtype):
        pose = Se3.identity(batch_size, device, dtype)
        assert (pose * torch.zeros(points_shape, device=device, dtype=dtype)).shape == out_shape

    @pytest.mark.parametrize("batch_size", [None, 1, 2, 5])
    def test_mul_vector(self, device, dtype, batch_size):
        world_pose_s1: Se3 = self._make_rand_se3d(device, dtype, batch_size)
        world_pose_s2: Se3 = self._make_rand_se3d_vec(device, dtype, batch_size)
        shape = () if batch_size is None else (batch_size,)
        pt_in_world = Vector3.random(shape, device, dtype)
        s1_pose_s2: Se3 = world_pose_s1.inverse() * world_pose_s2
        pt_in_s1 = world_pose_s1.inverse() * pt_in_world
        pt_in_s2 = world_pose_s2.inverse() * pt_in_world
        pt_in_s1_in_s2 = s1_pose_s2.inverse() * pt_in_s1
        pt_in_s2_in_s1 = s1_pose_s2 * pt_in_s2
        s3 = Se3.identity(batch_size, device, dtype)
        s4: Se3 = self._make_rand_se3d_vec(device, dtype, batch_size)
        s3s4 = s3 * s4
        s4s4inv = s4 * s4.inverse()
        zeros_vec = torch.zeros(3, device=device, dtype=dtype)
        if batch_size is not None:
            zeros_vec = zeros_vec.repeat(batch_size, 1)
        so3_expected = So3.identity(batch_size, device, dtype)
        translations = (world_pose_s1.t, world_pose_s2.t)
        self._assert_chains_agree(pt_in_s1, pt_in_s2_in_s1, pt_in_world, *translations)
        self._assert_chains_agree(pt_in_s2, pt_in_s1_in_s2, pt_in_world, *translations)
        self.assert_close(s3s4.r.q.data, s4.r.q.data)
        self.assert_close(s3s4.t, s4.t)
        self.assert_close(s4s4inv.r.q.data, so3_expected.q.data)
        self.assert_close(s4s4inv.t, zeros_vec)

    @pytest.mark.parametrize(("left_batch", "right_batch"), [(None, 3), (3, None)])
    def test_mul_unbatched_with_batched(self, device, dtype, left_batch, right_batch):
        # #6481: composing an unbatched Se3 with a batch used to raise in torch.linalg.cross
        s1 = self._make_rand_se3d(device, dtype, left_batch)
        s2 = self._make_rand_se3d(device, dtype, right_batch)
        out = s1 * s2
        assert out.t.shape == (3, 3)
        self.assert_close(out.matrix(), s1.matrix() @ s2.matrix())

    def test_mul_mismatched_batches_raise(self, device, dtype):
        with pytest.raises(ValueError, match="Cannot multiply quaternions of batch shapes"):
            Se3.random(3, device, dtype) * Se3.random(2, device, dtype)

    @pytest.mark.parametrize("batch_size", [None, 1, 2, 5])
    def test_exp(self, device, dtype, batch_size):
        omega = torch.zeros(3, device=device, dtype=dtype)
        t = torch.rand(3, device=device, dtype=dtype)
        if batch_size is not None:
            omega = omega.repeat(batch_size, 1)
            t = t.repeat(batch_size, 1)
        s = Se3.exp(torch.cat((t, omega), -1))
        quat_expected = Quaternion.identity(batch_size, device, dtype)
        self.assert_close(s.r.q.data, quat_expected.data)
        self.assert_close(s.t, t)

    @pytest.mark.parametrize("batch_size", [None, 1, 2, 5])
    def test_log(self, device, dtype, batch_size):
        q = Quaternion.identity(batch_size, device, dtype)
        t = self._make_rand_data(device, dtype, batch_size, dims=3)
        s = Se3(So3(q), t)
        zero_vec = torch.zeros(3, device=device, dtype=dtype)
        if batch_size is not None:
            zero_vec = zero_vec.repeat(batch_size, 1)
        self.assert_close(s.log(), torch.cat((t, zero_vec), -1))

    def test_log_is_principal_4925(self, device, dtype):
        # Se3.log inherits So3.log: a small rotation stored with real < 0 got |omega| close to 2 pi and, through
        # V_inv(omega), a translation that was six orders of magnitude off. Both signs now give the principal log.
        theta = {torch.bfloat16: 1e-1, torch.float16: 1e-2, torch.float32: 1e-4, torch.float64: 1e-6}[dtype]
        rtol = 1e-2 if dtype in (torch.float16, torch.bfloat16) else 1e-4
        axis = torch.tensor([[0.48, 0.6, 0.64]], dtype=torch.float64)  # unit length
        q = Quaternion.from_axis_angle(theta * axis).data.to(device=device, dtype=dtype)  # rounded once
        axis = axis.to(device=device, dtype=dtype)
        t = torch.tensor([[1.0, 2.0, 3.0]], device=device, dtype=dtype)
        xi = Se3(So3(Quaternion(-q)), t).log()
        self.assert_close(xi, Se3(So3(Quaternion(q)), t).log())
        self.assert_close(xi[..., 3:], theta * axis, rtol=rtol, atol=0.0)
        self.assert_close(xi[..., :3], t, rtol=0.0, atol=3.0 * theta)
        # every random pose logs to a principal rotation vector
        torch.manual_seed(0)
        omega = Se3.random(64, device=device, dtype=dtype).log()[..., 3:]
        assert bool((omega.norm(dim=-1) <= torch.pi * (1 + rtol)).all())

    def test_exp_log_keep_small_rotations(self, device, dtype):
        # V and V_inv are built from (1 - cos theta) / theta**2 and friends, which evaluate to exactly 0
        # for theta <= 1e-4 in float32 (1e-8 in float64) and lose most of their digits well above that,
        # so the rotation-coupled part of the translation vanished for small rotations.
        theta = {torch.bfloat16: 1e-1, torch.float16: 1e-2, torch.float32: 1e-4, torch.float64: 1e-8}[dtype]
        rtol = 1e-2 if dtype in (torch.float16, torch.bfloat16) else 1e-4
        v = torch.tensor([[1.0, 0.0, 0.0, 0.0, 0.0, theta]], device=device, dtype=dtype)
        t = Se3.exp(v).t
        # translating along x while turning by theta about z ends at ((sin theta) / theta, (1 - cos theta) / theta, 0)
        expected_y = torch.tensor(theta / 2 - theta**3 / 24, device=device, dtype=dtype)
        self.assert_close(t[0, 1], expected_y, rtol=rtol, atol=0.0)
        self.assert_close(t[0, 2], torch.zeros((), device=device, dtype=dtype))
        v = torch.tensor([[1.0, 2.0, 3.0, 0.6 * theta, 0.0, 0.8 * theta]], device=device, dtype=dtype)
        self.assert_close(Se3.exp(v).log(), v, rtol=rtol, atol=0.0)

    @pytest.mark.parametrize("batch_size", [None, 1, 2, 5])
    def test_exp_log(self, device, dtype, batch_size):
        a = self._make_rand_data(device, dtype, batch_size, dims=6)
        b = Se3.exp(a).log()
        self.assert_close(b, a)

    @pytest.mark.parametrize("batch_size", [None, 1, 2, 5])
    def test_hat_vee(self, device, dtype, batch_size):
        a = self._make_rand_data(device, dtype, batch_size, dims=6)
        omega_hat = Se3.hat(a)
        b = Se3.vee(omega_hat)
        self.assert_close(b, a)

    @pytest.mark.parametrize("batch_size", [None, 1, 2, 5])
    def test_matrix(self, device, dtype, batch_size):
        q = Quaternion.random(batch_size, device, dtype)
        t = self._make_rand_data(device, dtype, batch_size, dims=3)
        rot = So3(q)
        s = Se3(rot, t)
        rot_mat = s.matrix()
        assert rot_mat.shape[-2:] == (4, 4)
        if batch_size is not None:
            assert rot_mat.shape[0] == batch_size
        self.assert_close(rot_mat[..., 0:3, 0:3], rot.matrix())
        self.assert_close(rot_mat[..., 0:3, 3], t)

    @pytest.mark.parametrize("batch_size", [None, 1, 2, 5])
    def test_from_matrix(self, device, dtype, batch_size):
        matrix = torch.tensor(
            ((1.0, 0.0, 0.0, 0.0), (0.0, 0.0, -1.0, 0.0), (0.0, 1.0, 0.0, 0.0), (0.0, 0.0, 0.0, 1.0)),
            device=device,
            dtype=dtype,
        )
        if batch_size is not None:
            matrix = matrix.repeat(batch_size, 1, 1)
        s = Se3.from_matrix(matrix)
        self.assert_close(s.r.matrix(), matrix[..., 0:3, 0:3])
        self.assert_close(s.t, matrix[..., 0:3, 3])

    @pytest.mark.parametrize("batch_size", [None, 1, 2])
    def test_from_matrix_check_rotation(self, device, dtype, batch_size):
        # kornia#4773: the rotation block reaches rotation_matrix_to_quaternion, so a reflection
        # block is accepted by default and yields a non-unit quaternion. check_rotation=True has
        # to pass through Se3 -> So3 -> Quaternion to reject it.
        matrix = torch.eye(4, device=device, dtype=dtype)
        matrix[0, 0] = -1.0
        if batch_size is not None:
            matrix = matrix.repeat(batch_size, 1, 1)

        Se3.from_matrix(matrix)  # default is unchecked, must not raise
        with pytest.raises(ValueError, match="reflection"):
            Se3.from_matrix(matrix, check_rotation=True)

    @pytest.mark.parametrize("batch_size", [None, 1, 2, 5])
    def test_from_matrix_check_rotation_accepts_rotation(self, device, dtype, batch_size):
        # A genuine rotation block passes, and the flag leaves both parts of the group element
        # alone. Comparing the checked call against the unchecked one rather than against the
        # input keeps this about the check: the round trip loses too much in half precision.
        rotation = So3(Quaternion.random(batch_size, device, dtype))
        translation = self._make_rand_data(device, dtype, batch_size, dims=3)
        matrix = Se3(rotation, translation).matrix()

        checked = Se3.from_matrix(matrix, check_rotation=True)
        unchecked = Se3.from_matrix(matrix)
        self.assert_close(checked.r.q.data, unchecked.r.q.data)
        self.assert_close(checked.t, unchecked.t)

    @pytest.mark.parametrize("batch_size", [None, 1, 2, 5])
    def test_from_qxyz(self, device, dtype, batch_size):
        qxyz = self._make_rand_data(device, dtype, batch_size, dims=7)
        s = Se3.from_qxyz(qxyz)
        self.assert_close(s.r.q.data, qxyz[..., :4].data)
        self.assert_close(s.t, qxyz[..., 4:])

    @pytest.mark.parametrize("batch_size", [None, 1, 2, 5])
    def test_inverse(self, device, dtype, batch_size):
        q = Quaternion.random(batch_size, device, dtype)
        rot = So3(q)
        t = self._make_rand_data(device, dtype, batch_size, dims=3)
        sinv = Se3(rot, t).inverse()
        self.assert_close(sinv.r.inverse().q.data, q.data)
        self.assert_close(sinv.t, sinv.r * (-1 * t))

    @pytest.mark.parametrize("batch_size", [None, 1, 2, 5])
    def test_rot_x(self, device, dtype, batch_size):
        x = self._make_rand_data(device, dtype, batch_size, dims=1).squeeze(-1)
        se3 = Se3.rot_x(x)
        quat = rotation_matrix_to_quaternion(se3.so3.matrix())
        quat = Quaternion(quat)
        roll, _, _ = euler_from_quaternion(*quat.coeffs)
        self.assert_close(x, roll)
        self.assert_close(se3.t, torch.zeros_like(se3.t))

    @pytest.mark.parametrize("batch_size", [None, 1, 2, 5])
    def test_rot_y(self, device, dtype, batch_size):
        y = self._make_rand_data(device, dtype, batch_size, dims=1).squeeze(-1)
        se3 = Se3.rot_y(y)
        quat = rotation_matrix_to_quaternion(se3.so3.matrix())
        quat = Quaternion(quat)
        _, pitch, _ = euler_from_quaternion(*quat.coeffs)
        self.assert_close(y, pitch)
        self.assert_close(se3.t, torch.zeros_like(se3.t))

    @pytest.mark.parametrize("batch_size", [None, 1, 2, 5])
    def test_rot_z(self, device, dtype, batch_size):
        z = self._make_rand_data(device, dtype, batch_size, dims=1).squeeze(-1)
        se3 = Se3.rot_z(z)
        quat = rotation_matrix_to_quaternion(se3.so3.matrix())
        quat = Quaternion(quat)
        _, _, yaw = euler_from_quaternion(*quat.coeffs)
        self.assert_close(z, yaw)
        self.assert_close(se3.t, torch.zeros_like(se3.t))

    @pytest.mark.parametrize("batch_size", [None, 1, 2, 5])
    def test_trans(self, device, dtype, batch_size):
        trans = self._make_rand_data(device, dtype, batch_size, dims=3)
        x, y, z = trans[..., 0], trans[..., 1], trans[..., 2]
        se3 = Se3.trans(x, y, z)
        self.assert_close(se3.t, trans)
        self.assert_close(se3.so3.matrix(), So3.identity(batch_size, device, dtype).matrix())

    @pytest.mark.parametrize("batch_size", [None, 1, 2, 5])
    def test_trans_x(self, device, dtype, batch_size):
        x = self._make_rand_data(device, dtype, batch_size, dims=1).squeeze(-1)
        zs = torch.zeros_like(x)
        se3 = Se3.trans_x(x)
        self.assert_close(se3.t, torch.stack((x, zs, zs), -1))
        self.assert_close(se3.so3.matrix(), So3.identity(batch_size, device, dtype).matrix())

    @pytest.mark.parametrize("batch_size", [None, 1, 2, 5])
    def test_trans_y(self, device, dtype, batch_size):
        y = self._make_rand_data(device, dtype, batch_size, dims=1).squeeze(-1)
        zs = torch.zeros_like(y)
        se3 = Se3.trans_y(y)
        self.assert_close(se3.t, torch.stack((zs, y, zs), -1))
        self.assert_close(se3.so3.matrix(), So3.identity(batch_size, device, dtype).matrix())

    @pytest.mark.parametrize("batch_size", [None, 1, 2, 5])
    def test_trans_z(self, device, dtype, batch_size):
        z = self._make_rand_data(device, dtype, batch_size, dims=1).squeeze(-1)
        zs = torch.zeros_like(z)
        se3 = Se3.trans_z(z)
        self.assert_close(se3.t, torch.stack((zs, zs, z), -1))
        self.assert_close(se3.so3.matrix(), So3.identity(batch_size, device, dtype).matrix())

    @pytest.mark.parametrize("batch_size", [None, 1, 2, 5])
    def test_adjoint(self, device, dtype, batch_size):
        shape = (6,) if batch_size is None else (batch_size, 6)
        x_data = torch.tensor([0.1, -0.2, 0.3, 0.2, -0.1, 0.1], device=device, dtype=dtype).expand(shape)
        y_data = torch.tensor([-0.2, 0.1, 0.2, -0.1, 0.2, 0.1], device=device, dtype=dtype).expand(shape)
        x = Se3.exp(x_data)
        y = Se3.exp(y_data)
        adjoint = x.adjoint()
        inverse_adjoint = x.inverse().adjoint()
        identity = torch.eye(adjoint.shape[-1], device=device, dtype=dtype).expand_as(adjoint)
        half_tolerance = torch.finfo(dtype).eps if dtype in (torch.float16, torch.bfloat16) else None
        self.assert_close(adjoint @ inverse_adjoint, identity, rtol=half_tolerance, atol=half_tolerance)
        self.assert_close((x * y).adjoint(), adjoint @ y.adjoint(), rtol=half_tolerance, atol=half_tolerance)

    @pytest.mark.parametrize("batch_size", [None, 1, 2, 5])
    def test_random(self, device, dtype, batch_size):
        s = Se3.random(batch_size=batch_size, device=device, dtype=dtype)
        s_in_s = s.inverse() * s
        i = Se3.identity(batch_size=batch_size, device=device, dtype=dtype)
        self.assert_close(s_in_s.so3.q.data, i.so3.q.data)
        self.assert_close(s_in_s.t, i.t)

    def test_user_leaf_translation_receives_the_gradient(self, device, dtype):
        # A tensor that requires grad is kept, not re-wrapped as a new Parameter, so the gradient reaches it (#4943).
        t = torch.tensor([[1.0, 2.0, 3.0]], device=device, dtype=dtype, requires_grad=True)
        s = Se3(So3.identity(1, device, dtype), t)
        (s * torch.tensor([[1.0, 0.0, 0.0]], device=device, dtype=dtype)).sum().backward()
        assert t.grad is not None
        self.assert_close(t.grad, torch.ones_like(t))
        assert "_translation" in s.state_dict()
        # a tensor that does not require grad still becomes an optimizable parameter
        plain = Se3(So3.identity(1, device, dtype), torch.zeros(1, 3, device=device, dtype=dtype))
        assert [name for name, _ in plain.named_parameters()] == ["_translation"]

    def test_integer_translation_raises(self, device):
        with pytest.raises(TypeCheckError, match=r"Se3 stores 'translation'.*torch.int64"):
            Se3(Quaternion.identity(1, device), torch.tensor([[1, 2, 3]], device=device))

    @pytest.mark.parametrize(
        "pair",
        [
            (torch.float64, torch.float32),
            (torch.float32, torch.float64),
            (torch.float32, torch.float16),
            (torch.float16, torch.float32),
        ],
    )
    @pytest.mark.parametrize("wrap", ["so3", "quaternion"])
    def test_mixed_dtype_translation_raises_5913(self, device, pair, wrap):
        # The mix used to construct, then inverse()/adjoint()/__mul__ raised torch's "expected scalar type" error.
        if device.type == "mps" and torch.float64 in pair:
            pytest.skip("MPS has no float64")
        r_dtype, t_dtype = pair
        rotation = So3.identity(1, device, r_dtype) if wrap == "so3" else Quaternion.identity(1, device, r_dtype)
        with pytest.raises(
            TypeCheckError, match=r"Se3 translation must have the dtype of its rotation.*" + str(t_dtype)
        ):
            Se3(rotation, torch.zeros(1, 3, device=device, dtype=t_dtype))
        with pytest.raises(TypeCheckError, match=r"Se3 translation"):
            Se3(rotation, Vector3(torch.zeros(1, 3, device=device, dtype=t_dtype)))

    def test_same_dtype_translation_is_accepted_5913(self, device, dtype):
        s = Se3(So3.identity(2, device, dtype), torch.zeros(2, 3, device=device, dtype=dtype))
        assert s.t.dtype == s.quaternion.data.dtype == dtype

    @pytest.mark.skipif(not dynamo_is_available(), reason=DYNAMO_UNAVAILABLE_REASON)
    def test_dynamo_constructor_checks_5913(self, device, torch_optimizer):
        def build(q, t):
            return Se3(Quaternion(q), t).matrix()

        args = (torch.rand(2, 4, device=device), torch.rand(2, 3, device=device))
        self.assert_close(torch_optimizer(build, fullgraph=True)(*args), build(*args))

    @pytest.mark.parametrize("cdtype", [torch.cfloat, torch.cdouble])
    def test_complex_translation_raises_5913(self, device, cdtype):
        if device.type == "mps" and cdtype != torch.cfloat:
            pytest.skip("MPS supports complex64 only")
        with pytest.raises(TypeCheckError, match=r"Se3 translation must be a real floating-point tensor.*complex"):
            Se3(So3.identity(1, device), torch.zeros(1, 3, device=device, dtype=cdtype))

    @pytest.mark.parametrize("int_dtype", [torch.int64, torch.bool])
    def test_integer_parameter_translation_raises_5913(self, device, int_dtype):
        translation = torch.nn.Parameter(torch.zeros(1, 3, device=device, dtype=int_dtype), requires_grad=False)
        with pytest.raises(TypeCheckError, match=r"Se3 stores 'translation'.*" + str(int_dtype)):
            Se3(So3.identity(1, device), translation)

    def test_translation_on_another_device_raises_5913(self, device):
        # the meta device stands in for a second accelerator.
        with pytest.raises(DeviceError, match=r"Se3 translation must be on the device of its rotation"):
            Se3(So3.identity(1, device), torch.zeros(1, 3, device="meta"))

    def test_internal_constructions_still_build_5913(self, device, dtype):
        a = Se3.exp(torch.rand(2, 6, device=device, dtype=dtype))
        x = torch.rand(2, device=device, dtype=dtype)
        built = [
            Se3.identity(None, device, dtype),
            Se3.identity(2, device, dtype),
            Se3.random(None, device, dtype),
            Se3.random(2, device, dtype),
            Se3.from_matrix(a.matrix().detach()),
            Se3.from_qxyz(torch.rand(2, 7, device=device, dtype=dtype)),
            Se3.rot_x(x),
            Se3.rot_y(x),
            Se3.rot_z(x),
            Se3.trans(x, x, x),
            Se3.trans_x(x),
            Se3.trans_y(x),
            Se3.trans_z(x),
            a[0],
            a.inverse(),
            a * a,
            NamedPose.from_rt(So3.identity(1, device, dtype), torch.zeros(1, 3, device=device, dtype=dtype)).pose,
        ]
        assert all(isinstance(s, Se3) for s in built)
        assert all(s.t.dtype == dtype for s in built)

    def test_derived_state_moves_and_serializes(self, device, dtype):
        v = torch.rand(2, 6, device=device, dtype=dtype, requires_grad=True)
        s = Se3.exp(v)
        assert s.t.grad_fn is not None
        assert "_translation" in s.state_dict()
        restored = Se3(So3.identity(2, device, dtype), torch.zeros(2, 3, device=device, dtype=dtype))
        assert list(restored.state_dict()) == list(s.state_dict()) == ["_translation", "_rotation._q._data"]
        restored.load_state_dict(s.state_dict())
        self.assert_close(restored.t, s.t.detach())
        self.assert_close(restored.quaternion.data, s.quaternion.data.detach())
        self.assert_close(restored.matrix(), s.matrix().detach())
        other = torch.float16 if dtype == torch.float32 else torch.float32  # float64 is unavailable on MPS
        moved = s.to(other)
        assert moved.t.dtype == other
        assert moved.t.grad_fn is not None
        assert moved.quaternion.data.dtype == other
        assert moved.quaternion.data.grad_fn is not None
        moved.t.sum().backward()
        assert v.grad is not None

    def test_convention_se3_tangent_is_upsilon_omega_with_V(self, device, dtype):
        # The tangent is (upsilon, omega), translation part first: exp rotates by the rotation vector omega and
        # translates by V(omega) upsilon. Reference, float64: m = scipy.linalg.expm of
        # [[0, 0.3, 0.2, 1], [-0.3, 0, -0.4, -2], [-0.2, 0.4, 0, 3], [0, 0, 0, 0]]; t = m[:3, 3], R = m[:3, :3].
        v = torch.tensor([1.0, -2.0, 3.0, 0.4, 0.2, -0.3], device=device, dtype=dtype)
        g = Se3.exp(v)
        t_expected = torch.tensor(
            [0.8932266973410874, -2.666342656131567, 2.413407159033739], device=device, dtype=dtype
        )
        r_expected = torch.tensor(
            [
                [0.9365557269934556, 0.32475143364814213, 0.13190859175670216],
                [-0.24666617456316434, 0.8779917826797222, -0.4102270442977377],
                [-0.24903648038416887, 0.35166309998400436, 0.9023934261437778],
            ],
            device=device,
            dtype=dtype,
        )
        assert (t_expected - v[:3]).abs().max() > 0.1  # V is not the identity at this rotation
        self.assert_close(g.t, t_expected)
        self.assert_close(g.r.matrix(), r_expected)
        self.assert_close(g.r.log(), v[3:])

    def test_convention_se3_hat_layout(self, device, dtype):
        # hat(upsilon, omega) = [[hat(omega), upsilon], [0, 0]]: the cross-product matrix of omega in the top-left
        # block, upsilon in the last column, a zero bottom row. Its matrix exponential is exp(v).matrix().
        v = torch.tensor([1.0, -2.0, 3.0, 0.4, 0.2, -0.3], device=device, dtype=dtype)
        expected = torch.tensor(
            [[0.0, 0.3, 0.2, 1.0], [-0.3, 0.0, -0.4, -2.0], [-0.2, 0.4, 0.0, 3.0], [0.0, 0.0, 0.0, 0.0]],
            device=device,
            dtype=dtype,
        )
        m = Se3.hat(v)
        self.assert_close(m, expected)
        # matrix_exp has no half-precision kernel and MPS has no float64: take it in float64 on the CPU. Move first,
        # then cast: on torch 2.14 a single m.to("cpu", torch.float64) from MPS returns zeros.
        m_exp = torch.linalg.matrix_exp(m.cpu().double()).to(device=device, dtype=dtype)
        self.assert_close(m_exp, Se3.exp(v).matrix())

    def test_convention_se3_adjoint_conjugates_the_tangent(self, device, dtype):
        # g exp(v) = exp(Ad(g) v) g, with Ad(g) = [[R, hat(t) R], [0, R]] for the (upsilon, omega) tangent.
        g = Se3.exp(torch.tensor([1.0, -2.0, 3.0, 0.4, 0.2, -0.3], device=device, dtype=dtype))
        v = torch.tensor([0.3, 0.1, -0.2, -0.1, 0.3, 0.05], device=device, dtype=dtype)
        ad_v = (g.adjoint() @ v[:, None])[:, 0]
        assert (ad_v - v).abs().max() > 0.1  # g does not commute with exp(v)
        self.assert_close((g * Se3.exp(v)).matrix(), (Se3.exp(ad_v) * g).matrix())

    def test_convention_se3_composition_is_left_matrix_product(self, device, dtype):
        # a * b is the matrix product a b: b acts first on a point.
        a = Se3.exp(torch.tensor([1.0, -2.0, 3.0, 0.4, 0.2, -0.3], device=device, dtype=dtype))
        b = Se3.exp(torch.tensor([0.3, 0.1, -0.2, -0.1, 0.3, 0.05], device=device, dtype=dtype))
        self.assert_close(a.r.q.norm(), torch.ones((), device=device, dtype=dtype))
        self.assert_close(b.r.q.norm(), torch.ones((), device=device, dtype=dtype))
        ab, ba = a.matrix() @ b.matrix(), b.matrix() @ a.matrix()
        assert (ab - ba).abs().max() > 0.1  # a non-commuting pair
        self.assert_close((a * b).matrix(), ab)
        p = torch.tensor([0.7, -1.3, 2.1], device=device, dtype=dtype)
        self.assert_close((a * b) * p, a * (b * p))

    def test_convention_se3_from_qxyz_is_wxyz_then_xyz(self, device, dtype):
        # The seven numbers are the quaternion (w, x, y, z), then the translation (x, y, z).
        # Reference: 95 * scipy.spatial.transform.Rotation.from_quat(q).as_matrix(), which takes (x, y, z, w), for
        # q = (1, -3, 2, 9) (the wxyz reading) and q = (9, 1, -3, 2) (the xyzw reading).
        q = torch.tensor([9.0, 1.0, -3.0, 2.0], dtype=torch.float64) / math.sqrt(95.0)
        qxyz = torch.cat((q, torch.tensor([5.0, 6.0, 7.0], dtype=torch.float64))).to(device=device, dtype=dtype)
        wxyz = torch.tensor([[69.0, -42.0, -50.0], [30.0, 85.0, -30.0], [58.0, 6.0, 75.0]], device=device, dtype=dtype)
        xyzw = torch.tensor(
            [[75.0, 30.0, -50.0], [6.0, -85.0, -42.0], [-58.0, 30.0, -69.0]], device=device, dtype=dtype
        )
        assert (wxyz - xyzw).abs().max() > 50.0  # the two readings differ
        g = Se3.from_qxyz(qxyz)
        self.assert_close(g.r.matrix(), wxyz / 95.0)
        self.assert_close(g.t.data, torch.tensor([5.0, 6.0, 7.0], device=device, dtype=dtype))

    def test_convention_se3_from_matrix_ignores_the_bottom_row(self, device, dtype):
        # from_matrix reads the rotation block and the last column; it does not check the bottom row.
        clean = Se3.exp(torch.tensor([1.0, -2.0, 3.0, 0.4, 0.2, -0.3], device=device, dtype=dtype)).matrix().detach()
        junk = clean.clone()
        junk[3] = torch.tensor([0.5, -4.0, 7.0, 2.0], device=device, dtype=dtype)
        self.assert_close(Se3.from_matrix(junk).matrix(), clean)

    def test_se3_translation_is_a_tensor_for_every_constructor_4931(self, device, dtype):
        # https://github.com/kornia/kornia/issues/4931: every constructor registers the translation as a tensor, so
        # tensor indexing, state_dict and dtype casts work the same for identity, random, from_qxyz, a Vector3 input
        # and the poses derived from them.
        from_exp = Se3.exp(torch.zeros(1, 6, device=device, dtype=dtype))
        identity = Se3.identity(1, device, dtype)
        self.assert_close(identity.matrix(), from_exp.matrix())  # the same group element
        qxyz = torch.tensor([[1.0, 0.0, 0.0, 0.0, 5.0, 6.0, 7.0]], device=device, dtype=dtype)
        p = torch.tensor([[1.0, 2.0, 3.0]], device=device, dtype=dtype)
        poses = (
            identity,
            Se3.random(1, device, dtype),
            Se3.from_qxyz(qxyz),
            Se3(Quaternion.identity(1, device, dtype), Vector3(p)),
            from_exp * identity,
            identity.inverse(),
        )
        for pose in poses:
            assert isinstance(pose.t, torch.Tensor)
            assert pose.t.shape == (1, 3)
            assert "_translation" in pose.state_dict()
        self.assert_close(identity.t[..., 0], torch.zeros(1, device=device, dtype=dtype))
        self.assert_close(Se3.from_qxyz(qxyz).t, qxyz[..., 4:])
        # ``.half()`` / ``.float()`` reach the identity's translation (float64 is unavailable on MPS, so convert
        # towards float16 from float32)
        fresh = Se3.identity(1, device, dtype)
        converted = fresh.half() if dtype == torch.float32 else fresh.float()
        assert converted.t.dtype == (torch.float16 if dtype == torch.float32 else torch.float32)
        # g * p is a tensor for a tensor p and a Vector3 for a Vector3 p, whichever constructor built g.
        assert type(identity * p) is torch.Tensor
        self.assert_close(identity * p, p)
        assert isinstance(identity * Vector3(p), Vector3)
        self.assert_close((identity * Vector3(p)).data, p)

    def test_se3_state_dict_restores_translation_and_rotation_4923(self, device, dtype):
        src = Se3.exp(torch.tensor([[1.0, -2.0, 3.0, 0.4, 0.2, -0.3]], device=device, dtype=dtype))
        dst = Se3(Quaternion.identity(1, device, dtype), torch.zeros(1, 3, device=device, dtype=dtype))
        eye = torch.eye(3, device=device, dtype=dtype)[None]
        assert (src.r.matrix() - eye).abs().max() > 0.1  # the source rotation is not the identity
        # #4923: loading must restore the entire pose, including a plain tensor rotation.
        assert list(src.state_dict()) == ["_translation", "_rotation._q._data"]
        assert list(Se3.identity(1, device, dtype).state_dict()) == list(src.state_dict())
        result = dst.load_state_dict(src.state_dict())
        assert not result.missing_keys
        assert not result.unexpected_keys
        self.assert_close(dst.t, src.t.detach())
        self.assert_close(dst.quaternion.data, src.quaternion.data)
        self.assert_close(dst.r.matrix(), src.r.matrix())
        self.assert_close(dst.matrix(), src.matrix())
        point = torch.tensor([[1.0, 2.0, 3.0]], device=device, dtype=dtype)
        self.assert_close(dst * point, src * point)
        assert list(dict(dst.named_parameters())) == ["_translation"]
        assert list(dict(dst.named_buffers())) == ["_rotation._q._data"]

    def test_parent_casts_rotation_and_translation_4923(self, device, dtype):
        if device.type == "mps":
            pytest.skip("MPS does not support float64")
        pose = Se3(Quaternion.identity(1, device, dtype), torch.ones(1, 3, device=device, dtype=dtype))
        parent = torch.nn.ModuleDict({"pose": pose})
        for method, expected_dtype in (("double", torch.float64), ("float", torch.float32)):
            assert getattr(parent, method)() is parent
            assert pose.quaternion.data.dtype == expected_dtype
            assert pose.t.dtype == expected_dtype
            point = torch.zeros(1, 3, device=device, dtype=expected_dtype)
            self.assert_close(pose * point, torch.ones_like(point))

    def test_old_checkpoint_missing_rotation_4923(self, device, dtype):
        pose = Se3.identity(1, device, dtype)
        old_state = {"_translation": torch.ones(1, 3, device=device, dtype=dtype)}
        with pytest.raises(RuntimeError, match=r'Missing key.*"_rotation\._q\._data"'):
            pose.load_state_dict(old_state, strict=True)
        result = pose.load_state_dict(old_state, strict=False)
        assert result.missing_keys == ["_rotation._q._data"]
        assert result.unexpected_keys == []
        self.assert_close(pose.t, old_state["_translation"])
        self.assert_close(pose.quaternion.data, torch.tensor([[1.0, 0.0, 0.0, 0.0]], device=device, dtype=dtype))

    def test_random_translation_is_uniform_in_the_unit_interval(self, device, dtype):
        # random draws its translation with torch.rand, which the Vector3 it used to build drew as well (#4931).
        torch.manual_seed(0)
        t = Se3.random(1000, device=device, dtype=dtype).t
        assert t.shape == (1000, 3)
        assert t.min() >= 0, (t.min(), t.max())
        assert t.max() <= 1, (t.min(), t.max())
        assert 0.45 < t.mean() < 0.55, t.mean()

    def test_se3_batch_validation(self, device: torch.device, dtype: torch.dtype) -> None:
        # Incompatible batch sizes (mismatched batches)
        q_b3 = Quaternion.identity(3, device=device, dtype=dtype)
        t_b2 = torch.zeros(2, 3, device=device, dtype=dtype)
        with pytest.raises(ValueError, match="broadcasts"):
            Se3(q_b3, t_b2)

        so3_b3 = So3.identity(3, device=device, dtype=dtype)
        with pytest.raises(ValueError, match="broadcasts"):
            Se3(so3_b3, t_b2)

        with pytest.raises(ValueError, match=r"Shape mismatch at dimension.*expected 3, got 4"):
            Se3(so3_b3, torch.zeros(3, 4, device=device, dtype=dtype))

        # 1. Unbatched rotation with batched translation: Se3(So3.random(), torch.rand(5, 3))
        r_unb = So3.random(device=device, dtype=dtype)
        t_b5 = torch.rand(5, 3, device=device, dtype=dtype)
        pose_unb_r = Se3(r_unb, t_b5)
        ref_unb_r = Se3(So3(Quaternion(r_unb.q.data.expand(5, 4))), t_b5.clone())
        self.assert_close(pose_unb_r.matrix(), ref_unb_r.matrix())
        self.assert_close(pose_unb_r.log(), ref_unb_r.log())
        self.assert_close(pose_unb_r.adjoint(), ref_unb_r.adjoint())
        self.assert_close(pose_unb_r.inverse().matrix(), ref_unb_r.inverse().matrix())

        other5 = Se3.random(5, device=device, dtype=dtype)
        self.assert_close((pose_unb_r * other5).matrix(), (ref_unb_r * other5).matrix())
        self.assert_close((other5 * pose_unb_r).matrix(), (other5 * ref_unb_r).matrix())

        pts5 = torch.rand(5, 3, device=device, dtype=dtype)
        self.assert_close(pose_unb_r * pts5, ref_unb_r * pts5)
        pts1 = torch.rand(1, 3, device=device, dtype=dtype)
        self.assert_close(pose_unb_r * pts1, ref_unb_r * pts1)
        # an unbatched rotation keeps taking one point for all the translations, as on main
        self.assert_close(pose_unb_r * pts5[0], ref_unb_r * pts5[0].expand(5, 3))
        with pytest.raises(RuntimeError):
            _ = pose_unb_r * torch.rand(4, 3, device=device, dtype=dtype)

        for i in range(5):
            self.assert_close(pose_unb_r[i].matrix(), ref_unb_r[i].matrix())
        self.assert_close(pose_unb_r[1:4].matrix(), ref_unb_r[1:4].matrix())
        self.assert_close(pose_unb_r[::2].matrix(), ref_unb_r[::2].matrix())

        # 2. Batched rotation with unbatched translation: Se3(So3.random(3), torch.rand(3))
        r_b3 = So3.random(3, device=device, dtype=dtype)
        t_unb = torch.rand(3, device=device, dtype=dtype)
        pose_unb_t = Se3(r_b3, t_unb)
        ref_unb_t = Se3(r_b3, t_unb.expand(3, 3).clone())
        self.assert_close(pose_unb_t.matrix(), ref_unb_t.matrix())
        self.assert_close(pose_unb_t.log(), ref_unb_t.log())
        self.assert_close(pose_unb_t.adjoint(), ref_unb_t.adjoint())
        self.assert_close(pose_unb_t.inverse().matrix(), ref_unb_t.inverse().matrix())

        other3 = Se3.random(3, device=device, dtype=dtype)
        self.assert_close((pose_unb_t * other3).matrix(), (ref_unb_t * other3).matrix())
        self.assert_close((other3 * pose_unb_t).matrix(), (other3 * ref_unb_t).matrix())

        pts3 = torch.rand(3, 3, device=device, dtype=dtype)
        self.assert_close(pose_unb_t * pts3, ref_unb_t * pts3)
        self.assert_close(pose_unb_t * pts1, ref_unb_t * pts1)
        with pytest.raises(ValueError):
            _ = pose_unb_t * torch.rand(4, 3, device=device, dtype=dtype)

        for i in range(3):
            self.assert_close(pose_unb_t[i].matrix(), ref_unb_t[i].matrix())
        self.assert_close(pose_unb_t[0:2].matrix(), ref_unb_t[0:2].matrix())

        # 3. Both unbatched
        pose_unb_both = Se3(r_unb, t_unb)
        assert pose_unb_both.matrix().shape == (4, 4)
        assert pose_unb_both.log().shape == (6,)
        assert pose_unb_both.adjoint().shape == (6, 6)
        assert pose_unb_both.inverse().matrix().shape == (4, 4)
        t_homo = torch.cat((t_unb, torch.tensor([1.0], device=device, dtype=dtype)))
        self.assert_close(pose_unb_both * t_unb, (pose_unb_both.matrix() @ t_homo)[:3])

        # 4. Singleton batch broadcasting: (1,) and (4,)
        s_sing1 = Se3(So3.random(1, device=device, dtype=dtype), torch.rand(4, 3, device=device, dtype=dtype))
        ref_sing1 = Se3(So3(Quaternion(s_sing1.r.q.data.expand(4, 4))), s_sing1.t.clone())
        self.assert_close(s_sing1.matrix(), ref_sing1.matrix())
        self.assert_close(s_sing1.log(), ref_sing1.log())
        self.assert_close(s_sing1.adjoint(), ref_sing1.adjoint())
        self.assert_close(s_sing1.inverse().matrix(), ref_sing1.inverse().matrix())

        s_sing2 = Se3(So3.random(4, device=device, dtype=dtype), torch.rand(1, 3, device=device, dtype=dtype))
        ref_sing2 = Se3(s_sing2.r, s_sing2.t.expand(4, 3).clone())
        self.assert_close(s_sing2.matrix(), ref_sing2.matrix())
        self.assert_close(s_sing2.log(), ref_sing2.log())
        self.assert_close(s_sing2.adjoint(), ref_sing2.adjoint())
        self.assert_close(s_sing2.inverse().matrix(), ref_sing2.inverse().matrix())

        # 5. Multi-dimensional broadcast batches: (2, 1) rotation and (1, 3) translation
        q_raw = torch.randn(2, 1, 4, device=device, dtype=dtype)
        q_raw = q_raw / q_raw.norm(dim=-1, keepdim=True)
        q_2x1 = Quaternion(q_raw)
        t_1x3 = torch.rand(1, 3, 3, device=device, dtype=dtype)
        s_multi = Se3(q_2x1, t_1x3)
        ref_multi = Se3(So3(Quaternion(q_raw.expand(2, 3, 4))), t_1x3.expand(2, 3, 3).clone())
        self.assert_close(s_multi.matrix(), ref_multi.matrix())
        self.assert_close(s_multi.log(), ref_multi.log())
        self.assert_close(s_multi.adjoint(), ref_multi.adjoint())
        self.assert_close(s_multi.inverse().matrix(), ref_multi.inverse().matrix())
        self.assert_close(s_multi[0].matrix(), ref_multi[0].matrix())
        self.assert_close(s_multi[1].matrix(), ref_multi[1].matrix())
        self.assert_close(s_multi[1:].matrix(), ref_multi[1:].matrix())
        self.assert_close(s_multi[0:2].matrix(), ref_multi[0:2].matrix())


class TestSe3HalfPrecision(BaseTester):
    # g * p and a * b compute in float32 for float16/bfloat16 inputs and round once to the input dtype, and the
    # rotation follows So3 (TestSo3HalfPrecision). Evaluated in half precision, the chains of test_mul, test_mul_point
    # and test_mul_vector drifted past their 1-2 unit tolerances.

    @staticmethod
    def _poses(device, dtype, n):
        # translations in [-0.5, 0.5): every output below stays under 2 in magnitude
        a = Se3(So3.random(n, device, dtype), torch.rand(n, 3, device=device, dtype=dtype) - 0.5)
        b = Se3(So3.random(n, device, dtype), torch.rand(n, 3, device=device, dtype=dtype) - 0.5)
        return a, b, torch.rand(n, 3, device=device, dtype=dtype) - 0.5

    @staticmethod
    def _cast(s, dtype):
        """The same pose in ``dtype``; a float64 copy goes to the CPU, since MPS has no float64."""
        q, t = s.r.q.data, s.t
        if dtype == torch.float64:
            q, t = q.cpu(), t.cpu()
        return Se3(So3(Quaternion(q.to(dtype))), t.to(dtype))

    def test_float32_and_float64_are_evaluated_in_their_own_dtype(self, device, dtype):
        if dtype not in (torch.float32, torch.float64):
            pytest.skip("float16 and bfloat16 are computed in float32 (test_half_precision_rounds_float32_once)")
        a, b, p = self._poses(device, dtype, 5)
        # bit for bit the group formulas in the input dtype, with no detour through another dtype
        assert torch.equal(a * p, a.r * p + a.t)
        assert torch.equal((a * Vector3(p)).data, a.r * p + a.t)
        assert torch.equal((a * b).t, a.t + a.r * b.t)
        assert torch.equal((a * b).r.q.data, (a.r * b.r).q.data)
        assert torch.equal(a.inverse().t, a.r.inverse() * (-1 * a.t))
        assert torch.equal(a.matrix()[..., :3, :3], a.r.matrix())

    def test_half_precision_rounds_float32_once(self, device, dtype):
        if dtype not in (torch.float16, torch.bfloat16):
            pytest.skip("only float16 and bfloat16 inputs are computed in float32")
        a, b, p = self._poses(device, dtype, 5)
        a32, b32 = self._cast(a, torch.float32), self._cast(b, torch.float32)
        for actual, wide in (
            (a * p, a32 * p.float()),
            ((a * Vector3(p)).data, a32 * p.float()),
            ((a * b).t, (a32 * b32).t),
            ((a * b).r.q.data, (a32 * b32).r.q.data),
            (a.inverse().t, a32.inverse().t),
            (a.matrix(), a32.matrix()),
        ):
            assert actual.dtype == dtype
            assert torch.equal(actual, wide.to(dtype))

    def test_half_precision_matches_float64_within_one_rounding(self, device, dtype):
        if dtype not in (torch.float16, torch.bfloat16):
            pytest.skip("float32 and float64 are evaluated in their own dtype")
        # The reference is float64 from the same rounded inputs. Every output is below 2 in magnitude, where one
        # rounding costs at most eps / 2 (plus a float32 error far below it); evaluated in half precision, g * p
        # rounded the rotated point and then the sum.
        eps = torch.finfo(dtype).eps
        a, b, p = self._poses(device, dtype, 1000)
        a64, b64, p64 = self._cast(a, torch.float64), self._cast(b, torch.float64), p.cpu().double()
        self.assert_close((a * p).cpu().double(), a64 * p64, rtol=0.0, atol=eps)
        self.assert_close((a * b).t.cpu().double(), (a64 * b64).t, rtol=0.0, atol=eps)
        self.assert_close(a.inverse().t.cpu().double(), a64.inverse().t, rtol=0.0, atol=eps)

    def test_half_precision_backward(self, device, dtype):
        if dtype not in (torch.float16, torch.bfloat16):
            pytest.skip("float32 and float64 gradients are covered by test_gradcheck")
        a, b, p = self._poses(device, dtype, 4)
        leaves = [a.r.q.data.detach(), a.t.detach(), b.t.detach(), p.detach()]
        leaves = [x.requires_grad_(True) for x in leaves]
        leaves32 = [x.detach().float().requires_grad_(True) for x in leaves]
        for q, t, t_b, x in (leaves, leaves32):
            s = Se3(So3(Quaternion(q)), t)
            s_b = Se3(Quaternion(b.r.q.data.to(q.dtype)), t_b)
            ((s * x).sum() + (s * s_b).t.sum() + s.inverse().t.sum() + s.matrix().sum()).backward()
        for grad, grad32 in zip((x.grad for x in leaves), (x.grad for x in leaves32)):
            assert grad.dtype == dtype
            assert bool(torch.isfinite(grad).all())
            self.assert_close(grad, grad32.to(dtype), low_tolerance=True)