Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

57.2 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 BaseError, DeviceError, TypeCheckError
from kornia.geometry.liegroup import Se2, So2
from kornia.geometry.pose import NamedPose
from kornia.geometry.vector import Vector2

from testing.base import DYNAMO_UNAVAILABLE_REASON, BaseTester, dynamo_is_available


def _complex_dtype(dtype: torch.dtype) -> torch.dtype:
    """Complex dtype whose real dtype is ``dtype``; bfloat16 has none, and Se2 pairs its rotation with complex64."""
    return {torch.float16: torch.chalf, torch.float64: torch.cdouble}.get(dtype, torch.cfloat)


class TestSe2(BaseTester):
    def _make_rand_data(self, device, dtype, input_shape):
        batch_size = input_shape[0]
        shape = input_shape[1:] if batch_size is None else input_shape
        return torch.rand(shape, device=device, dtype=dtype)

    def test_smoke(self, device, dtype):
        z = torch.rand((2,), dtype=torch.cfloat, device=device).to(_complex_dtype(dtype))
        so2 = So2(z)
        t = torch.rand((1, 2), device=device, dtype=dtype)
        s = Se2(so2, t)
        assert isinstance(s, Se2)
        assert isinstance(s.r, So2)
        self.assert_close(s.r.z.data, z)
        self.assert_close(s.t, t)

    @pytest.mark.parametrize("input_shape", [(1,), (2,), (5,), ()])
    def test_cardinality(self, device, dtype, input_shape):
        if dtype == torch.bfloat16:
            pytest.skip("torch has no complex bfloat16 dtype, which So2 stores its rotation in")
        t_input_shape = (*input_shape, 2)
        z = torch.randn((*input_shape, 2), dtype=dtype, device=device)
        t = torch.randn(t_input_shape, dtype=dtype, device=device)
        s = Se2(So2(torch.complex(z[..., 0], z[..., 1])), t)
        theta = torch.rand((*input_shape, 3), dtype=dtype, device=device)
        assert s.so2.z.shape == input_shape
        assert s.t.shape == t_input_shape
        assert (s * s).so2.z.shape == input_shape
        assert (s * s).t.shape == t_input_shape
        assert s.exp(theta).so2.z.shape == input_shape
        assert s.exp(theta).t.shape == t_input_shape
        assert s.log().shape == (*input_shape, 3)
        expected_hat_shape = (input_shape[0], 3, 3) if any(input_shape) else (3, 3)
        assert s.hat(theta).shape == expected_hat_shape
        assert s.inverse().so2.z.shape == input_shape
        assert s.inverse().t.shape == t_input_shape

    @pytest.mark.parametrize("batch_size", [1, 2, 5])
    def test_exception(self, device, dtype, batch_size):
        # A bfloat16 identity raises TypeCheckError, a TypeError, so the TypeError check below would pass for
        # the wrong reason; test_bfloat16_rotation_raises pins that error instead.
        if dtype == torch.bfloat16:
            pytest.skip("torch has no complex bfloat16 dtype, which So2 stores its rotation in")
        r = So2.random(batch_size)
        t1 = torch.randn((batch_size, 1), dtype=dtype, device=device)
        t2 = torch.randn((batch_size, 3), dtype=dtype, device=device)
        with pytest.raises(ValueError):
            Se2(r, t1)
        with pytest.raises(ValueError):
            Se2(r, t2)
        theta = torch.rand((batch_size, 2), dtype=dtype, device=device)
        with pytest.raises(ValueError):
            Se2.exp(theta)
        v = torch.rand((batch_size, 2), dtype=dtype, device=device)
        with pytest.raises(ValueError):
            Se2.hat(v)
        omega = torch.rand((4, 4), dtype=dtype, device=device)
        with pytest.raises(ValueError):
            Se2.vee(omega)
        with pytest.raises(TypeError):
            Se2.identity(1, device, dtype) * [1.0, 2.0, 1.0]
        theta = torch.rand((batch_size, 2), dtype=dtype, device=device)
        with pytest.raises(ValueError):
            Se2.hat(theta)
        with pytest.raises(BaseError):
            Se2.identity(batch_size=0)
        with pytest.raises(BaseError):
            Se2.random(batch_size=0)
        x = torch.rand(5, dtype=dtype, device=device)
        y = torch.rand(3, dtype=dtype, device=device)
        with pytest.raises(BaseError):
            Se2.trans(x, y)

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

    def test_gradient_at_the_identity_4404_4924(self, device, dtype):
        # #4404: both quotients that build the translation block are 0/0 at theta = 0, and the
        # torch.where that discards them still differentiates them, so 0 * nan = nan reached the
        # gradient at the identity. #4924: the value that where fell back to there was 0 where the
        # limit is 1, so the (vx, vy) gradient of exp(v).t was 0 and the theta gradient of log was
        # nan. Pin the values: with t = V(theta) (vx, vy), d sum(matrix()) / dv is
        # [1, 1, (vx - vy) / 2] at theta = 0 and d sum(log(exp(v))) / dv is [1, 1, 1].
        if dtype == torch.bfloat16:
            # Se2 holds its rotation as a complex So2, and torch.complex has no bfloat16 overload,
            # so most of this class already cannot run at that dtype -- unrelated to the guard.
            pytest.skip("torch.complex has no bfloat16 overload, so So2 cannot be built at all")
        v = torch.tensor([[1.0, 2.0, 0.0]], device=device, dtype=dtype, requires_grad=True)
        Se2.exp(v).matrix().sum().backward()
        self.assert_close(v.grad, torch.tensor([[1.0, 1.0, -0.5]], device=device, dtype=dtype))
        v.grad = None
        Se2.exp(v).log().sum().backward()
        self.assert_close(v.grad, torch.tensor([[1.0, 1.0, 1.0]], device=device, dtype=dtype))

    # 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):
        if dtype == torch.bfloat16:
            pytest.skip("torch has no complex bfloat16 dtype, which So2 stores its rotation in")
        s1 = Se2.random(batch_size, device, dtype)
        s2 = Se2(s1.r, s1.t)
        assert isinstance(s2, Se2)
        self.assert_close(s1.r.z, s2.r.z)
        self.assert_close(s1.t, s2.t)

    @pytest.mark.parametrize("batch_size", [1, 2, 5])
    def test_getitem(self, device, dtype, batch_size):
        z = torch.rand(batch_size, dtype=torch.cfloat, device=device).to(_complex_dtype(dtype))
        t = torch.rand((batch_size, 2), device=device, dtype=dtype)
        s = Se2(So2(z), t)
        for i in range(batch_size):
            s1 = s[i]
            self.assert_close(s1.r.z, z[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):
        if dtype == torch.bfloat16:
            pytest.skip("torch has no complex bfloat16 dtype, which So2 stores its rotation in")
        s1 = Se2.identity(batch_size, device, dtype)
        s2 = Se2.random(batch_size, device, dtype)
        s1_pose_s2 = s1 * s2
        s2_pose_s2 = s2 * s2.inverse()
        zeros_vec = torch.zeros(2, device=device, dtype=dtype)
        if batch_size is not None:
            zeros_vec = zeros_vec.repeat(batch_size, 1)
        so2_expected = So2.identity(batch_size, device, dtype)
        self.assert_close(s1_pose_s2.r.z, s2.r.z)
        self.assert_close(s1_pose_s2.t, s2.t)
        self.assert_close(s2_pose_s2.r.z.real, so2_expected.z.real)
        self.assert_close(s2_pose_s2.r.z.imag, so2_expected.z.imag)
        self.assert_close(s2_pose_s2.t, zeros_vec)

    @pytest.mark.parametrize("batch_size", [None, 1, 2, 5])
    def test_mul_vector(self, device, dtype, batch_size):
        if dtype == torch.bfloat16:
            pytest.skip("torch has no complex bfloat16 dtype, which So2 stores its rotation in")
        s1 = Se2.identity(batch_size, device, dtype)
        shape = () if batch_size is None else (batch_size,)
        s2 = Se2(So2.identity(batch_size, device, dtype), Vector2.random(shape, device, dtype))
        s1_pose_s2 = s1 * s2
        s2_pose_s2 = s2 * s2.inverse()
        zeros_vec = torch.zeros(2, device=device, dtype=dtype)
        if batch_size is not None:
            zeros_vec = zeros_vec.repeat(batch_size, 1)
        so2_expected = So2.identity(batch_size, device, dtype)
        self.assert_close(s1_pose_s2.r.z, s2.r.z)
        self.assert_close(s1_pose_s2.t, s2.t)
        self.assert_close(s2_pose_s2.r.z.real, so2_expected.z.real)
        self.assert_close(s2_pose_s2.r.z.imag, so2_expected.z.imag)
        self.assert_close(s2_pose_s2.t, zeros_vec)

    @pytest.mark.parametrize("batch_size", [None, 1, 2, 5])
    def test_exp(self, device, dtype, batch_size):
        if dtype == torch.bfloat16:
            pytest.skip("torch has no complex bfloat16 dtype, which So2 stores its rotation in")
        t = self._make_rand_data(device, dtype, (batch_size, 2))
        theta = torch.zeros(batch_size if batch_size is not None else (), device=device, dtype=dtype)
        s = Se2.exp(torch.cat((t, theta[..., None]), -1))
        self.assert_close(s.r.z, So2.exp(theta).z)
        # V(0) is the identity, so a pure translation keeps its translation (#4924)
        self.assert_close(s.t, t)

    @pytest.mark.parametrize("batch_size", [None, 1, 2, 5])
    def test_log(self, device, dtype, batch_size):
        if dtype == torch.bfloat16:
            pytest.skip("torch has no complex bfloat16 dtype, which So2 stores its rotation in")
        t = self._make_rand_data(device, dtype, (batch_size, 2))
        s = Se2(So2.identity(batch_size, device, dtype), t)
        # V(0)^-1 is the identity, so the log of a pure translation is (t, 0) (#4924)
        self.assert_close(s.log(), torch.cat((t, torch.zeros_like(t[..., :1])), -1))

    @pytest.mark.parametrize("batch_size", [None, 1, 2, 5])
    def test_exp_log(self, device, dtype, batch_size):
        if dtype == torch.bfloat16:
            pytest.skip("torch has no complex bfloat16 dtype, which So2 stores its rotation in")
        a = self._make_rand_data(device, dtype, (batch_size, 3))
        b = Se2.exp(a).log()
        self.assert_close(b, a, low_tolerance=True)

    def test_exp_log_keep_small_rotations_4924(self, device, dtype):
        # #4924: exp guarded a = sin(theta) / theta and b = (1 - cos(theta)) / theta with a fallback of 0
        # at theta = 0, where their limits are 1 and 0, and log guarded (theta / 2) cot(theta / 2) the same
        # way, so a pure translation went into and out of the tangent space as [0, 0]. Just above
        # theta = 0 the closed forms cancelled: exp(v).t was off by 1e-4 and log(exp(v)) by 2.0 at
        # theta = 1e-4 in float32 (2e-2 in float16, 1e-8 in float64).
        if dtype == torch.bfloat16:
            pytest.skip("torch.complex has no bfloat16 overload, so So2 cannot be built at all")
        theta = {torch.float16: 2e-2, torch.float32: 1e-4}.get(dtype, 1e-8)
        v = torch.tensor([[1.0, 2.0, 0.0], [1.0, 2.0, theta], [1.0, 2.0, -theta]], dtype=dtype)
        # V(theta) (vx, vy) for the rounded angle, in float64 on the CPU (MPS has no float64) and
        # without cancellation: 1 - cos(theta) = 2 sin(theta / 2)^2
        th = v[..., 2].double()
        a = torch.where(th == 0, torch.ones_like(th), torch.sin(th) / th)
        b = torch.where(th == 0, torch.zeros_like(th), 2 * torch.sin(th / 2) ** 2 / th)
        x, y = v[..., 0].double(), v[..., 1].double()
        t_ref = torch.stack((a * x - b * y, b * x + a * y), -1).to(device=device, dtype=dtype)
        v = v.to(device)
        eps = torch.finfo(dtype).eps
        self.assert_close(Se2.exp(v).t, t_ref, rtol=8 * eps, atol=8 * eps)
        g = Se2(So2.exp(v[..., 2]), t_ref)  # the element exp(v), rounded to dtype
        self.assert_close(g.log(), v, rtol=8 * eps, atol=8 * eps)

    def test_exp_keeps_large_angles_4924(self, device, dtype):
        # Past the small-angle branch exp takes sin(theta) / theta and 2 sin(theta / 2)^2 / theta directly.
        # 1 - theta^2 (theta - sin(theta)) / theta^3 cancels wherever sin(theta) / theta is small (37.7 is
        # within 1e-3 of 12 pi), 1 - cos(theta) cancels there too, and theta^3 overflows float16 above 40.3 rad,
        # which made that coefficient 0 and exp(v).t close to (vx, vy); the series that torch.where discards
        # overflows from 50 rad and made the gradient nan.
        if dtype == torch.bfloat16:
            pytest.skip("torch.complex has no bfloat16 overload, so So2 cannot be built at all")
        angles = (-300.0, -100.0, -41.0, 12.5, 37.7, 41.0, 100.0, 300.0)
        v = torch.tensor([[1.0, 2.0, th] for th in angles], dtype=dtype)
        # V(theta) (vx, vy) for the rounded angle, in float64 on the CPU (MPS has no float64)
        th = v[..., 2].double()
        a, b = torch.sin(th) / th, 2 * torch.sin(th / 2) ** 2 / th
        x, y = v[..., 0].double(), v[..., 1].double()
        t_ref = torch.stack((a * x - b * y, b * x + a * y), -1).to(device=device, dtype=dtype)
        v = v.to(device).requires_grad_(True)
        t = Se2.exp(v).t
        self.assert_close(t, t_ref, rtol=16 * torch.finfo(dtype).eps, atol=0.0)
        t.sum().backward()
        assert bool(torch.isfinite(v.grad).all()), v.grad

    def test_exp_gradient_below_the_switch_4924(self, device, dtype):
        # Below 0.5 rad the angle gradient comes from the series: autograd of sin(theta) / theta is
        # cos(theta) / theta - sin(theta) / theta^2, which loses about three digits at theta = 0.06.
        # Reference: the derivative series of a = sin(theta) / theta and b = (1 - cos(theta)) / theta in float64.
        if dtype == torch.bfloat16:
            pytest.skip("torch.complex has no bfloat16 overload, so So2 cannot be built at all")
        v = torch.tensor([[1.0, 2.0, 0.06], [1.0, 2.0, -0.3]], dtype=dtype)
        th = v[..., 2].double()
        da = sum((-1) ** k * 2 * k * th ** (2 * k - 1) / float(math.factorial(2 * k + 1)) for k in range(1, 12))
        db = sum((-1) ** (k + 1) * (2 * k - 1) * th ** (2 * k - 2) / float(math.factorial(2 * k)) for k in range(1, 12))
        # d sum(t) / d theta with t = (a x - b y, b x + a y)
        x, y = v[..., 0].double(), v[..., 1].double()
        ref = (da * (x + y) + db * (x - y)).to(device=device, dtype=dtype)
        v = v.to(device).requires_grad_(True)
        Se2.exp(v).t.sum().backward()
        eps = torch.finfo(dtype).eps
        self.assert_close(v.grad[..., 2], ref, rtol=8 * eps, atol=8 * eps)

    def test_exp_log_negative_angles_past_the_series_switch_4924(self, device, dtype):
        # The coefficients are even in theta, so exp and log evaluate them at |theta|. The So3 helper takes its
        # series below a positive switch point, so a signed theta would take the truncated series for every
        # negative angle; at theta = -3 that is off by about 1e-4 in log. Pin both signs past the switch.
        if dtype == torch.bfloat16:
            pytest.skip("torch.complex has no bfloat16 overload, so So2 cannot be built at all")
        v = torch.tensor([[1.0, 2.0, th] for th in (-3.0, -2.0, -1.0, 1.0, 2.0, 3.0)], dtype=dtype)
        # V(theta) (vx, vy) for the rounded angle, in float64 on the CPU (MPS has no float64)
        th = v[..., 2].double()
        a, b = torch.sin(th) / th, 2 * torch.sin(th / 2) ** 2 / th
        x, y = v[..., 0].double(), v[..., 1].double()
        t_ref = torch.stack((a * x - b * y, b * x + a * y), -1).to(device=device, dtype=dtype)
        v = v.to(device)
        eps = torch.finfo(dtype).eps
        self.assert_close(Se2.exp(v).t, t_ref, rtol=8 * eps, atol=8 * eps)
        g = Se2(So2.exp(v[..., 2]), t_ref)  # the element exp(v), rounded to dtype
        self.assert_close(g.log(), v, rtol=8 * eps, atol=8 * eps)

    @pytest.mark.parametrize("batch_size", [None, 1, 2, 5])
    def test_convention_se2_hat_and_vee_are_the_generator_4929(self, device, dtype, batch_size):
        # https://github.com/kornia/kornia/issues/4929: hat used to put the translation in the bottom row and the
        # angle in a symmetric block, and vee read that layout. Pin both separately, since vee(hat(v)) round-trips
        # either way.
        v = self._make_rand_data(device, dtype, (batch_size, 2))
        theta = self._make_rand_data(device, dtype, (batch_size, 1))
        s_hat = Se2.hat(torch.cat((v, theta), -1))
        self.assert_close(s_hat[..., :2, 2], v)
        self.assert_close(s_hat[..., :2, :2].squeeze(), So2.hat(theta.squeeze(-1)).squeeze())
        self.assert_close(s_hat[..., 2, :], torch.zeros_like(s_hat[..., 2, :]))
        omega = self._make_rand_data(device, dtype, input_shape=(batch_size, 3, 3))
        recovered = Se2.vee(omega)
        self.assert_close(recovered[..., :2], omega[..., :2, 2])
        self.assert_close(recovered[..., -1], omega[..., 1, 0])
        self.assert_close(Se2.vee(s_hat), torch.cat((v, theta), -1))

    @pytest.mark.parametrize("batch_size", [None, 1, 2, 5])
    def test_matrix_exp_of_hat_is_exp(self, device, dtype, batch_size):
        if dtype == torch.bfloat16:
            pytest.skip("torch has no complex bfloat16 dtype, which So2 stores its rotation in")
        v = self._make_rand_data(device, dtype, (batch_size, 3))
        # The reference runs in float64 on the CPU: MPS has no float64 and CPU matrix_exp has no
        # half-precision kernel.
        expm = torch.linalg.matrix_exp(Se2.hat(v).cpu().double()).to(device=device, dtype=dtype)
        self.assert_close(expm, Se2.exp(v).matrix())

    @pytest.mark.parametrize("batch_size", [None, 1, 2, 5])
    def test_identity(self, device, dtype, batch_size):
        s = Se2.random(batch_size)
        s_pose_s = s * Se2.identity(batch_size)
        self.assert_close(s_pose_s.so2.z.real, s.so2.z.real)
        self.assert_close(s_pose_s.so2.z.imag, s.so2.z.imag)
        self.assert_close(s.t, s_pose_s.t)

    @pytest.mark.parametrize("batch_size", [None, 1, 2, 5])
    def test_matrix(self, device, dtype, batch_size):
        if dtype == torch.bfloat16:
            pytest.skip("torch has no complex bfloat16 dtype, which So2 stores its rotation in")
        theta = self._make_rand_data(device, dtype, (batch_size,))
        t = self._make_rand_data(device, dtype, (batch_size, 2))
        s = So2.exp(theta)
        p1 = s * t
        p2 = s.matrix() @ t[..., None]
        self.assert_close(p1, p2.squeeze(-1))

    @pytest.mark.parametrize("batch_size", [None, 1, 2, 5])
    def test_from_matrix(self, device, dtype, batch_size):
        if dtype == torch.bfloat16:
            pytest.skip("torch has no complex bfloat16 dtype, which So2 stores its rotation in")
        theta = self._make_rand_data(device, dtype, (batch_size,))
        t = self._make_rand_data(device, dtype, (batch_size, 2))
        s = So2.exp(theta)
        p1 = s * t
        RT = torch.eye(3, device=device, dtype=dtype)
        if batch_size is not None:
            RT = RT.repeat(batch_size, 1, 1)
        RT[..., :2, :2] = s.matrix()
        p2 = Se2.from_matrix(RT) * t
        self.assert_close(p1, p2)

    @pytest.mark.parametrize("batch_size", [None, 1, 2, 5])
    def test_inverse(self, device, batch_size, dtype):
        if dtype == torch.bfloat16:
            pytest.skip("torch has no complex bfloat16 dtype, which So2 stores its rotation in")
        s = Se2.random(batch_size, device, dtype)
        s_in_in = s.inverse().inverse()
        self.assert_close(s_in_in.so2.z.real, s.so2.z.real)
        self.assert_close(s_in_in.so2.z.imag, s.so2.z.imag)
        self.assert_close(s_in_in.t, s.t)

    @pytest.mark.parametrize("batch_size", [None, 1, 2, 5])
    def test_random(self, device, dtype, batch_size):
        if dtype == torch.bfloat16:
            pytest.skip("torch has no complex bfloat16 dtype, which So2 stores its rotation in")
        s = So2.random(batch_size=batch_size, device=device, dtype=dtype)
        t = self._make_rand_data(device, dtype, (batch_size, 2))
        se2 = Se2(s, t)
        se2_in_se2 = se2.inverse() * se2
        i = Se2.identity(batch_size=batch_size, device=device, dtype=dtype)
        self.assert_close(se2_in_se2.so2.z.real, i.so2.z.real)
        self.assert_close(se2_in_se2.so2.z.imag, i.so2.z.imag)
        self.assert_close(se2_in_se2.t, i.t)

    def test_random_rotation_is_a_uniform_unit_rotation_4930(self, device, dtype):
        # #4930: Se2.random takes its rotation from So2.random, which was neither unit nor uniform in angle.
        if dtype not in (torch.float32, torch.float64):
            pytest.skip("torch.complex has no bfloat16 overload and ComplexHalf support is experimental")
        torch.manual_seed(0)
        z = Se2.random(1000, device=device, dtype=dtype).so2.z
        self.assert_close(z.abs(), torch.ones(1000, device=device, dtype=dtype))
        theta = z.imag.atan2(z.real)
        assert theta.min() < -math.pi / 2, (theta.min(), theta.max())
        assert theta.max() > math.pi / 2, (theta.min(), theta.max())

    @pytest.mark.parametrize("batch_size", [None, 1, 2, 5])
    def test_trans(self, device, dtype, batch_size):
        if dtype == torch.bfloat16:
            pytest.skip("torch has no complex bfloat16 dtype, which So2 stores its rotation in")
        trans = self._make_rand_data(device, dtype, (batch_size, 2))
        x, y = trans[..., 0], trans[..., 1]
        se2 = Se2.trans(x, y)
        self.assert_close(se2.t, trans)
        self.assert_close(se2.so2.matrix(), So2.identity(batch_size, device, dtype).matrix())

    @pytest.mark.parametrize("batch_size", [None, 1, 2, 5])
    def test_trans_x(self, device, dtype, batch_size):
        if dtype == torch.bfloat16:
            pytest.skip("torch has no complex bfloat16 dtype, which So2 stores its rotation in")
        x = self._make_rand_data(device, dtype, (batch_size, 1)).squeeze(-1)
        zs = torch.zeros_like(x)
        se2 = Se2.trans_x(x)
        self.assert_close(se2.t, torch.stack((x, zs), -1))
        self.assert_close(se2.so2.matrix(), So2.identity(batch_size, device, dtype).matrix())

    @pytest.mark.parametrize("batch_size", [None, 1, 2, 5])
    def test_trans_y(self, device, dtype, batch_size):
        if dtype == torch.bfloat16:
            pytest.skip("torch has no complex bfloat16 dtype, which So2 stores its rotation in")
        y = self._make_rand_data(device, dtype, (batch_size, 1)).squeeze(-1)
        zs = torch.zeros_like(y)
        se2 = Se2.trans_y(y)
        self.assert_close(se2.t, torch.stack((zs, y), -1))
        self.assert_close(se2.so2.matrix(), So2.identity(batch_size, device, dtype).matrix())

    @pytest.mark.parametrize("batch_size", [None, 1, 2, 5])
    def test_adjoint(self, device, dtype, batch_size):
        x = Se2.random(batch_size)
        y = Se2.random(batch_size)
        self.assert_close(x.inverse().adjoint(), x.adjoint().inverse())
        self.assert_close((x * y).adjoint(), x.adjoint() @ y.adjoint())

    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).
        if dtype == torch.bfloat16:
            pytest.skip("torch has no complex bfloat16 dtype, which So2 stores its rotation in")
        t = torch.tensor([[1.0, 2.0]], device=device, dtype=dtype, requires_grad=True)
        s = Se2(So2.identity(1, device, dtype), t)
        (s * torch.tensor([[1.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()

    def test_integer_translation_raises(self, device):
        # An integer translation cannot be optimizable state: a kornia error names its dtype instead of torch's
        # autograd error (#5201). Cast it to a floating-point dtype first.
        with pytest.raises(TypeCheckError, match=r"Se2 stores 'translation'.*torch.int64"):
            Se2(So2.identity(1, device), torch.tensor([[1, 2]], device=device))

    @pytest.mark.parametrize(
        "pair",
        [
            (torch.float64, torch.float32),
            (torch.float32, torch.float64),
            (torch.float32, torch.float16),
            (torch.float16, torch.float32),
        ],
    )
    def test_mixed_dtype_translation_raises_5913(self, device, pair):
        # The mix used to construct, then log() raised torch's "expected scalar type Double but found Float".
        if device.type == "mps" and (torch.float64 in pair or pair[0] == torch.float16):
            pytest.skip("MPS has no float64 or complex32")
        r_dtype, t_dtype = pair
        rotation = So2.identity(1, device, r_dtype)
        with pytest.raises(
            TypeCheckError, match=r"Se2 translation must have the dtype of its rotation.*" + str(t_dtype)
        ):
            Se2(rotation, torch.zeros(1, 2, device=device, dtype=t_dtype))
        with pytest.raises(TypeCheckError, match=r"Se2 translation"):
            Se2(rotation, Vector2(torch.zeros(1, 2, device=device, dtype=t_dtype)))
        with pytest.raises(TypeCheckError, match=r"Se2 translation"):
            Se2(So2.identity(None, device, r_dtype), torch.zeros(2, device=device, dtype=t_dtype))

    def test_same_dtype_translation_is_accepted_5913(self, device, dtype):
        if dtype == torch.bfloat16:
            pytest.skip("torch.complex has no bfloat16 overload, so So2 cannot be built at all")
        s = Se2(So2.identity(2, device, dtype), torch.zeros(2, 2, device=device, dtype=dtype))
        assert s.t.dtype == dtype
        assert s.r.z.real.dtype == dtype

    @pytest.mark.parametrize("real_dtype", [torch.float16, torch.float32, torch.float64])
    def test_bfloat16_module_state_is_closed_5913(self, device, real_dtype):
        # ``.bfloat16()`` keeps the complex rotation (complex32/64/128) and casts the translation (documented in
        # the class Convention). Every method must keep working on that state: log/matrix/adjoint read the
        # translation at the rotation's precision, and inverse/pose * pose return a translation of its real dtype.
        if device.type == "mps" and real_dtype != torch.float32:
            pytest.skip("MPS supports complex64 only")
        v = torch.tensor([[0.5, 0.2, 0.3], [0.1, 0.4, -0.2]], device=device, dtype=real_dtype)
        cdtype = {torch.float16: torch.chalf, torch.float32: torch.cfloat, torch.float64: torch.cdouble}[real_dtype]
        s = Se2.exp(v).bfloat16()
        assert s.t.dtype == torch.bfloat16
        assert s.r.z.dtype == cdtype
        tol = {"atol": 0.05, "rtol": 0.05}
        log = s.log()
        assert log.dtype == real_dtype
        self.assert_close(log, v, **tol)
        assert s[0].t.dtype == torch.bfloat16
        for pose in (s[0], s.inverse(), s * s, s.inverse().inverse(), s * s.inverse()):
            assert isinstance(pose, Se2)
            assert pose.r.z.dtype == cdtype
        # inverse() and pose * pose build a translation of the rotation's real dtype
        for pose in (s.inverse(), s * s, s * s.inverse()):
            assert pose.t.dtype == real_dtype
        assert s.inverse().log().dtype == real_dtype
        self.assert_close((s * s.inverse()).log(), torch.zeros_like(v), **tol)
        matrix = s.matrix()
        assert matrix.dtype == real_dtype
        self.assert_close((s * s).matrix(), matrix @ matrix, **tol)
        assert s.adjoint().dtype == real_dtype
        points = torch.ones(2, 2, device=device, dtype=real_dtype)
        out = s * points
        assert out.is_floating_point()
        expected = (matrix[:, :2, :2] @ points[..., None])[..., 0] + matrix[:, :2, 2]
        self.assert_close(out.to(real_dtype), expected, **tol)
        Se2(So2.identity(1, device), torch.zeros(1, 2, device=device, dtype=torch.bfloat16))

    @pytest.mark.skipif(not dynamo_is_available(), reason=DYNAMO_UNAVAILABLE_REASON)
    def test_dynamo_constructor_checks_5913(self, device, torch_optimizer):
        def build(real, imag, t):
            return Se2(So2(torch.complex(real, imag)), t).matrix()

        args = (torch.rand(2, device=device), torch.rand(2, device=device), torch.rand(2, 2, 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):
        # the translation is a real vector; a complex one used to construct (its imaginary part silently dropped)
        if device.type == "mps" and cdtype != torch.cfloat:
            pytest.skip("MPS supports complex64 only")
        with pytest.raises(TypeCheckError, match=r"Se2 translation must be a real floating-point tensor.*complex"):
            Se2(So2.identity(1, device), torch.zeros(1, 2, device=device, dtype=cdtype))

    @pytest.mark.parametrize("int_dtype", [torch.int64, torch.bool])
    def test_integer_parameter_translation_raises_5913(self, device, int_dtype):
        # register_module_state keeps an existing nn.Parameter as given, so an integer one used to get through
        translation = torch.nn.Parameter(torch.zeros(1, 2, device=device, dtype=int_dtype), requires_grad=False)
        with pytest.raises(TypeCheckError, match=r"Se2 stores 'translation'.*" + str(int_dtype)):
            Se2(So2.identity(1, device), translation)

    def test_translation_on_another_device_raises_5913(self, device):
        # Rotation and translation on different devices fail in every method (matrix, log, inverse, __mul__);
        # the meta device stands in for a second accelerator.
        with pytest.raises(DeviceError, match=r"Se2 translation must be on the device of its rotation"):
            Se2(So2.identity(1, device), torch.zeros(1, 2, device="meta"))

    def test_internal_constructions_still_build_5913(self, device, dtype):
        if dtype == torch.bfloat16:
            pytest.skip("torch.complex has no bfloat16 overload, so So2 cannot be built at all")
        a = Se2.exp(torch.tensor([[0.5, 0.2, 0.3], [0.1, 0.4, -0.2]], device=device, dtype=dtype))
        built = [
            Se2.identity(None, device, dtype),
            Se2.identity(2, device, dtype),
            Se2.random(None, device, dtype),
            Se2.random(2, device, dtype),
            Se2.from_matrix(a.matrix().detach()),
            Se2.trans(torch.ones(2, device=device, dtype=dtype), torch.zeros(2, device=device, dtype=dtype)),
            Se2.trans_x(torch.ones(2, device=device, dtype=dtype)),
            Se2.trans_y(torch.ones(2, device=device, dtype=dtype)),
            a[0],
            a.inverse(),
            a * a,
            NamedPose.from_rt(So2.identity(1, device, dtype), torch.zeros(1, 2, device=device, dtype=dtype)).pose,
        ]
        assert all(isinstance(s, Se2) for s in built)
        assert all(s.t.dtype == dtype and s.r.z.real.dtype == dtype for s in built)

    def test_bfloat16_rotation_raises(self, device):
        # Every Se2 builder goes through an So2 builder, which raises a kornia error naming bfloat16 because PyTorch
        # has no complex bfloat16 dtype; torch.complex raised a RuntimeError there before. ``.bfloat16()`` on a
        # built pose keeps working (test_bfloat16_module_state_is_closed_5913).
        bf16 = torch.bfloat16
        ones = torch.ones(2, device=device, dtype=bf16)
        builders = {
            "exp": lambda: Se2.exp(torch.ones(2, 3, device=device, dtype=bf16)),
            "identity": lambda: Se2.identity(2, device, bf16),
            "random": lambda: Se2.random(2, device, bf16),
            "from_matrix": lambda: Se2.from_matrix(torch.eye(3, device=device, dtype=bf16)),
            "trans": lambda: Se2.trans(ones, ones),
            "trans_x": lambda: Se2.trans_x(ones),
            "trans_y": lambda: Se2.trans_y(ones),
        }
        message = r"So2 stores its rotation as a complex tensor.*no complex bfloat16 dtype"
        for name, build in builders.items():
            with pytest.raises(TypeCheckError, match=message) as err:
                build()
            assert err.value.actual_type == bf16, name

    def test_derived_state_moves_and_serializes(self, device, dtype):
        if dtype == torch.bfloat16:
            pytest.skip("torch has no complex bfloat16 dtype, which So2 stores its rotation in")
        # A group built from a tensor with autograd history keeps that history; its state must
        # still be registered so ``state_dict`` and ``.to()`` / ``.double()`` reach it.
        v = torch.rand(2, 3, device=device, dtype=dtype, requires_grad=True)
        s = Se2.exp(v)
        assert s.t.grad_fn is not None
        assert s.so2.z.grad_fn is not None
        assert set(s.state_dict()) == {"_translation", "_rotation._z"}
        restored = Se2(So2.identity(2, device, dtype), torch.zeros(2, 2, device=device, dtype=dtype))
        restored.load_state_dict(s.state_dict())
        self.assert_close(restored.matrix(), s.matrix().detach())
        # ``.half()`` / ``.float()`` convert the floating buffers in place and keep the graph
        # (float64 is unavailable on MPS, so convert towards float16 from float32)
        converted = s.half() if dtype == torch.float32 else s.float()
        assert converted.t.dtype == (torch.float16 if dtype == torch.float32 else torch.float32)
        assert converted.so2.z.real.dtype == converted.t.dtype
        assert converted.t.grad_fn is not None
        converted.t.sum().backward()
        assert v.grad is not None

    def test_se2_identity_and_random_translation_is_module_state_4931(self, device, dtype):
        if dtype == torch.bfloat16:
            pytest.skip("torch has no complex bfloat16 dtype, which So2 stores its rotation in")
        # https://github.com/kornia/kornia/issues/4931: identity and random register their translation like the other
        # constructors, so it is in state_dict() and ``.half()`` / ``.float()`` convert it (float64 is unavailable on
        # MPS, so convert towards float16 from float32). The complex So2 components follow the same precision.
        for pose in (Se2.identity(1, device, dtype), Se2.random(1, device, dtype)):
            assert "_translation" in pose.state_dict()
            converted = pose.half() if dtype == torch.float32 else pose.float()
            assert converted.t.dtype == (torch.float16 if dtype == torch.float32 else torch.float32)
            assert converted.r.z.is_complex()
            assert converted.r.z.real.dtype == converted.t.dtype

    @pytest.mark.parametrize("method", ["to", "bfloat16"])
    def test_parent_bfloat16_conversion_preserves_pose_4923(self, device, method):
        # Reviewer reproduction: casting a network containing a pose must keep the rotation usable.
        class M(torch.nn.Module):
            def __init__(self):
                super().__init__()
                self.linear = torch.nn.Linear(2, 2)
                self.pose = Se2.exp(torch.tensor([[1.0, 2.0, 0.3]], dtype=torch.float32))

        model = M()
        before_rotation = model.pose.so2.z.detach().clone()
        before_matrix = model.pose.matrix().detach().clone()
        if method == "to":
            model.to(device=device, dtype=torch.bfloat16)
        else:
            model.to(device=device).bfloat16()

        assert model.linear.weight.dtype == torch.bfloat16
        assert model.linear.weight.device == device
        assert model.pose.t.dtype == torch.bfloat16
        assert model.pose.t.device == device
        assert model.pose.so2.z.dtype == before_rotation.dtype
        assert model.pose.so2.z.device == device
        self.assert_close(model.pose.so2.z, before_rotation.to(device))
        expected_matrix = before_matrix.to(device)
        expected_matrix[:, :2, 2] = expected_matrix[:, :2, 2].to(torch.bfloat16).float()
        matrix = model.pose.matrix()
        self.assert_close(matrix, expected_matrix)
        point = torch.tensor([[1.0, 2.0]], device=device, dtype=torch.bfloat16)
        expected_point = (expected_matrix[:, :2, :2] @ point.float()[..., None]).squeeze(-1)
        expected_point = expected_point + expected_matrix[:, :2, 2]
        self.assert_close(model.pose * point, expected_point)
        self.assert_close(model.pose.inverse().matrix() @ matrix, torch.eye(3, device=device)[None])
        self.assert_close((model.pose * model.pose).matrix(), matrix @ matrix)

    @pytest.mark.parametrize("method", ["to", "convenience"])
    def test_parent_dtype_conversion_preserves_rotation_4923(self, device, dtype, method):
        if dtype == torch.bfloat16:
            pytest.skip("PyTorch has no complex bfloat16 dtype")
        source_dtype = torch.float64 if dtype == torch.float32 and device.type != "mps" else torch.float32
        angle = torch.tensor([0.3, -1.2], dtype=source_dtype, requires_grad=True)
        translation = torch.tensor([[3.0, 4.0], [-2.0, 1.0]], dtype=source_dtype, requires_grad=True)
        reference_angle = angle.detach().clone().requires_grad_()
        reference_translation = translation.detach().clone().requires_grad_()
        pose = Se2(So2.exp(angle), translation)
        parent = torch.nn.ModuleDict({"pose": pose})
        assert pose.so2.z.device.type == pose.t.device.type == "cpu"
        if method == "to":
            parent.to(device=device, dtype=dtype)
        else:
            before_dtype = pose.so2.z.dtype
            parent.to(device=device)
            assert pose.so2.z.dtype == before_dtype
            assert pose.t.dtype == source_dtype
            name = {torch.float16: "half", torch.float32: "float", torch.float64: "double"}[dtype]
            getattr(parent, name)()

        assert pose.so2.z.device == pose.t.device == device
        assert pose.so2.z.is_complex()
        assert pose.so2.z.real.dtype == pose.t.dtype == dtype
        assert set(parent.state_dict()) == {"pose._rotation._z", "pose._translation"}
        assert set(dict(parent.named_buffers())) == {"pose._rotation._z", "pose._translation"}
        assert not dict(parent.named_parameters())
        c = reference_angle.cos().to(device=device, dtype=dtype)
        s = reference_angle.sin().to(device=device, dtype=dtype)
        t = reference_translation.to(device=device, dtype=dtype)
        expected_matrix = torch.zeros(2, 3, 3, device=device, dtype=dtype)
        expected_matrix[:, 0, 0], expected_matrix[:, 0, 1] = c, -s
        expected_matrix[:, 1, 0], expected_matrix[:, 1, 1] = s, c
        expected_matrix[:, :2, 2], expected_matrix[:, 2, 2] = t, 1
        self.assert_close(pose.matrix(), expected_matrix)
        point = torch.tensor([[1.0, 2.0], [-3.0, 1.0]], device=device, dtype=dtype)
        x, y = point.unbind(-1)
        expected = torch.stack((c * x - s * y, s * x + c * y), -1) + t
        actual = pose * point
        self.assert_close(actual, expected)
        actual_grads = torch.autograd.grad(actual.sum(), (angle, translation))
        expected_grads = torch.autograd.grad(expected.sum(), (reference_angle, reference_translation))
        self.assert_close(actual_grads[0], expected_grads[0])
        self.assert_close(actual_grads[1], expected_grads[1])

    def test_dtype_conversion_keeps_checkpoint_layout_4923(self, device, dtype):
        if dtype == torch.bfloat16:
            pytest.skip("PyTorch has no complex bfloat16 dtype")
        source_dtype = torch.float64 if dtype == torch.float32 and device.type != "mps" else torch.float32
        legacy_state = {
            "_rotation._z": torch.complex(
                torch.zeros(1, device=device, dtype=source_dtype), torch.ones(1, device=device, dtype=source_dtype)
            ),
            "_translation": torch.tensor([[3.0, 4.0]], device=device, dtype=source_dtype),
        }
        target = Se2.identity(1, device, source_dtype).to(dtype=dtype)
        result = target.load_state_dict(legacy_state)
        assert not result.missing_keys
        assert not result.unexpected_keys
        assert set(target.state_dict()) == set(legacy_state)
        assert target.so2.z.is_complex()
        assert target.so2.z.real.dtype == target.t.dtype == dtype
        expected_matrix = torch.tensor(
            [[[0.0, -1.0, 3.0], [1.0, 0.0, 4.0], [0.0, 0.0, 1.0]]], device=device, dtype=dtype
        )
        self.assert_close(target.matrix(), expected_matrix)
        restored = Se2.identity(1, device, dtype)
        restored.load_state_dict(target.state_dict())
        self.assert_close(restored.matrix(), expected_matrix)
        point = torch.tensor([[1.0, 2.0]], device=device, dtype=dtype)
        self.assert_close(restored * point, torch.tensor([[1.0, 5.0]], device=device, dtype=dtype))

    def test_convention_se2_tangent_is_vx_vy_theta_with_V(self, device, dtype):
        if dtype == torch.bfloat16:
            pytest.skip("torch has no complex bfloat16 dtype, which So2 stores its rotation in")
        # The tangent is (vx, vy, theta), angle last, and exp translates by V(theta) (vx, vy), V = [[a, -b], [b, a]]
        # with a = sin(theta) / theta and b = (1 - cos(theta)) / theta. Reference, float64:
        # a, b = math.sin(0.3) / 0.3, (1 - math.cos(0.3)) / 0.3; (a - 2 * b, b + 2 * a) and (2 * a - b, 2 * b + a).
        v = torch.tensor([1.0, 2.0, 0.3], device=device, dtype=dtype)
        g = Se2.exp(v)
        self.assert_close(g.so2.log(), v[2])
        t_expected = torch.tensor([0.6873106163751718, 2.1190130806569103], device=device, dtype=dtype)
        assert (t_expected - v[:2]).abs().max() > 0.1  # V is not the identity at this angle
        self.assert_close(g.t, t_expected)
        # V couples the two slots: swapping vx and vy does not swap the translation
        swapped = Se2.exp(v[[1, 0, 2]]).t
        self.assert_close(swapped, torch.tensor([1.8212563414942837, 1.2828240947004255], device=device, dtype=dtype))

    def test_convention_se2_adjoint_conjugates_the_tangent(self, device, dtype):
        if dtype == torch.bfloat16:
            pytest.skip("torch has no complex bfloat16 dtype, which So2 stores its rotation in")
        # g exp(v) = exp(Ad(g) v) g, with Ad(g) = [[R, (ty, -tx)], [0, 0, 1]] for the (vx, vy, theta) tangent.
        g = Se2.exp(torch.tensor([0.5, -1.0, 0.7], device=device, dtype=dtype))
        v = torch.tensor([0.3, 0.2, -0.4], 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 * Se2.exp(v)).matrix(), (Se2.exp(ad_v) * g).matrix())

    def test_convention_se2_composition_is_left_matrix_product(self, device, dtype):
        if dtype == torch.bfloat16:
            pytest.skip("torch has no complex bfloat16 dtype, which So2 stores its rotation in")
        # a * b is the matrix product a b: b acts first on a point.
        a = Se2.exp(torch.tensor([1.0, -0.5, 0.9], device=device, dtype=dtype))
        b = Se2.exp(torch.tensor([-0.3, 2.0, -0.4], 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], device=device, dtype=dtype)
        self.assert_close((a * b) * p, a * (b * p))

    def test_convention_se2_point_action_broadcasts_the_pose(self, device, dtype):
        if dtype == torch.bfloat16:
            pytest.skip("torch has no complex bfloat16 dtype, which So2 stores its rotation in")
        # Unlike Se3, an unbatched pose transforms (N, 2) points and a batched pose a single (2,) point.
        v = torch.tensor([[1.0, -0.5, 0.9], [-0.3, 2.0, -0.4]], device=device, dtype=dtype)
        p = torch.tensor([[0.7, -1.3], [2.0, 0.5], [-1.0, 1.0]], device=device, dtype=dtype)
        g0 = Se2.exp(v[0])
        self.assert_close(g0 * p, p @ g0.so2.matrix().mT + g0.t)
        g = Se2.exp(v)
        self.assert_close(g * p[0], torch.stack([Se2.exp(v[i]) * p[0] for i in range(2)]))

    def test_convention_se2_log_is_principal(self, device, dtype):
        if dtype == torch.bfloat16:
            pytest.skip("torch has no complex bfloat16 dtype, which So2 stores its rotation in")
        # The angle of log is in [-pi, pi], and the translation part is taken with that angle, so exp(log(g)) = g.
        # Reference, float64: scipy.linalg.logm(scipy.linalg.expm([[0, -3.5, 1], [3.5, 0, 2], [0, 0, 0]])), whose
        # entries (0, 2), (1, 2), (1, 0) are vx, vy, theta.
        g = Se2.exp(torch.tensor([1.0, 2.0, 3.5], device=device, dtype=dtype))
        expected = torch.tensor(
            [-0.7951958020513128, -1.5903916041026287, -2.7831853071795862], device=device, dtype=dtype
        )
        self.assert_close(g.log(), expected)
        self.assert_close(Se2.exp(g.log()).matrix(), g.matrix())

    def test_convention_se2_from_matrix_ignores_the_bottom_row(self, device, dtype):
        if dtype == torch.bfloat16:
            pytest.skip("torch has no complex bfloat16 dtype, which So2 stores its rotation in")
        # from_matrix reads the rotation block, validated by So2.from_matrix, and the last column; it does not
        # check the bottom row.
        v = torch.tensor([1.0, 2.0, 0.3], device=device, dtype=dtype)
        clean = Se2.exp(v).matrix().detach()
        junk = clean.clone()
        junk[2] = torch.tensor([0.5, -4.0, 7.0], device=device, dtype=dtype)
        self.assert_close(Se2.from_matrix(junk).matrix(), clean)
        # A scaled rotation block is accepted and its scale kept in z, which log drops.
        scaled = clean.clone()
        scaled[:2, :2] *= 2.0
        g = Se2.from_matrix(scaled)
        self.assert_close(g.matrix(), scaled)
        self.assert_close(g.log()[2], v[2])
        reflection = clean.clone()
        reflection[:2, :2] = torch.tensor([[1.0, 0.0], [0.0, -1.0]], device=device, dtype=dtype)
        with pytest.raises(ValueError, match="Invalid SO2 rotation matrix"):
            Se2.from_matrix(reflection)

    @pytest.mark.skipif(not dynamo_is_available(), reason=DYNAMO_UNAVAILABLE_REASON)
    def test_convention_se2_from_matrix_omits_rotation_value_validation_during_export(self, device, dtype):
        if dtype == torch.bfloat16:
            pytest.skip("torch has no complex bfloat16 dtype, which So2 stores its rotation in")
        # Graph export cannot read rotation values, so from_matrix keeps m00 + i m10 and omits eager validation.
        reflection = torch.tensor([[1.0, 0.0], [0.0, -1.0]], device=device, dtype=dtype)
        matrix = torch.eye(3, device=device, dtype=dtype)
        matrix[:2, :2] = reflection
        with pytest.raises(ValueError):
            Se2.from_matrix(matrix)

        class FromMatrix(torch.nn.Module):
            def forward(self, input):
                return Se2.from_matrix(input).matrix()

        expected = torch.eye(3, device=device, dtype=dtype)
        exported = torch.export.export(FromMatrix(), (matrix,)).module()
        self.assert_close(exported(matrix), expected)

    @pytest.mark.skipif(not dynamo_is_available(), reason=DYNAMO_UNAVAILABLE_REASON)
    def test_convention_se2_from_matrix_omits_rotation_value_validation_under_any_capture_5037(self, device, dtype):
        if dtype == torch.bfloat16:
            pytest.skip("torch has no complex bfloat16 dtype, which So2 stores its rotation in")
        # As under export, a fullgraph trace cannot read the rotation values, so any capture omits the check (#5037)
        # and keeps m00 + i m10; a valid pose traces in one graph and matches eager.
        from torch._dynamo.testing import CompileCounter

        def from_matrix(matrix: torch.Tensor) -> torch.Tensor:
            return Se2.from_matrix(matrix).matrix()

        pose = Se2.exp(torch.tensor([[1.0, 2.0, 0.3]], device=device, dtype=dtype)).matrix().detach()
        reflection = torch.eye(3, device=device, dtype=dtype)
        reflection[1, 1] = -1.0
        counter = CompileCounter()
        torch._dynamo.reset()
        traced = torch.compile(from_matrix, backend=counter, fullgraph=True)
        self.assert_close(traced(pose), from_matrix(pose), atol=0.0, rtol=0.0)
        assert counter.frame_count == 1
        with pytest.raises(ValueError, match="Invalid SO2 rotation matrix"):
            from_matrix(reflection[None])
        self.assert_close(traced(reflection[None]), torch.eye(3, device=device, dtype=dtype)[None], atol=0.0, rtol=0.0)

    def test_se2_translation_is_a_tensor_for_every_constructor_4931(self, device, dtype):
        if dtype == torch.bfloat16:
            pytest.skip("torch has no complex bfloat16 dtype, which So2 stores its rotation in")
        # https://github.com/kornia/kornia/issues/4931: identity and random store their translation as a registered
        # tensor like the other constructors, so g * p is a tensor for a tensor p whichever constructor built g, and
        # a Vector2 only for a Vector2 p.
        p = torch.tensor([[1.0, 2.0]], device=device, dtype=dtype)
        from_exp = Se2.exp(torch.zeros(1, 3, device=device, dtype=dtype))
        identity = Se2.identity(1, device, dtype)
        self.assert_close(identity.matrix(), from_exp.matrix())  # the same group element
        poses = [
            identity,
            Se2.random(1, device, dtype),
            Se2(So2.identity(1, device, dtype), Vector2(p)),
            from_exp * identity,
            identity.inverse(),
        ]
        for pose in poses:
            assert isinstance(pose.t, torch.Tensor)
            assert pose.t.shape == (1, 2)
            assert "_translation" in pose.state_dict()
        self.assert_close(identity.t[..., 0], torch.zeros(1, device=device, dtype=dtype))
        for g in (from_exp, identity, from_exp * identity):
            assert type(g * p) is torch.Tensor
            self.assert_close(g * p, p)
        assert isinstance(identity * Vector2(p), Vector2)
        self.assert_close((identity * Vector2(p)).data, p)

    def test_random_translation_is_uniform_in_the_unit_interval(self, device, dtype):
        if dtype not in (torch.float32, torch.float64):
            pytest.skip("torch.complex has no bfloat16 overload and ComplexHalf support is experimental")
        # random draws its translation with torch.rand, which the Vector2 it used to build drew as well (#4931).
        torch.manual_seed(0)
        t = Se2.random(1000, device=device, dtype=dtype).t
        assert t.shape == (1000, 2)
        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()

    # #6426: a pose maps (2,) or (N, 2) 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, 2)), (2, (7, 2)), (2, (2, 7, 2)), (1, (1, 7, 2))]
    )
    def test_point_layout_outside_the_contract_raises(self, batch_size, points_shape, device, dtype):
        if dtype == torch.bfloat16:
            pytest.skip("torch has no complex bfloat16 dtype, which So2 stores its rotation in")
        pose = Se2.identity(batch_size, device, dtype)
        with pytest.raises(ValueError, match=r"Expected points of shape \(2,\) or \(N, 2\)"):
            pose * torch.zeros(points_shape, device=device, dtype=dtype)

    @pytest.mark.parametrize(
        ("batch_size", "points_shape", "out_shape"),
        [
            (None, (2,), (2,)),
            (None, (7, 2), (7, 2)),
            (1, (7, 2), (7, 2)),
            (2, (2, 2), (2, 2)),
            (2, (1, 2), (2, 2)),
            (2, (2,), (2, 2)),
        ],
    )
    def test_point_layout_in_the_contract_maps(self, batch_size, points_shape, out_shape, device, dtype):
        if dtype == torch.bfloat16:
            pytest.skip("torch has no complex bfloat16 dtype, which So2 stores its rotation in")
        pose = Se2.identity(batch_size, device, dtype)
        assert (pose * torch.zeros(points_shape, device=device, dtype=dtype)).shape == out_shape

    def test_se2_batch_validation(self, device: torch.device, dtype: torch.dtype) -> None:
        if dtype == torch.bfloat16:
            pytest.skip("torch has no complex bfloat16 dtype, which So2 stores its rotation in")

        # Incompatible batch sizes (mismatched batches)
        r_batched = So2.identity(2, device=device, dtype=dtype)
        t_mismatched = torch.zeros(3, 2, device=device, dtype=dtype)
        with pytest.raises(ValueError, match="broadcasts"):
            Se2(r_batched, t_mismatched)

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

        # 1. Unbatched rotation with batched translation: Se2(So2.random(), torch.rand(5, 2))
        r_unb = So2.random(device=device, dtype=dtype)
        t_b5 = torch.rand(5, 2, device=device, dtype=dtype)
        pose_unb_r = Se2(r_unb, t_b5)
        ref_unb_r = Se2(So2(r_unb.z.expand(5)), 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 = Se2.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, 2, device=device, dtype=dtype)
        self.assert_close(pose_unb_r * pts5, ref_unb_r * pts5)
        pts1 = torch.rand(1, 2, device=device, dtype=dtype)
        self.assert_close(pose_unb_r * pts1, ref_unb_r * pts1)
        with pytest.raises(ValueError):
            _ = pose_unb_r * torch.rand(4, 2, 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: Se2(So2.random(3), torch.rand(2))
        r_b3 = So2.random(3, device=device, dtype=dtype)
        t_unb = torch.rand(2, device=device, dtype=dtype)
        pose_unb_t = Se2(r_b3, t_unb)
        ref_unb_t = Se2(r_b3, t_unb.expand(3, 2).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 = Se2.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, 2, 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, 2, 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 = Se2(r_unb, t_unb)
        assert pose_unb_both.matrix().shape == (3, 3)
        assert pose_unb_both.log().shape == (3,)
        assert pose_unb_both.adjoint().shape == (3, 3)
        assert pose_unb_both.inverse().matrix().shape == (3, 3)
        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)[:2])

        # 4. Singleton batch broadcasting: (1,) and (4,)
        s_sing1 = Se2(So2.random(1, device=device, dtype=dtype), torch.rand(4, 2, device=device, dtype=dtype))
        ref_sing1 = Se2(So2(s_sing1.r.z.expand(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 = Se2(So2.random(4, device=device, dtype=dtype), torch.rand(1, 2, device=device, dtype=dtype))
        ref_sing2 = Se2(s_sing2.r, s_sing2.t.expand(4, 2).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: unbatched rotation and (2, 3) translation
        r_unb_multi = So2.random(device=device, dtype=dtype)
        t_multi = torch.rand(2, 3, 2, device=device, dtype=dtype)
        s_multi = Se2(r_unb_multi, t_multi)
        assert s_multi.matrix().shape == (2, 3, 3, 3)
        assert s_multi.log().shape == (2, 3, 3)
        assert s_multi.adjoint().shape == (2, 3, 3, 3)
        assert s_multi.inverse().matrix().shape == (2, 3, 3, 3)
        for i in range(2):
            for j in range(3):
                ref_ij = Se2(r_unb_multi, t_multi[i, j])
                self.assert_close(s_multi.matrix()[i, j], ref_ij.matrix())
                self.assert_close(s_multi.log()[i, j], ref_ij.log())
                self.assert_close(s_multi.adjoint()[i, j], ref_ij.adjoint())
                self.assert_close(s_multi.inverse().matrix()[i, j], ref_ij.inverse().matrix())
        self.assert_close(s_multi[0].matrix(), s_multi.matrix()[0])
        self.assert_close(s_multi[1].matrix(), s_multi.matrix()[1])