π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
Fix Lie group shape validation and quaternion coefficient handling (#6513)
Bhavya Kumar760326ffd683
diff --git a/changelog.d/6513.fixed.md b/changelog.d/6513.fixed.mdnew file mode 100644index 000000000..98409d445--- /dev/null+++ b/changelog.d/6513.fixed.md@@ -0,0 +1 @@+`Se2` and `Se3` reject a translation whose batch does not broadcast with the rotation batch when they are built; before, the pose was built and `matrix()` raised a raw shape error later. Their `matrix()`, `log()`, `adjoint()` and indexing now expand a rotation and translation that broadcast, such as one `Se3` rotation with `(N, 3)` translations or a batch of one on either side. `Quaternion.from_coeffs` builds a quaternion of the default floating dtype from integer or `bool` coefficients, which used to give an `int64` or `bool` quaternion, and rejects complex coefficients. `average_quaternions` accepts `(M, 1)` weights, which raised a raw `RuntimeError`.diff --git a/kornia/geometry/liegroup/se2.py b/kornia/geometry/liegroup/se2.pyindex e27c3505e..1d0921257 100644--- a/kornia/geometry/liegroup/se2.py+++ b/kornia/geometry/liegroup/se2.py@@ -34,17 +34,16 @@ from kornia.geometry.vector import Vector2def _check_se2_r_t_shape(r: So2, t: torch.Tensor) -> None:- z_shape = r.z.shape- if ((len(z_shape) == 1) and (len(t.shape) == 2)) or ((len(z_shape) == 0) and len(t.shape) == 1):- # check_se2_t_shape- is_batch_shape = KORNIA_CHECK_SHAPE(t, ["B", "2"], raises=False)- is_single_shape = KORNIA_CHECK_SHAPE(t, ["2"], raises=False)- if not (is_batch_shape or is_single_shape):- raise ValueError(f"Invalid translation shape, we expect [B, 2], or [2] Got: {t.shape}")- else:+ KORNIA_CHECK_SHAPE(t, ["*", "2"])+ r_batch = r.z.shape+ t_batch = t.shape[:-1]+ try:+ torch.broadcast_shapes(r_batch, t_batch)+ except RuntimeError:raise ValueError(- f"Invalid input, both the inputs should be either batched or unbatched. Got: {r.z.shape} and {t.shape}"- )+ f"Expected a translation whose batch broadcasts with the rotation batch {tuple(r_batch)}. "+ f"Got translation of shape {tuple(t.shape)}."+ ) from Nonedef _check_se2_r_t_dtype_device(r: So2, t: torch.Tensor) -> None:@@ -140,16 +139,19 @@ class Se2(nn.Module):Args:rotation: So2 group encompassing a rotation.- translation: translation torch.Tensor with the shape of ``(B, 2)``, or a Vector2 wrapping one; the- tensor is what gets stored. It must have the rotation's dtype (``z``'s real dtype) and device;+ translation: translation torch.Tensor with shape ``(B, 2)``, or ``(2,)`` for an unbatched translation,+ or a Vector2 wrapping one; the tensor is what gets stored. Multidimensional batch shapes ``(*, 2)``+ are also accepted. The rotation and translation batch shapes must be broadcastable (an unbatched side+ may broadcast against a batched side). Incompatible batch shapes raise a ``ValueError`` at+ construction time. It must have the rotation's dtype (``z``'s real dtype) and device;a bfloat16 translation is also accepted beside a complex32, complex64 or complex128 rotation, whichis what ``.bfloat16()`` leaves (PyTorch has no complex bfloat16). Every method then reads thetranslation at the rotation's precision, and ``inverse`` and ``g * g`` return a translation of the- rotation's real dtype. It must be batched exactly when the rotation is (``ValueError`` otherwise), but- its batch size is not checked against the rotation's: a mismatch fails later, in ``matrix()``- (`#6482 <https://github.com/kornia/kornia/issues/6482>`_).+ rotation's real dtype.Raises:+ ValueError: if translation shape does not end in 2, or rotation and translation batch shapes cannot be+ broadcast.TypeCheckError: if the translation is an integer, bool or complex tensor (an ``nn.Parameter`` too), or itsdtype differs from the rotation's (``log`` and the other methods cannot combine them).DeviceError: if the translation is on another device than the rotation.@@ -180,15 +182,30 @@ class Se2(nn.Module):return f"rotation: {self.r}\ntranslation: {self.t}"def __getitem__(self, idx: int | slice) -> Se2:- return Se2(self._rotation[idx], self._translation[idx])+ r = self._rotation+ t = self._translation+ r_batch = r.z.shape+ t_batch = t.shape[:-1]+ if len(r_batch) == 0 and len(t_batch) == 0:+ return Se2(r[idx], t[idx])+ r_b = (1,) if len(r_batch) == 0 else r_batch+ t_b = (1,) if len(t_batch) == 0 else t_batch+ b_batch = torch.broadcast_shapes(r_b, t_b)+ z = r.z if r.z.shape == b_batch else r.z.expand(b_batch)+ t_exp = t if t.shape[:-1] == b_batch else t.expand(b_batch + (2,))+ return Se2(So2(z[idx]), t_exp[idx])def _mul_se2(self, right: Se2) -> Se2:so2 = self.so2t = self.t_r = so2 * right.so2+ z = so2.z+ real, imag = z.real, z.imag+ x, y = right.t[..., 0], right.t[..., 1]+ rot_t = torch.stack((real * x - imag * y, imag * x + real * y), -1)# the rotation's real dtype: beside a complex32 rotation, a bfloat16 translation (what ``.bfloat16()``# leaves) would otherwise be promoted to float32, which the constructor rejects- _t = (t + so2 * right.t).to(_r.z.real.dtype)+ _t = (t + rot_t).to(_r.z.real.dtype)return Se2(_r, _t)@overload@@ -215,8 +232,9 @@ class Se2(nn.Module):KORNIA_CHECK_TYPE(right, Se2)return self._mul_se2(right)if isinstance(right, (Vector2, torch.Tensor)):- # _check_se2_r_t_shape(so2, risght)- return so2 * right + t+ b_batch = torch.broadcast_shapes(so2.z.shape, t.shape[:-1])+ rot = so2 if so2.z.shape == b_batch else So2(so2.z.expand(b_batch))+ return rot * right + traise TypeError(f"Unsupported type: {type(right)}")@property@@ -314,6 +332,8 @@ class Se2(nn.Module):V_inv = torch.stack((row0, row1), -2)# the translation is read at the rotation's precision, so a bfloat16 translation beside a wider rotation worksupsilon = V_inv @ self.t.to(theta.dtype)[..., None]+ if theta.shape != upsilon.shape[:-2]:+ theta = theta.expand(upsilon.shape[:-2])return torch.stack((upsilon[..., 0, 0], upsilon[..., 1, 0], theta), -1)@staticmethod@@ -414,7 +434,13 @@ class Se2(nn.Module):"""r_matrix = self.r.matrix()- rt = torch.cat((r_matrix, self.t.to(r_matrix.dtype)[..., None]), -1)+ b_batch = torch.broadcast_shapes(r_matrix.shape[:-2], self.t.shape[:-1])+ if r_matrix.shape[:-2] != b_batch:+ r_matrix = r_matrix.expand(b_batch + (2, 2))+ t = self.t.to(r_matrix.dtype)+ if t.shape[:-1] != b_batch:+ t = t.expand(b_batch + (2,))+ rt = torch.cat((r_matrix, t[..., None]), -1)rt_3x3 = F.pad(rt, (0, 0, 0, 1)) # add last row torch.zerosrt_3x3[..., -1, -1] = 1.0return rt_3x3@@ -455,8 +481,12 @@ class Se2(nn.Module):"""r_inv: So2 = self.r.inverse()+ z = r_inv.z+ real, imag = z.real, z.imag+ x, y = -self.t[..., 0], -self.t[..., 1]+ t_inv = torch.stack((real * x - imag * y, imag * x + real * y), -1)# the rotation's real dtype, as in ``__mul__``- return Se2(r_inv, (r_inv * (-1 * self.t)).to(r_inv.z.real.dtype))+ return Se2(r_inv, t_inv.to(r_inv.z.real.dtype))@classmethoddef random(@@ -535,6 +565,9 @@ class Se2(nn.Module):"""rt = self.matrix()+ b_batch = rt.shape[:-2]t = self.t+ if t.shape[:-1] != b_batch:+ t = t.expand(b_batch + (2,))rt[..., 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 d83b0b8fa..e731667ee 100644--- a/kornia/geometry/liegroup/se3.py+++ b/kornia/geometry/liegroup/se3.py@@ -34,6 +34,19 @@ from kornia.geometry.quaternion import Quaternionfrom kornia.geometry.vector import Vector3+def _check_se3_r_t_shape(r: Quaternion | So3, t: torch.Tensor) -> None:+ q = r.q if isinstance(r, So3) else r+ r_batch = q.data.shape[:-1]++ try:+ torch.broadcast_shapes(r_batch, t.shape[:-1])+ except RuntimeError:+ raise ValueError(+ f"Expected a translation whose batch broadcasts with the rotation batch {tuple(r_batch)}. "+ f"Got translation of shape {tuple(t.shape)}."+ ) from None++def _check_se3_r_t_dtype_device(r: Quaternion | So3, t: torch.Tensor) -> None:"""Reject a translation the rotation's methods cannot combine with: another dtype or another device."""q = r.q if isinstance(r, So3) else r@@ -131,12 +144,15 @@ class Se3(nn.Module):Args:rotation: So3 group encompassing a rotation, or a Quaternion to wrap in one; it is stored as given, anda non-unit quaternion stands for the rotation of its direction.- translation: translation torch.Tensor with the shape of ``(B, 3)``, or a Vector3 wrapping one; the- tensor is what gets stored. It must have the rotation's dtype and device. Its batch is not checked- against the rotation's: a mismatch fails later, in ``matrix()``- (`#6482 <https://github.com/kornia/kornia/issues/6482>`_).+ translation: translation torch.Tensor with shape ``(B, 3)``, or ``(3,)`` for an unbatched translation,+ or a Vector3 wrapping one; the tensor is what gets stored. Multidimensional batch shapes ``(*, 3)``+ are also accepted. The rotation and translation batch shapes must be broadcastable (an unbatched side+ may broadcast against a batched side). Incompatible batch shapes raise a ``ValueError`` at+ construction time. It must have the rotation's dtype and device.Raises:+ ValueError: if translation shape does not end in 3, or rotation and translation batch shapes cannot be+ broadcast.TypeCheckError: if the translation is an integer, bool or complex tensor (an ``nn.Parameter`` too), or itsdtype differs from the rotation's (``inverse``, ``adjoint`` and the other methods cannot combine them).DeviceError: if the translation is on another device than the rotation.@@ -161,6 +177,7 @@ 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"])+ _check_se3_r_t_shape(rotation, _t_data)_check_se3_r_t_dtype_device(rotation, _t_data)self._translation: torch.Tensorself._rotation: So3@@ -174,7 +191,19 @@ class Se3(nn.Module):return f"rotation: {self.r}\ntranslation: {self.t}"def __getitem__(self, idx: int | slice) -> Se3:- return Se3(self._rotation[idx], self._translation[idx])+ r = self._rotation+ t = self._translation+ q = r.q if isinstance(r, So3) else r+ r_batch = q.data.shape[:-1]+ t_batch = t.shape[:-1]+ if len(r_batch) == 0 and len(t_batch) == 0:+ return Se3(r[idx], t[idx])+ r_b = (1,) if len(r_batch) == 0 else r_batch+ t_b = (1,) if len(t_batch) == 0 else t_batch+ b_batch = torch.broadcast_shapes(r_b, t_b)+ q_data = q.data if q.data.shape[:-1] == b_batch else q.data.expand(b_batch + (4,))+ t_exp = t if t.shape[:-1] == b_batch else t.expand(b_batch + (3,))+ return Se3(So3(Quaternion(q_data[idx])), t_exp[idx])def _mul_se3(self, right: Se3) -> Se3:_r = self.r * right.r@@ -317,7 +346,13 @@ class Se3(nn.Module):V_inv = (torch.eye(3, device=omega.device, dtype=omega.dtype) - 0.5 * omega_hat + c[..., None, None] * omega_hat_sq)- return torch.cat(((t[..., None, :] * V_inv).sum(-1), omega), -1)+ upsilon = (t[..., None, :] * V_inv).sum(-1)+ b_batch = torch.broadcast_shapes(upsilon.shape[:-1], omega.shape[:-1])+ if upsilon.shape[:-1] != b_batch:+ upsilon = upsilon.expand(b_batch + (3,))+ if omega.shape[:-1] != b_batch:+ omega = omega.expand(b_batch + (3,))+ return torch.cat((upsilon, omega), -1)@staticmethoddef hat(v: torch.Tensor) -> torch.Tensor:@@ -407,7 +442,14 @@ class Se3(nn.Module):[0., 0., 0., 1.]], grad_fn=<CopySlices>)"""- rt = torch.cat((self.r.matrix(), self.t[..., None]), -1)+ r_matrix = self.r.matrix()+ b_batch = torch.broadcast_shapes(r_matrix.shape[:-2], self.t.shape[:-1])+ if r_matrix.shape[:-2] != b_batch:+ r_matrix = r_matrix.expand(b_batch + (3, 3))+ t = self.t.to(r_matrix.dtype)+ if t.shape[:-1] != b_batch:+ t = t.expand(b_batch + (3,))+ rt = torch.cat((r_matrix, t[..., None]), -1)rt_4x4 = F.pad(rt, (0, 0, 0, 1)) # add last row torch.zerosrt_4x4[..., -1, -1] = 1.0return rt_4x4@@ -472,7 +514,7 @@ class Se3(nn.Module):"""r_inv = self.r.inverse()- return Se3(r_inv, r_inv * (-1 * self.t))+ return Se3(r_inv, _so3_rotate(r_inv.q, -self.t).to(self.t.dtype))@classmethoddef random(@@ -601,7 +643,13 @@ class Se3(nn.Module):"""R = self.so3.matrix()+ b_batch = torch.broadcast_shapes(R.shape[:-2], self.t.shape[:-1])+ if R.shape[:-2] != b_batch:+ R = R.expand(b_batch + (3, 3))+ t = self.t+ if t.shape[:-1] != b_batch:+ t = t.expand(b_batch + (3,))z = torch.zeros_like(R)- row0 = torch.cat((R, So3.hat(self.t) @ R), -1)+ row0 = torch.cat((R, So3.hat(t) @ R), -1)row1 = torch.cat((z, R), -1)return torch.cat((row0, row1), -2)diff --git a/kornia/geometry/quaternion.py b/kornia/geometry/quaternion.pyindex 429459e50..10c27c940 100644--- a/kornia/geometry/quaternion.py+++ b/kornia/geometry/quaternion.py@@ -598,7 +598,19 @@ class Quaternion(nn.Module):tensor([1., 0., 0., 0.])"""- return cls(torch.tensor([w, x, y, z]))+ coeffs = (w, x, y, z)+ for c in coeffs:+ if isinstance(c, complex):+ raise ValueError(f"Quaternion coefficients must be real-valued, got complex scalar {c}")+ if isinstance(c, torch.Tensor) and c.is_complex():+ raise ValueError(+ f"Quaternion coefficients must be real-valued, got complex tensor with dtype {c.dtype}"+ )++ data = torch.tensor([w, x, y, z])+ if not data.is_floating_point():+ data = data.to(torch.get_default_dtype())+ return cls(data)# TODO: update signature# def random(cls, shape: Optional[List] = None, device = None, dtype = None) -> 'Quaternion':@@ -765,8 +777,8 @@ def average_quaternions(Q: "Quaternion", w: Optional[torch.Tensor] = None) -> "Qr"""Average quaternions as their weighted chordal mean rotation, whatever their signs.``q_mean = average_quaternions(Q, w)`` takes a :class:`Quaternion` of ``M`` quaternions, ``(M, 4)``, and optional- non-negative weights ``w`` of shape ``(M,)``, uniform by default, and returns their mean rotation as a unit- :class:`Quaternion` of shape ``(1, 4)``. To interpolate between two rotations instead, use+ non-negative weights ``w`` of shape ``(M,)`` or ``(M, 1)``, uniform by default, and returns their mean rotation as+ a unit :class:`Quaternion` of shape ``(1, 4)``. To interpolate between two rotations instead, use:meth:`Quaternion.slerp`.Convention:@@ -779,8 +791,7 @@ def average_quaternions(Q: "Quaternion", w: Optional[torch.Tensor] = None) -> "QArgs:Q: quaternions of shape ``(M, 4)``.- w: weights of shape ``(M,)``. If None, uniform weights are used. ``(M, 1)`` weights raise a- ``RuntimeError`` (`#6482 <https://github.com/kornia/kornia/issues/6482>`_).+ w: weights of shape ``(M,)`` or ``(M, 1)``. If None, uniform weights are used.Returns:the averaged quaternion, of unit norm and shape ``(1, 4)``.@@ -811,9 +822,11 @@ def average_quaternions(Q: "Quaternion", w: Optional[torch.Tensor] = None) -> "Qif w is None:A = (data.T @ data) / Melse:+ if w.shape == (M, 1):+ w = w.squeeze(-1)+ elif w.shape != (M,):+ raise ValueError(f"weights shape {tuple(w.shape)} must be ({M},) or ({M}, 1)")w = w.to(data.device, dtype=data.dtype)- if w.numel() != M:- raise ValueError(f"weights length {w.numel()} must match number of quaternions {M}")if bool((w < 0).any()):raise ValueError("weights must be non-negative")w_sum = w.sum()diff --git a/tests/geometry/liegroup/test_se2.py b/tests/geometry/liegroup/test_se2.pyindex 4396650ac..68fa5dbe8 100644--- a/tests/geometry/liegroup/test_se2.py+++ b/tests/geometry/liegroup/test_se2.py@@ -923,3 +923,108 @@ class TestSe2(BaseTester):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])diff --git a/tests/geometry/liegroup/test_se3.py b/tests/geometry/liegroup/test_se3.pyindex 8cbb270c5..b01ff2f17 100644--- a/tests/geometry/liegroup/test_se3.py+++ b/tests/geometry/liegroup/test_se3.py@@ -769,6 +769,112 @@ class TestSe3(BaseTester):assert t.max() <= 1, (t.min(), t.max())assert 0.45 < t.mean() < 0.55, t.mean()+ def test_se3_batch_validation(self, device: torch.device, dtype: torch.dtype) -> None:+ # Incompatible batch sizes (mismatched batches)+ q_b3 = Quaternion.identity(3, device=device, dtype=dtype)+ t_b2 = torch.zeros(2, 3, device=device, dtype=dtype)+ with pytest.raises(ValueError, match="broadcasts"):+ Se3(q_b3, t_b2)++ so3_b3 = So3.identity(3, device=device, dtype=dtype)+ with pytest.raises(ValueError, match="broadcasts"):+ Se3(so3_b3, t_b2)++ with pytest.raises(ValueError, match=r"Shape mismatch at dimension.*expected 3, got 4"):+ Se3(so3_b3, torch.zeros(3, 4, device=device, dtype=dtype))++ # 1. Unbatched rotation with batched translation: Se3(So3.random(), torch.rand(5, 3))+ r_unb = So3.random(device=device, dtype=dtype)+ t_b5 = torch.rand(5, 3, device=device, dtype=dtype)+ pose_unb_r = Se3(r_unb, t_b5)+ ref_unb_r = Se3(So3(Quaternion(r_unb.q.data.expand(5, 4))), t_b5.clone())+ self.assert_close(pose_unb_r.matrix(), ref_unb_r.matrix())+ self.assert_close(pose_unb_r.log(), ref_unb_r.log())+ self.assert_close(pose_unb_r.adjoint(), ref_unb_r.adjoint())+ self.assert_close(pose_unb_r.inverse().matrix(), ref_unb_r.inverse().matrix())++ other5 = Se3.random(5, device=device, dtype=dtype)+ self.assert_close((pose_unb_r * other5).matrix(), (ref_unb_r * other5).matrix())+ self.assert_close((other5 * pose_unb_r).matrix(), (other5 * ref_unb_r).matrix())++ pts5 = torch.rand(5, 3, device=device, dtype=dtype)+ self.assert_close(pose_unb_r * pts5, ref_unb_r * pts5)+ pts1 = torch.rand(1, 3, device=device, dtype=dtype)+ self.assert_close(pose_unb_r * pts1, ref_unb_r * pts1)+ # an unbatched rotation keeps taking one point for all the translations, as on main+ self.assert_close(pose_unb_r * pts5[0], ref_unb_r * pts5[0].expand(5, 3))+ with pytest.raises(RuntimeError):+ _ = pose_unb_r * torch.rand(4, 3, device=device, dtype=dtype)++ for i in range(5):+ self.assert_close(pose_unb_r[i].matrix(), ref_unb_r[i].matrix())+ self.assert_close(pose_unb_r[1:4].matrix(), ref_unb_r[1:4].matrix())+ self.assert_close(pose_unb_r[::2].matrix(), ref_unb_r[::2].matrix())++ # 2. Batched rotation with unbatched translation: Se3(So3.random(3), torch.rand(3))+ r_b3 = So3.random(3, device=device, dtype=dtype)+ t_unb = torch.rand(3, device=device, dtype=dtype)+ pose_unb_t = Se3(r_b3, t_unb)+ ref_unb_t = Se3(r_b3, t_unb.expand(3, 3).clone())+ self.assert_close(pose_unb_t.matrix(), ref_unb_t.matrix())+ self.assert_close(pose_unb_t.log(), ref_unb_t.log())+ self.assert_close(pose_unb_t.adjoint(), ref_unb_t.adjoint())+ self.assert_close(pose_unb_t.inverse().matrix(), ref_unb_t.inverse().matrix())++ other3 = Se3.random(3, device=device, dtype=dtype)+ self.assert_close((pose_unb_t * other3).matrix(), (ref_unb_t * other3).matrix())+ self.assert_close((other3 * pose_unb_t).matrix(), (other3 * ref_unb_t).matrix())++ pts3 = torch.rand(3, 3, device=device, dtype=dtype)+ self.assert_close(pose_unb_t * pts3, ref_unb_t * pts3)+ self.assert_close(pose_unb_t * pts1, ref_unb_t * pts1)+ with pytest.raises(ValueError):+ _ = pose_unb_t * torch.rand(4, 3, device=device, dtype=dtype)++ for i in range(3):+ self.assert_close(pose_unb_t[i].matrix(), ref_unb_t[i].matrix())+ self.assert_close(pose_unb_t[0:2].matrix(), ref_unb_t[0:2].matrix())++ # 3. Both unbatched+ pose_unb_both = Se3(r_unb, t_unb)+ assert pose_unb_both.matrix().shape == (4, 4)+ assert pose_unb_both.log().shape == (6,)+ assert pose_unb_both.adjoint().shape == (6, 6)+ assert pose_unb_both.inverse().matrix().shape == (4, 4)+ t_homo = torch.cat((t_unb, torch.tensor([1.0], device=device, dtype=dtype)))+ self.assert_close(pose_unb_both * t_unb, (pose_unb_both.matrix() @ t_homo)[:3])++ # 4. Singleton batch broadcasting: (1,) and (4,)+ s_sing1 = Se3(So3.random(1, device=device, dtype=dtype), torch.rand(4, 3, device=device, dtype=dtype))+ ref_sing1 = Se3(So3(Quaternion(s_sing1.r.q.data.expand(4, 4))), s_sing1.t.clone())+ self.assert_close(s_sing1.matrix(), ref_sing1.matrix())+ self.assert_close(s_sing1.log(), ref_sing1.log())+ self.assert_close(s_sing1.adjoint(), ref_sing1.adjoint())+ self.assert_close(s_sing1.inverse().matrix(), ref_sing1.inverse().matrix())++ s_sing2 = Se3(So3.random(4, device=device, dtype=dtype), torch.rand(1, 3, device=device, dtype=dtype))+ ref_sing2 = Se3(s_sing2.r, s_sing2.t.expand(4, 3).clone())+ self.assert_close(s_sing2.matrix(), ref_sing2.matrix())+ self.assert_close(s_sing2.log(), ref_sing2.log())+ self.assert_close(s_sing2.adjoint(), ref_sing2.adjoint())+ self.assert_close(s_sing2.inverse().matrix(), ref_sing2.inverse().matrix())++ # 5. Multi-dimensional broadcast batches: (2, 1) rotation and (1, 3) translation+ q_raw = torch.randn(2, 1, 4, device=device, dtype=dtype)+ q_raw = q_raw / q_raw.norm(dim=-1, keepdim=True)+ q_2x1 = Quaternion(q_raw)+ t_1x3 = torch.rand(1, 3, 3, device=device, dtype=dtype)+ s_multi = Se3(q_2x1, t_1x3)+ ref_multi = Se3(So3(Quaternion(q_raw.expand(2, 3, 4))), t_1x3.expand(2, 3, 3).clone())+ self.assert_close(s_multi.matrix(), ref_multi.matrix())+ self.assert_close(s_multi.log(), ref_multi.log())+ self.assert_close(s_multi.adjoint(), ref_multi.adjoint())+ self.assert_close(s_multi.inverse().matrix(), ref_multi.inverse().matrix())+ self.assert_close(s_multi[0].matrix(), ref_multi[0].matrix())+ self.assert_close(s_multi[1].matrix(), ref_multi[1].matrix())+ self.assert_close(s_multi[1:].matrix(), ref_multi[1:].matrix())+ self.assert_close(s_multi[0:2].matrix(), ref_multi[0:2].matrix())+class TestSe3HalfPrecision(BaseTester):# g * p and a * b compute in float32 for float16/bfloat16 inputs and round once to the input dtype, and thediff --git a/tests/geometry/test_quaternion.py b/tests/geometry/test_quaternion.pyindex d232324d7..00d8cfa60 100644--- a/tests/geometry/test_quaternion.py+++ b/tests/geometry/test_quaternion.py@@ -44,6 +44,61 @@ class TestQuaternion(BaseTester):self.assert_close(q.scalar, q_data[..., 0])self.assert_close(q.vec, q_data[..., 1:])+ def test_from_coeffs_integer_and_types(self, device: torch.device, dtype: torch.dtype) -> None:+ # 1. Normal Python float coefficients produce (4,)+ q_float = Quaternion.from_coeffs(1.0, 0.0, 0.0, 0.0)+ assert q_float.data.is_floating_point()+ assert q_float.data.dtype == torch.get_default_dtype()+ assert q_float.data.shape == (4,)+ self.assert_close(q_float.data, torch.tensor([1.0, 0.0, 0.0, 0.0]))++ # 2. Integer-only coefficients produce floating-point data with default dtype+ q_int = Quaternion.from_coeffs(1, 0, 0, 0)+ assert q_int.data.is_floating_point()+ assert q_int.data.dtype == torch.get_default_dtype()+ assert q_int.data.shape == (4,)+ self.assert_close(q_int.data, torch.tensor([1.0, 0.0, 0.0, 0.0]))+ # Operations on integer-constructed quaternion must succeed+ self.assert_close(q_int.matrix(), torch.eye(3))+ self.assert_close(q_int.to_axis_angle(), torch.zeros(3))++ # Mixed float and int coefficients+ q_mixed = Quaternion.from_coeffs(1, 0.0, 0, 0.0)+ assert q_mixed.data.is_floating_point()+ assert q_mixed.data.dtype == torch.get_default_dtype()++ # 3. Complex Python scalar coefficients raise ValueError+ with pytest.raises(ValueError, match="real"):+ Quaternion.from_coeffs(1 + 2j, 0, 0, 0)++ # 4. Complex tensor coefficients raise ValueError+ with pytest.raises(ValueError, match="real"):+ Quaternion.from_coeffs(torch.tensor(1.0 + 1.0j), 0.0, 0.0, 0.0)++ # 5. Four tensor coefficients of shape (1,) preserve original upstream behavior+ t_w = torch.tensor([1.0])+ t_z = torch.tensor([0.0])+ q_1d = Quaternion.from_coeffs(t_w, t_z, t_z, t_z)+ expected_shape = torch.tensor([t_w, t_z, t_z, t_z]).shape+ assert q_1d.data.shape == expected_shape++ # 6. Mixed float32 and float64 tensor coefficients preserve original behavior (promote to float64)+ t_f32 = torch.tensor(1.0, dtype=torch.float32)+ t_f64 = torch.tensor(0.0, dtype=torch.float64)+ q_promoted = Quaternion.from_coeffs(t_f32, t_f64, t_f32, t_f32)+ expected_promoted = torch.tensor([t_f32, t_f64, t_f32, t_f32])+ assert q_promoted.data.dtype == expected_promoted.dtype+ assert q_promoted.data.dtype == torch.float64++ # Default floating-point dtype behavior when default is changed+ orig_default = torch.get_default_dtype()+ try:+ torch.set_default_dtype(torch.float64)+ q_f64_default = Quaternion.from_coeffs(1, 0, 0, 0)+ assert q_f64_default.data.dtype == torch.float64+ finally:+ torch.set_default_dtype(orig_default)+@pytest.mark.parametrize("batch_size", [None, 1, 2, 5])def test_init(self, device, dtype, batch_size):q1 = Quaternion.identity(batch_size, device, dtype)@@ -757,6 +812,40 @@ class TestQuaternionAverage(BaseTester):with pytest.raises(ValueError, match="zero"):average_quaternions(Q, w=torch.zeros(3, device=device, dtype=dtype))+ def test_average_quaternions_weight_shapes(self, device: torch.device, dtype: torch.dtype) -> None:+ # Issue 6482 reproduction: Quaternion.random(6) with torch.ones(6, 1)+ q6 = Quaternion.random(6, device=device, dtype=dtype)+ w6_2d = torch.ones(6, 1, device=device, dtype=dtype)+ w6_1d = torch.ones(6, device=device, dtype=dtype)+ out6_2d = average_quaternions(q6, w=w6_2d)+ out6_1d = average_quaternions(q6, w=w6_1d)+ self.assert_close(out6_2d.data, out6_1d.data)++ Q = Quaternion.random(3, device=device, dtype=dtype)+ w_1d = torch.tensor([1.0, 2.0, 3.0], device=device, dtype=dtype)+ w_2d = torch.tensor([[1.0], [2.0], [3.0]], device=device, dtype=dtype)++ # (M, 1) weights must match (M,) weights+ out_1d = average_quaternions(Q, w=w_1d)+ out_2d = average_quaternions(Q, w=w_2d)+ self.assert_close(out_1d.data, out_2d.data)++ # Incompatible shapes must raise ValueError mentioning the expected shape+ with pytest.raises(ValueError, match=r"must be \(3,\) or \(3, 1\)"):+ average_quaternions(Q, w=torch.tensor([[1.0, 2.0, 3.0]], device=device, dtype=dtype))++ with pytest.raises(ValueError, match=r"must be \(3,\) or \(3, 1\)"):+ average_quaternions(Q, w=torch.zeros((3, 2), device=device, dtype=dtype))++ with pytest.raises(ValueError, match=r"must be \(3,\) or \(3, 1\)"):+ average_quaternions(Q, w=torch.zeros((3, 1, 1), device=device, dtype=dtype))++ with pytest.raises(ValueError, match=r"must be \(3,\) or \(3, 1\)"):+ average_quaternions(Q, w=torch.zeros((2, 1), device=device, dtype=dtype))++ with pytest.raises(ValueError, match=r"must be \(3,\) or \(3, 1\)"):+ average_quaternions(Q, w=torch.zeros((2,), device=device, dtype=dtype))+def test_member_norm_is_not_a_weight_4974(self, device, dtype):# #4974: the members were used as stored, so a member stored as 3 q counted 9 times (the result was scipy's# Rotation.mean with weights [9, 1]). Reference: scipy 1.18.1 Rotation.from_rotvec(rv).mean().as_rotvec().