π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
fix(liegroup): store the Se2/Se3 translation as a registered tensor for every constructor, not a Vector2/Vector3 (#5011)
εΊζ’η68494ae33a53
diff --git a/changelog.d/5011.breaking.md b/changelog.d/5011.breaking.mdnew file mode 100644index 000000000..862db803a--- /dev/null+++ b/changelog.d/5011.breaking.md@@ -0,0 +1,10 @@+`Se2.t` / `Se3.t` (and `.translation`) are now always a tensor registered as module state, whichever constructor built+the pose: `__init__` unwraps a `Vector2`/`Vector3`, and `identity`, `random` and `Se3.from_qxyz` pass tensors. Those+three used to keep a `Vector2`/`Vector3` outside module state, so `Se3.identity(1).t[..., 0]` raised `RuntimeError:+Could not infer dtype of ellipsis`, `Se2.identity(1) * points` returned a `Vector2`, and `state_dict()` and `.to()`+skipped the translation. Their translation is now an `nn.Parameter` with `requires_grad=True` like the other+constructors', so `.x`/`.y`/`.z` on it stop working (index the tensor instead) and `matrix()`, `adjoint()` and `g * p`+of such a pose carry a `grad_fn`; `g * p` still returns a `Vector2`/`Vector3` when `p` is one. Numerical results are+unchanged. A `state_dict` saved before this change has no `_translation` entry for such a pose, so a strict+`load_state_dict` of it now raises `Missing key(s)`; load it with `strict=False`, which keeps the translation the+constructor built, as loading did before. (#5011)diff --git a/kornia/geometry/liegroup/se2.py b/kornia/geometry/liegroup/se2.pyindex 5c1991681..84cf8db6e 100644--- a/kornia/geometry/liegroup/se2.py+++ b/kornia/geometry/liegroup/se2.py@@ -26,7 +26,6 @@ import torch.nn.functional as Ffrom torch import nnfrom kornia.core.check import KORNIA_CHECK, KORNIA_CHECK_SAME_DEVICES, KORNIA_CHECK_SHAPE, KORNIA_CHECK_TYPE-from kornia.core.tensor_wrapper import _unwrapfrom kornia.core.utils import register_module_statefrom kornia.geometry.liegroup.so2 import So2from kornia.geometry.liegroup.so3 import _so3_small_angle_coefficients@@ -65,12 +64,11 @@ class Se2(nn.Module):has the form :math:`[[a, -b], [b, a]]`, a rotation scaled by :math:`\sqrt{a^2 + b^2}`, and keeps the scaleas a non-unit ``z`` that ``log`` drops; it rejects a reflection. Graph export omits the value check andinterprets the block as ``z = m00 + i m10``.+ - ``t`` is always a tensor registered as module state, whichever constructor built the pose; a ``Vector2``+ passed to the constructor is unwrapped. ``g * p`` returns a ``Vector2`` only when ``p`` is one.- Known defects: ``hat`` and ``vee`` put the translation in the bottom row and the angle in a symmetric block- (`#4929 <https://github.com/kornia/kornia/issues/4929>`_); for ``identity``, ``random`` and any pose- composed with or inverted from one, ``t`` and ``g * points`` are a ``Vector2`` instead of a tensor- (`#4931 <https://github.com/kornia/kornia/issues/4931>`_), and ``state_dict`` and ``.to()`` skip that- translation, while ``.to()`` a real dtype breaks the ``So2`` rotation- (`#4923 <https://github.com/kornia/kornia/issues/4923>`_).+ (`#4929 <https://github.com/kornia/kornia/issues/4929>`_), and ``.to()`` a real dtype breaks the ``So2``+ rotation (`#4923 <https://github.com/kornia/kornia/issues/4923>`_).Example:>>> so2 = So2.identity(1)@@ -91,7 +89,8 @@ class Se2(nn.Module):Args:rotation: So2 group encompassing a rotation.- translation: translation vector with the shape of :math:`(B, 2)`.+ translation: translation torch.Tensor with the shape of :math:`(B, 2)`, or a Vector2 wrapping one; the+ tensor is what gets stored.Example:>>> so2 = So2.identity(1)@@ -108,13 +107,11 @@ class Se2(nn.Module):KORNIA_CHECK_TYPE(rotation, So2)if not isinstance(translation, (Vector2, torch.Tensor)):raise TypeError(f"translation type is {type(translation)}")- self._translation: Vector2 | torch.Tensor+ _t_data = translation.data if isinstance(translation, Vector2) else translation+ _check_se2_r_t_shape(rotation, _t_data) # TODO remove+ self._translation: torch.Tensorself._rotation: So2 = rotation- if isinstance(translation, torch.Tensor):- _check_se2_r_t_shape(rotation, translation) # TODO remove- register_module_state(self, "_translation", translation)- else:- self._translation = translation+ register_module_state(self, "_translation", _t_data)def __repr__(self) -> str:return f"rotation: {self.r}\ntranslation: {self.t}"@@ -166,7 +163,7 @@ class Se2(nn.Module):return self._rotation@property- def t(self) -> Vector2 | torch.Tensor:+ def t(self) -> torch.Tensor:"""Return the underlying translation vector of shape :math:`(B,2)`."""return self._translation@@ -176,7 +173,7 @@ class Se2(nn.Module):return self._rotation@property- def translation(self) -> Vector2 | torch.Tensor:+ def translation(self) -> torch.Tensor:"""Return the underlying translation vector of shape :math:`(B,2)`."""return self._translation@@ -248,7 +245,7 @@ class Se2(nn.Module):row0 = torch.stack((a, half_theta), -1)row1 = torch.stack((-half_theta, a), -1)V_inv = torch.stack((row0, row1), -2)- upsilon = V_inv @ _unwrap(self.t)[..., None]+ upsilon = V_inv @ self.t[..., None]return torch.stack((upsilon[..., 0, 0], upsilon[..., 1, 0], theta), -1)@staticmethod@@ -326,15 +323,15 @@ class Se2(nn.Module):Parameter containing:tensor([1.+0.j], requires_grad=True)>>> s.t- x: tensor([0.])- y: tensor([0.])+ Parameter containing:+ tensor([[0., 0.]], requires_grad=True)"""t: torch.Tensor = torch.tensor([0.0, 0.0], device=device, dtype=dtype)if batch_size is not None:KORNIA_CHECK(batch_size >= 1, msg="batch_size must be positive")t = t.repeat(batch_size, 1)- return cls(So2.identity(batch_size, device, dtype), Vector2(t))+ return cls(So2.identity(batch_size, device, dtype), t)def matrix(self) -> torch.Tensor:"""Return the matrix representation of shape :math:`(B, 3, 3)`.@@ -347,7 +344,7 @@ class Se2(nn.Module):[0., 0., 1.]]], grad_fn=<CopySlices>)"""- rt = torch.cat((self.r.matrix(), _unwrap(self.t)[..., None]), -1)+ rt = torch.cat((self.r.matrix(), self.t[..., None]), -1)rt_3x3 = F.pad(rt, (0, 0, 0, 1)) # add last row torch.zerosrt_3x3[..., -1, -1] = 1.0return rt_3x3@@ -388,11 +385,7 @@ class Se2(nn.Module):"""r_inv: So2 = self.r.inverse()- _t = -1 * self.t- if isinstance(_t, int):- raise TypeError("Unexpected integer from `-1 * translation`")-- return Se2(r_inv, r_inv * _t)+ return Se2(r_inv, r_inv * (-1 * self.t))@classmethoddef random(@@ -420,7 +413,7 @@ class Se2(nn.Module):else:KORNIA_CHECK(batch_size >= 1, msg="batch_size must be positive")shape = (batch_size, 2)- return cls(r, Vector2(torch.rand(shape, device=device, dtype=dtype)))+ return cls(r, torch.rand(shape, device=device, dtype=dtype))@classmethoddef trans(cls, x: torch.Tensor, y: torch.Tensor) -> Se2:@@ -471,6 +464,6 @@ class Se2(nn.Module):"""rt = self.matrix()- t = _unwrap(self.t)+ t = self.trt[..., 0:2, 2] = torch.stack((t[..., 1], -t[..., 0]), -1)return rtdiff --git a/kornia/geometry/liegroup/se3.py b/kornia/geometry/liegroup/se3.pyindex 3ec49d887..f3ea6103f 100644--- a/kornia/geometry/liegroup/se3.py+++ b/kornia/geometry/liegroup/se3.py@@ -26,7 +26,6 @@ import torch.nn.functional as Ffrom torch import nnfrom kornia.core.check import KORNIA_CHECK, KORNIA_CHECK_SAME_DEVICES, KORNIA_CHECK_SHAPE-from kornia.core.tensor_wrapper import _unwrapfrom kornia.core.utils import register_module_statefrom kornia.geometry.liegroup.so3 import So3, _so3_small_angle_coefficientsfrom kornia.geometry.linalg import batched_dot_product@@ -52,11 +51,10 @@ class Se3(nn.Module):- The rotation is an :class:`~kornia.geometry.liegroup.So3`, whose storage and point-shape conventionsapply, including its non-unit quaternion defect (`#4942 <https://github.com/kornia/kornia/issues/4942>`_).``from_matrix`` ignores the bottom row.- - Known defects: for ``identity``, ``random``, ``from_qxyz`` and any pose composed with or inverted from one,- ``t`` is a ``Vector3``, which rejects tensor indexing such as ``t[..., 0]``- (`#4931 <https://github.com/kornia/kornia/issues/4931>`_); ``state_dict`` and ``.to()`` skip such a- translation, and skip the rotation unless its quaternion is an ``nn.Parameter``, so ``load_state_dict`` can- restore one pose's translation next to another pose's rotation+ - ``t`` is always a tensor registered as module state, whichever constructor built the pose; a ``Vector3``+ passed to the constructor is unwrapped. ``g * p`` returns a ``Vector3`` only when ``p`` is one.+ - Known defect: ``state_dict`` and ``.to()`` skip the rotation unless its quaternion is an ``nn.Parameter``, so+ ``load_state_dict`` can restore one pose's translation next to another pose's rotation(`#4923 <https://github.com/kornia/kornia/issues/4923>`_).Example:@@ -78,7 +76,8 @@ class Se3(nn.Module):Args:rotation: So3 group encompassing a rotation, or a Quaternion to wrap in one; it is not normalised(`#4942 <https://github.com/kornia/kornia/issues/4942>`_).- translation: Vector3 or translation torch.Tensor with the shape of :math:`(B, 3)`.+ translation: translation torch.Tensor with the shape of :math:`(B, 3)`, or a Vector3 wrapping one; the+ tensor is what gets stored.Example:>>> from kornia.geometry.quaternion import Quaternion@@ -100,12 +99,9 @@ class Se3(nn.Module):raise TypeError(f"translation type is {type(translation)}")_t_data = translation.data if isinstance(translation, Vector3) else translationKORNIA_CHECK_SHAPE(_t_data, ["*", "3"])- self._translation: Vector3 | torch.Tensor+ self._translation: torch.Tensorself._rotation: So3- if isinstance(translation, torch.Tensor):- register_module_state(self, "_translation", translation)- else:- self._translation = translation+ register_module_state(self, "_translation", _t_data)if isinstance(rotation, Quaternion):self._rotation = So3(rotation)else:@@ -141,7 +137,7 @@ class Se3(nn.Module):if isinstance(right, (Vector3, torch.Tensor)):_right_data = right if isinstance(right, torch.Tensor) else right.dataKORNIA_CHECK_SHAPE(_right_data, ["*", "N"])- return so3 * right + _unwrap(t)+ return so3 * right + traise TypeError(f"Unsupported type: {type(right)}")@property@@ -160,7 +156,7 @@ class Se3(nn.Module):return self._rotation@property- def t(self) -> Vector3 | torch.Tensor:+ def t(self) -> torch.Tensor:"""Return the underlying translation vector of shape :math:`(B,3)`."""return self._translation@@ -170,7 +166,7 @@ class Se3(nn.Module):return self._rotation@property- def translation(self) -> Vector3 | torch.Tensor:+ def translation(self) -> torch.Tensor:"""Return the underlying translation vector of shape :math:`(B,3)`."""return self._translation@@ -233,7 +229,7 @@ class Se3(nn.Module):# and take the exact zero elsewhere, where V_inv is the identity.safe_theta_sq = torch.where(nonzero, theta_sq.clamp_min(1e-12), torch.ones_like(theta_sq))theta = torch.where(nonzero, safe_theta_sq.sqrt(), torch.zeros_like(theta_sq))- t = _unwrap(self.t)+ t = self.tomega_hat = So3.hat(omega)omega_hat_sq = omega_hat @ omega_hat# c is finite at theta = 0 (1/12), so V^-1 @ t is taken for every element, which keeps@@ -310,16 +306,15 @@ class Se3(nn.Module):>>> s.rtensor([1., 0., 0., 0.])>>> s.t- x: 0.0- y: 0.0- z: 0.0+ Parameter containing:+ tensor([0., 0., 0.], requires_grad=True)"""t = torch.tensor([0.0, 0.0, 0.0], device=device, dtype=dtype)if batch_size is not None:t = t.repeat(batch_size, 1)- return cls(So3.identity(batch_size, device, dtype), Vector3(t))+ return cls(So3.identity(batch_size, device, dtype), t)def matrix(self) -> torch.Tensor:"""Return the matrix representation of shape :math:`(B, 4, 4)`.@@ -333,7 +328,7 @@ class Se3(nn.Module):[0., 0., 0., 1.]], grad_fn=<CopySlices>)"""- rt = torch.cat((self.r.matrix(), _unwrap(self.t)[..., None]), -1)+ rt = torch.cat((self.r.matrix(), self.t[..., None]), -1)rt_4x4 = F.pad(rt, (0, 0, 0, 1)) # add last row torch.zerosrt_4x4[..., -1, -1] = 1.0return rt_4x4@@ -377,14 +372,13 @@ class Se3(nn.Module):>>> s.rtensor([0., 0., 0., 1.])>>> s.t- x: 0.0- y: 0.0- z: 1.0+ Parameter containing:+ tensor([0., 0., 1.], requires_grad=True)"""KORNIA_CHECK_SHAPE(qxyz, ["*", "7"])q, xyz = qxyz[..., :4], qxyz[..., 4:]- return cls(So3.from_wxyz(q), Vector3(xyz))+ return cls(So3.from_wxyz(q), xyz)def inverse(self) -> Se3:"""Return the inverse transformation.@@ -399,11 +393,7 @@ class Se3(nn.Module):"""r_inv = self.r.inverse()- _t = -1 * self.t- if isinstance(_t, int):- raise TypeError("Unexpected integer from `-1 * translation`")-- return Se3(r_inv, r_inv * _t)+ return Se3(r_inv, r_inv * (-1 * self.t))@classmethoddef random(@@ -431,7 +421,7 @@ class Se3(nn.Module):KORNIA_CHECK(batch_size >= 1, msg="batch_size must be positive")shape = (batch_size,)r = So3.random(batch_size, device, dtype)- t = Vector3.random(shape, device, dtype)+ t = torch.rand((*shape, 3), device=device, dtype=dtype)return cls(r, t)@classmethod@@ -528,7 +518,7 @@ class Se3(nn.Module):[0., 0., 1., 0., 0., 0.],[0., 0., 0., 1., 0., 0.],[0., 0., 0., 0., 1., 0.],- [0., 0., 0., 0., 0., 1.]])+ [0., 0., 0., 0., 0., 1.]], grad_fn=<CatBackward0>)"""R = self.so3.matrix()diff --git a/kornia/geometry/pose.py b/kornia/geometry/pose.pyindex ba2927514..0cc930b70 100644--- a/kornia/geometry/pose.py+++ b/kornia/geometry/pose.py@@ -63,9 +63,8 @@ class NamedPose:>>> b_from_a = NamedPose(Se3.identity(), frame_src="frame_a", frame_dst="frame_b")>>> b_from_aNamedPose(dst_from_src=rotation: tensor([1., 0., 0., 0.])- translation: x: 0.0- y: 0.0- z: 0.0,+ translation: Parameter containing:+ tensor([0., 0., 0.], requires_grad=True),frame_src: frame_a -> frame_dst: frame_b)"""@@ -103,9 +102,7 @@ class NamedPose:>>> c_from_b = NamedPose(Se3.identity(), frame_src="frame_b", frame_dst="frame_c")>>> c_from_b * b_from_aNamedPose(dst_from_src=rotation: tensor([1., 0., 0., 0.])- translation: x: 0.0- y: 0.0- z: 0.0,+ translation: tensor([0., 0., 0.], grad_fn=<AddBackward0>),frame_src: frame_a -> frame_dst: frame_c)"""@@ -212,7 +209,7 @@ class NamedPose:NamedPose constructed from a matrix.Example:- >>> b_from_a_matrix = Se3.identity().matrix()+ >>> b_from_a_matrix = torch.eye(4)>>> b_from_a = NamedPose.from_matrix(b_from_a_matrix, frame_src="frame_a", frame_dst="frame_b")>>> b_from_aNamedPose(dst_from_src=rotation: tensor([1., 0., 0., 0.])@@ -239,9 +236,7 @@ class NamedPose:>>> b_from_a = NamedPose(Se3.identity(), frame_src="frame_a", frame_dst="frame_b")>>> b_from_a.inverse()NamedPose(dst_from_src=rotation: tensor([1., -0., -0., -0.])- translation: x: 0.0- y: 0.0- z: 0.0,+ translation: tensor([0., 0., 0.], grad_fn=<SliceBackward0>),frame_src: frame_b -> frame_dst: frame_a)"""@@ -259,7 +254,7 @@ class NamedPose:Example:>>> b_from_a = NamedPose(Se3.identity(), frame_src="frame_a", frame_dst="frame_b")>>> b_from_a.transform_points(torch.tensor([1., 2., 3.]))- tensor([1., 2., 3.])+ tensor([1., 2., 3.], grad_fn=<AddBackward0>)"""return self._dst_from_src * points_in_srcdiff --git a/tests/geometry/liegroup/test_se2.py b/tests/geometry/liegroup/test_se2.pyindex f7ad7b65f..9314373c5 100644--- a/tests/geometry/liegroup/test_se2.py+++ b/tests/geometry/liegroup/test_se2.py@@ -415,17 +415,17 @@ class TestSe2(BaseTester):converted.t.sum().backward()assert v.grad is not None- def test_wart_se2_vector2_translation_is_not_registered_or_moved_4923(self, device, dtype):+ 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/4923: identity and random keep their Vector2 translation outside- # module state, so it is absent from state_dict() and .to() leaves it at its original dtype. Cast to a- # complex dtype so this pin does not depend on So2's separate real-cast defect under the same issue.+ # 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.for pose in (Se2.identity(1, device, dtype), Se2.random(1, device, dtype)):- assert "_translation" not in pose.state_dict()- pose.to(torch.complex64)- assert pose.r.z.dtype == torch.complex64- assert pose.t.data.dtype == 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()def test_convention_se2_tangent_is_vx_vy_theta_with_V(self, device, dtype):if dtype == torch.bfloat16:@@ -529,18 +529,40 @@ class TestSe2(BaseTester):exported = torch.export.export(FromMatrix(), (matrix,)).module()self.assert_close(exported(matrix), expected)- def test_wart_se2_identity_point_action_returns_a_vector2_4931(self, device, dtype):+ 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- assert isinstance(from_exp * p, torch.Tensor)- # https://github.com/kornia/kornia/issues/4931: identity stores its translation as a Vector2 and __mul__ adds- # it without unwrapping, so the point action of the identity returns a Vector2, not a tensor.- out = identity * p- assert isinstance(out, Vector2)- assert not isinstance(out, torch.Tensor)- self.assert_close(out.data, p)- assert isinstance((from_exp * identity) * p, Vector2) # a product with the identity inherits it+ poses = [+ identity,+ Se2.random(1, device, dtype),+ Se2(So2.identity(1, device, dtype), Vector2(p)),+ from_exp * identity,+ ]+ if dtype != torch.float16: # So2.inverse divides a ComplexHalf z, which the CPU does not implement+ poses.append(identity.inverse())+ for pose in poses:+ assert isinstance(pose.t, torch.Tensor) and 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 and t.max() <= 1, (t.min(), t.max())+ assert 0.45 < t.mean() < 0.55, t.mean()diff --git a/tests/geometry/liegroup/test_se3.py b/tests/geometry/liegroup/test_se3.pyindex b6b6440b4..afa6f104b 100644--- a/tests/geometry/liegroup/test_se3.py+++ b/tests/geometry/liegroup/test_se3.py@@ -525,19 +525,38 @@ class TestSe3(BaseTester):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_wart_se3_translation_type_depends_on_constructor_4931(self, device, dtype):+ 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- assert isinstance(from_exp.t, torch.Tensor)- # https://github.com/kornia/kornia/issues/4931: identity stores its translation as a Vector3, which is not a- # tensor, so tensor indexing of the translation fails for it and works for the exp-built element.- assert isinstance(identity.t, Vector3)- assert not isinstance(identity.t, torch.Tensor)- self.assert_close(from_exp.t[..., 0], torch.zeros(1, device=device, dtype=dtype))- with pytest.raises(RuntimeError):- identity.t[..., 0]- assert isinstance((from_exp * identity).t, Vector3) # a product with the identity inherits it+ 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) and 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_wart_se3_load_state_dict_restores_translation_not_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))@@ -548,8 +567,16 @@ class TestSe3(BaseTester):# only the translation; loading reports every key matched, restores the translation and keeps the old# rotation.assert list(src.state_dict()) == ["_translation"]- assert list(Se3.identity(1, device, dtype).state_dict()) == [] # a Vector3 translation is not saved either+ assert list(Se3.identity(1, device, dtype).state_dict()) == ["_translation"] # the identity saves t alone tooresult = dst.load_state_dict(src.state_dict())assert not result.missing_keys and not result.unexpected_keysself.assert_close(dst.t, src.t.detach())self.assert_close(dst.r.matrix(), eye)++ 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 and t.max() <= 1, (t.min(), t.max())+ assert 0.45 < t.mean() < 0.55, t.mean()