π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
fix(geometry): preserve So2 complex state during dtype conversion (#5453)
RiverYua92218558f32
diff --git a/changelog.d/5453.fixed.md b/changelog.d/5453.fixed.mdnew file mode 100644index 000000000..099486968--- /dev/null+++ b/changelog.d/5453.fixed.md@@ -0,0 +1,7 @@+`So2` module dtype conversions now preserve both complex rotation components:+`float()` and `to(float32)` use complex64, while `double()` and `to(float64)` use+complex128. Parent modules and `Se2` inherit the same behavior; device-only moves+preserve precision. Complex checkpoint keys and shapes remain unchanged.+Half precision uses PyTorch's experimental complex32 support. Since PyTorch has no+complex bfloat16 dtype, bfloat16 casts keep the rotation's existing complex precision+while following device moves; other floating module state still converts to bfloat16.diff --git a/kornia/geometry/liegroup/se2.py b/kornia/geometry/liegroup/se2.pyindex 3197d9453..870343add 100644--- a/kornia/geometry/liegroup/se2.py+++ b/kornia/geometry/liegroup/se2.py@@ -68,8 +68,9 @@ class Se2(nn.Module):passed to the constructor is unwrapped. ``g * p`` returns a ``Vector2`` only when ``p`` is one.- ``hat`` returns the se(2) generator :math:`[[0, -\theta, v_x], [\theta, 0, v_y], [0, 0, 0]]` and ``vee``reads it back, so ``matrix_exp(hat(v))`` equals ``exp(v).matrix()``.- - Known defects: ``.to()`` a real dtype breaks the ``So2`` rotation- (`#4923 <https://github.com/kornia/kornia/issues/4923>`_).+ - Module conversions follow :class:`~kornia.geometry.liegroup.So2`'s dtype policy for the rotation and+ PyTorch's native policy for the translation. A bfloat16 cast changes the translation precision while+ keeping the rotation's existing complex precision; both follow any requested device move.Example:>>> so2 = So2.identity(1)diff --git a/kornia/geometry/liegroup/so2.py b/kornia/geometry/liegroup/so2.pyindex c3293cd83..36fa292cb 100644--- a/kornia/geometry/liegroup/so2.py+++ b/kornia/geometry/liegroup/so2.py@@ -19,6 +19,7 @@# https://github.com/strasdat/Sophus/blob/master/sympy/sophus/so2.pyfrom __future__ import annotations+from collections.abc import Callablefrom typing import Optional, Union, overloadimport torch@@ -42,15 +43,19 @@ class So2(nn.Module):``z`` or angle is accepted and read as :math:`(B,)`. For unit :math:`z = \cos\theta + i \sin\theta`,``matrix()`` is :math:`[[\cos\theta, -\sin\theta], [\sin\theta, \cos\theta]]`. Non-unit ``z = a + i b``is accepted and produces :math:`[[a, -b], [b, a]]`, which rotates and scales by :math:`|z|`. The complex- storage rules out bfloat16.+ storage has no bfloat16 counterpart in PyTorch.- A positive angle rotates the x axis toward the y axis: counter-clockwise in a y-up frame, clockwise asdisplayed on y-down image axes. For a unit rotation, ``matrix()`` is the transpose of:func:`~kornia.geometry.conversions.angle_to_rotation_matrix`, which takes degrees.``log`` returns the angle in :math:`[-\pi, \pi]`, and ``adjoint()`` is the 2x2 identity.- ``hat`` returns the so(2) generator :math:`[[0, -\theta], [\theta, 0]]` and ``vee`` reads its ``[1, 0]``entry, so ``matrix_exp(hat(theta))`` equals ``exp(theta).matrix()``.- - Known defects: ``.to()`` a real dtype keeps the real part of ``z``, drops its imaginary part and makes- ``matrix()`` raise (`#4923 <https://github.com/kornia/kornia/issues/4923>`_).+ - Module dtype conversions act on the real and imaginary components together: ``.float()`` and+ ``.to(torch.float32)`` use complex64 state, while ``.double()`` and ``.to(torch.float64)`` use complex128.+ Device-only conversions preserve the complex precision, and explicit complex dtypes are also accepted.+ The complex checkpoint key ``_z`` and its shape are unchanged. ``.half()`` uses PyTorch's experimental+ complex32 dtype. Since PyTorch has no complex bfloat16 dtype, ``.bfloat16()`` and ``.to(torch.bfloat16)``+ keep the rotation's existing complex precision while following any requested device move.Example:>>> real = torch.tensor([0.6])@@ -91,6 +96,25 @@ class So2(nn.Module):# outer product (#4932).register_module_state(self, "_z", z)+ def _apply(self, fn: Callable[[torch.Tensor], torch.Tensor], recurse: bool = True) -> So2:+ def convert(tensor: torch.Tensor) -> torch.Tensor:+ if not tensor.is_complex():+ return fn(tensor)+ # Apply real dtype conversions to both components, without losing the imaginary part.+ components = torch.view_as_real(tensor.resolve_conj())+ converted = fn(components)+ if converted.is_complex():+ return fn(tensor) # An explicit complex target already has the correct native semantics.+ if converted is components:+ return tensor+ if converted.dtype == torch.bfloat16:+ # No complex bfloat16 exists: move the rotation, keeping its complex precision.+ return tensor.to(device=converted.device)+ return torch.view_as_complex(converted)++ # Let Module manage parameters, existing gradients, buffers and child-module recursion.+ return super()._apply(convert, recurse=recurse)+def __repr__(self) -> str:return f"{self.z}"diff --git a/tests/geometry/liegroup/test_se2.py b/tests/geometry/liegroup/test_se2.pyindex 7b68d005d..fe4e766df 100644--- a/tests/geometry/liegroup/test_se2.py+++ b/tests/geometry/liegroup/test_se2.py@@ -424,6 +424,7 @@ class TestSe2(BaseTester):# (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.dtypeassert converted.t.grad_fn is not Noneconverted.t.sum().backward()assert v.grad is not None@@ -433,12 +434,117 @@ class TestSe2(BaseTester):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 state is left alone by these casts.+ # 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 and 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() and 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 and not result.unexpected_keys+ assert set(target.state_dict()) == set(legacy_state)+ assert target.so2.z.is_complex() and 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:diff --git a/tests/geometry/liegroup/test_so2.py b/tests/geometry/liegroup/test_so2.pyindex de1cdd1bc..f3ebf8647 100644--- a/tests/geometry/liegroup/test_so2.py+++ b/tests/geometry/liegroup/test_so2.py@@ -16,7 +16,6 @@#import math-import warningsimport pytestimport torch@@ -25,7 +24,7 @@ from kornia.geometry.conversions import angle_to_rotation_matrixfrom kornia.geometry.liegroup import Se2, So2from kornia.geometry.vector import Vector2-from testing.base import BaseTester+from testing.base import DYNAMO_UNAVAILABLE_REASON, BaseTester, dynamo_is_availableclass TestSo2(BaseTester):@@ -388,18 +387,231 @@ class TestSo2(BaseTester):torch.optim.SGD(s.parameters(), lr=0.1).step()assert not torch.equal(torch.view_as_real(param.detach()), before)- def test_wart_so2_real_dtype_cast_drops_the_imaginary_part_4923(self, device, dtype):+ @pytest.mark.parametrize("method", ["to", "bfloat16"])+ @pytest.mark.parametrize("as_parameter", [False, True])+ @pytest.mark.parametrize("cdtype", [torch.cfloat, torch.cdouble])+ def test_bfloat16_conversion_keeps_the_rotation_4923(self, device, method, as_parameter, cdtype):+ # No complex bfloat16 exists: keep both rotation components at their original precision while moving them.+ source_dtype = torch.float32 if cdtype == torch.cfloat else torch.float64+ angle = torch.tensor([0.3], dtype=source_dtype, requires_grad=not as_parameter)+ data = torch.complex(angle.cos(), angle.sin())+ rotation = So2(torch.nn.Parameter(data) if as_parameter else data)+ before = rotation.z.detach().clone()+ if as_parameter:+ (rotation.z.real.sum() + 2 * rotation.z.imag.sum()).backward()+ parent = torch.nn.ModuleDict({"rotation": rotation, "linear": torch.nn.Linear(2, 2)})+ if method == "to":+ parent.to(device=device, dtype=torch.bfloat16)+ else:+ parent.to(device=device).bfloat16()++ assert parent["linear"].weight.dtype == torch.bfloat16+ assert parent["linear"].weight.device == device+ assert rotation.z.dtype == before.dtype+ assert rotation.z.device == device+ assert isinstance(rotation._z, torch.nn.Parameter) == as_parameter+ state = dict(rotation.named_parameters()) if as_parameter else dict(rotation.named_buffers())+ assert state["_z"] is rotation._z+ self.assert_close(rotation.z, before.to(device))+ c, s = before.real.to(device), before.imag.to(device)+ expected_matrix = torch.stack((c, -s, s, c), -1).reshape(1, 2, 2)+ self.assert_close(rotation.matrix(), expected_matrix)+ point = torch.tensor([[1.0, 2.0]], device=device, dtype=torch.bfloat16)+ self.assert_close(rotation * point, torch.stack((c - 2 * s, s + 2 * c), -1))+ if as_parameter:+ assert rotation._z.grad.dtype == before.dtype+ assert rotation._z.grad.device == device+ self.assert_close(rotation._z.grad.real, torch.ones_like(c))+ self.assert_close(rotation._z.grad.imag, torch.full_like(s, 2.0))+ else:+ (rotation * point).sum().backward()+ self.assert_close(angle.grad, -3 * angle.detach().sin() - angle.detach().cos())+++class _So2PointTransform(torch.nn.Module):+ def __init__(self, rotation: So2) -> None:+ super().__init__()+ self.rotation = rotation++ def forward(self, point: torch.Tensor) -> torch.Tensor:+ return (self.rotation.matrix() @ point[..., None]).squeeze(-1)+++class TestSo2DtypeMigration(BaseTester):+ @pytest.fixture(autouse=True)+ def _require_complex_dtype(self, dtype):if dtype == torch.bfloat16:- pytest.skip("torch has no complex bfloat16 dtype, which So2 stores its rotation in")- theta = torch.tensor([0.3, -1.2], device=device, dtype=dtype)- g = So2.exp(theta)- assert g.z.is_complex()- with warnings.catch_warnings():- warnings.simplefilter("ignore") # torch warns, once per process, that the cast discards the imaginary part- cast = g.to(torch.float32)- # https://github.com/kornia/kornia/issues/4923: nn.Module.to(float32) casts the complex state z to a real- # tensor, which keeps cos(theta) and drops sin(theta), so the rotation is lost and matrix() raises.- assert not cast.z.is_complex()- self.assert_close(cast.z, theta.cos().float())- with pytest.raises(RuntimeError):- cast.matrix()+ pytest.skip("PyTorch has no complex bfloat16 dtype; module bfloat16 conversion is tested separately")++ def _source_dtype(self, device, dtype):+ # Exercise a precision change in both directions, without constructing float64 on MPS.+ return torch.float64 if dtype == torch.float32 and device.type != "mps" else torch.float32++ def _cast(self, module, dtype, method):+ if method == "to":+ return module.to(dtype=dtype)+ name = {torch.float16: "half", torch.float32: "float", torch.float64: "double"}[dtype]+ return getattr(module, name)()++ @pytest.mark.parametrize("method", ["to", "convenience"])+ @pytest.mark.parametrize("as_parameter", [False, True])+ @pytest.mark.parametrize("shape", [(), (2,), (2, 1)])+ def test_real_dtype_conversion_4923(self, device, dtype, method, as_parameter, shape):+ source_dtype = self._source_dtype(device, dtype)+ theta = torch.tensor([0.3, -1.2] if shape else 0.3, device=device, dtype=source_dtype)+ theta = theta.reshape(shape).requires_grad_(not as_parameter)+ data = torch.complex(theta.cos(), theta.sin())+ rotation = So2(torch.nn.Parameter(data) if as_parameter else data)+ before = rotation.z.detach().clone()++ assert self._cast(rotation, dtype, method) is rotation+ assert rotation.z.is_complex() and rotation.z.real.dtype == dtype+ assert rotation.state_dict()["_z"].shape == shape+ self.assert_close(rotation.z.real, before.real.to(dtype))+ self.assert_close(rotation.z.imag, before.imag.to(dtype))+ c, s = before.real.to(dtype), before.imag.to(dtype)+ expected = torch.stack((c, -s, s, c), -1).reshape(*c.shape, 2, 2)+ self.assert_close(rotation.matrix(), expected)+ if as_parameter:+ assert dict(rotation.named_parameters())["_z"] is rotation._z+ assert not dict(rotation.named_buffers())+ else:+ assert dict(rotation.named_buffers())["_z"] is rotation._z+ assert not dict(rotation.named_parameters())++ @pytest.mark.parametrize("method", ["to", "convenience"])+ def test_parent_conversion_preserves_recursion(self, device, dtype, method):+ source_dtype = self._source_dtype(device, dtype)+ rotation = So2.exp(torch.tensor([0.3], device=device, dtype=source_dtype, requires_grad=True))+ rotation.extra = torch.nn.Module()+ rotation.extra.register_buffer("value", torch.ones(1, device=device, dtype=source_dtype))+ rotation.extra.weight = torch.nn.Parameter(torch.ones(1, device=device, dtype=source_dtype))+ rotation.extra.weight.sum().backward()+ parent = torch.nn.ModuleDict({"rotation": rotation})++ assert self._cast(parent, dtype, method) is parent+ assert rotation.z.is_complex() and rotation.z.real.dtype == dtype+ assert rotation.extra.value.dtype == dtype+ assert rotation.extra.weight.dtype == dtype and rotation.extra.weight.grad.dtype == dtype+ assert dict(parent.named_parameters())["rotation.extra.weight"] is rotation.extra.weight+ assert dict(parent.named_buffers())["rotation._z"] is rotation._z++ def test_parameter_gradient_and_optimizer(self, device, dtype):+ theta = torch.tensor([0.3, -1.2], device=device, dtype=self._source_dtype(device, dtype))+ parameter = torch.nn.Parameter(torch.complex(theta.cos(), theta.sin()))+ rotation = So2(parameter)+ assert rotation._z is parameter+ before = parameter.detach().clone()+ (rotation.z.real.sum() + 2 * rotation.z.imag.sum()).backward()+ rotation.to(dtype=dtype)++ assert isinstance(rotation._z, torch.nn.Parameter)+ assert dict(rotation.named_parameters())["_z"] is rotation._z+ assert rotation._z.grad.is_complex() and rotation._z.grad.real.dtype == dtype+ self.assert_close(rotation._z.grad.real, torch.ones(2, device=device, dtype=dtype))+ self.assert_close(rotation._z.grad.imag, torch.full((2,), 2.0, device=device, dtype=dtype))+ torch.optim.SGD(rotation.parameters(), lr=0.125).step()+ self.assert_close(rotation.z.real, before.real.to(dtype) - 0.125)+ self.assert_close(rotation.z.imag, before.imag.to(dtype) - 0.25)++ @pytest.mark.parametrize("method", ["to", "convenience"])+ def test_angle_gradient_matches_real_reference(self, device, dtype, method):+ angle = torch.tensor([0.3, -1.2], device=device, dtype=self._source_dtype(device, dtype), requires_grad=True)+ reference_angle = angle.detach().clone().requires_grad_()+ rotation = So2.exp(angle)+ self._cast(rotation, dtype, method)+ point = torch.tensor([[1.0, 2.0], [-3.0, 1.0]], device=device, dtype=dtype)+ weights = torch.tensor([[2.0, -1.0], [1.0, 3.0]], device=device, dtype=dtype)+ c, s = reference_angle.cos().to(dtype), reference_angle.sin().to(dtype)+ x, y = point.unbind(-1)+ expected = torch.stack((c * x - s * y, s * x + c * y), -1)+ actual = rotation * point+ self.assert_close(actual, expected)+ actual_grad = torch.autograd.grad((actual * weights).sum(), angle)[0]+ expected_grad = torch.autograd.grad((expected * weights).sum(), reference_angle)[0]+ self.assert_close(actual_grad, expected_grad)++ def test_conjugate_view_preserves_gradient(self, device, dtype):+ theta = torch.tensor([0.3], device=device, dtype=self._source_dtype(device, dtype))+ data = torch.complex(theta.cos(), theta.sin()).requires_grad_()+ rotation = So2(data.conj())+ assert rotation.z.is_conj()+ rotation.to(dtype=dtype)+ self.assert_close(rotation.z.real, data.real.to(dtype))+ self.assert_close(rotation.z.imag, -data.imag.to(dtype))+ (rotation * torch.tensor([[1.0, 2.0]], device=device, dtype=dtype)).sum().backward()+ self.assert_close(data.grad.real, torch.full_like(data.real, 3.0))+ self.assert_close(data.grad.imag, torch.ones_like(data.imag))++ @pytest.mark.parametrize("conjugate", [False, True])+ def test_noop_conversion_preserves_buffer(self, device, dtype, conjugate):+ theta = torch.tensor([0.3], device=device, dtype=dtype, requires_grad=True)+ data = torch.complex(theta.cos(), theta.sin())+ if conjugate:+ data = data.conj()+ rotation = So2(data)+ assert rotation.to(device=device)._z is data+ assert rotation.to(dtype=dtype)._z is data+ assert rotation.to(dtype=data.dtype)._z is data+ assert self._cast(rotation, dtype, "convenience")._z is data++ def test_explicit_complex_dtype(self, device, dtype):+ rotation = So2.exp(torch.tensor([0.3], device=device, dtype=self._source_dtype(device, dtype)))+ before = rotation.z.detach().clone()+ complex_dtype = torch.complex(torch.empty((), dtype=dtype), torch.empty((), dtype=dtype)).dtype+ rotation.to(dtype=complex_dtype)+ assert rotation.z.dtype == complex_dtype+ self.assert_close(rotation.z.real, before.real.to(dtype))+ self.assert_close(rotation.z.imag, before.imag.to(dtype))++ def test_checkpoint_compatibility(self, device, dtype):+ theta = torch.tensor([0.3, -1.2], device=device, dtype=self._source_dtype(device, dtype))+ legacy_state = {"_z": torch.complex(theta.cos(), theta.sin())}+ target = So2.exp((-theta).requires_grad_()).to(dtype=dtype)+ assert target._z.data_ptr() != legacy_state["_z"].data_ptr()+ result = target.load_state_dict(legacy_state)+ assert not result.missing_keys and not result.unexpected_keys+ assert list(target.state_dict()) == ["_z"]+ assert target.state_dict()["_z"].shape == legacy_state["_z"].shape+ assert target.z.is_complex() and target.z.real.dtype == dtype+ self.assert_close(target.z.real, legacy_state["_z"].real.to(dtype))+ self.assert_close(target.z.imag, legacy_state["_z"].imag.to(dtype))+ restored = So2.identity(2, device, dtype)+ restored.load_state_dict(target.state_dict())+ self.assert_close(restored.matrix(), target.matrix())+ point = torch.tensor([[1.0, 2.0], [-3.0, 1.0]], device=device, dtype=dtype)+ c, s = theta.cos().to(dtype), theta.sin().to(dtype)+ x, y = point.unbind(-1)+ self.assert_close(restored * point, torch.stack((c * x - s * y, s * x + c * y), -1))++ @pytest.mark.parametrize("as_parameter", [False, True])+ @pytest.mark.parametrize("change_dtype", [False, True])+ def test_parent_device_migration(self, device, dtype, as_parameter, change_dtype):+ source_dtype = self._source_dtype(device, dtype) if change_dtype else dtype+ angle = torch.tensor([0.3, -1.2], dtype=source_dtype, requires_grad=not as_parameter)+ data = torch.complex(angle.cos(), angle.sin())+ rotation = So2(torch.nn.Parameter(data) if as_parameter else data)+ parent = torch.nn.ModuleDict({"rotation": rotation})+ assert rotation.z.device.type == "cpu"+ if change_dtype:+ parent.to(device=device, dtype=dtype)+ else:+ parent.to(device=device)+ assert rotation.z.device == device+ assert rotation.z.is_complex() and rotation.z.real.dtype == dtype+ assert parent.state_dict()["rotation._z"].device == device+ assert isinstance(rotation._z, torch.nn.Parameter) == as_parameter+ c, s = angle.cos().to(device=device, dtype=dtype), angle.sin().to(device=device, dtype=dtype)+ point = torch.tensor([[1.0, 2.0], [-3.0, 1.0]], device=device, dtype=dtype)+ x, y = point.unbind(-1)+ self.assert_close(rotation * point, torch.stack((c * x - s * y, s * x + c * y), -1))+ restored = So2.identity(2, device, dtype)+ restored.load_state_dict(rotation.state_dict())+ self.assert_close(restored.matrix(), rotation.matrix())++ @pytest.mark.skipif(not dynamo_is_available(), reason=DYNAMO_UNAVAILABLE_REASON)+ def test_dynamo(self, device, dtype, torch_optimizer):+ rotation = So2.exp(torch.tensor([0.3, -1.2], device=device, dtype=self._source_dtype(device, dtype)))+ model = _So2PointTransform(rotation).to(dtype=dtype)+ point = torch.tensor([[1.0, 2.0], [-3.0, 1.0]], device=device, dtype=dtype)+ self.assert_close(torch_optimizer(model, fullgraph=True)(point), model(point))