π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
fix(geometry): compose an unbatched So3, Se3 or Quaternion with a batch (#6490)
Parman Mohammadalizadeh4fdbadf0828e
diff --git a/changelog.d/6490.fixed.md b/changelog.d/6490.fixed.mdnew file mode 100644index 000000000..da400e144--- /dev/null+++ b/changelog.d/6490.fixed.md@@ -0,0 +1 @@+`Quaternion * Quaternion`, `So3 * So3` and `Se3 * Se3` now compose an unbatched element with a batched one and return the batched result, as `So2` and `Se2` do. They used to raise in `torch.linalg.cross`. The same holds for an unbatched `Quaternion` times a tensor of scalars. Batch shapes that cannot be broadcast, such as `(3,)` and `(2,)`, raise a `ValueError` that names both shapes.diff --git a/kornia/geometry/quaternion.py b/kornia/geometry/quaternion.pyindex d6c215d83..c5a43f69e 100644--- a/kornia/geometry/quaternion.py+++ b/kornia/geometry/quaternion.py@@ -238,36 +238,13 @@ class Quaternion(nn.Module):return Quaternion(result_data)def __mul__(self, right: Union["Quaternion", torch.Tensor, float]) -> "Quaternion":- # If right is a Quaternion, do quaternion multiplicationif isinstance(right, Quaternion):- new_real = self.real * right.real - batched_dot_product(self.vec, right.vec)- new_vec = (- self.real[..., None] * right.vec- + right.real[..., None] * self.vec- + torch.linalg.cross(self.vec, right.vec, dim=-1)- )- return Quaternion(torch.cat((new_real[..., None], new_vec), -1))-- # If right is a scalar/torch.Tensor, convert to scalar quaternion and multiply- right_quat = self._to_scalar_quaternion(right)- new_real = self.real * right_quat.real - batched_dot_product(self.vec, right_quat.vec)- new_vec = (- self.real[..., None] * right_quat.vec- + right_quat.real[..., None] * self.vec- + torch.linalg.cross(self.vec, right_quat.vec, dim=-1)- )- return Quaternion(torch.cat((new_real[..., None], new_vec), -1))+ return _hamilton_product(self, right)+ return _hamilton_product(self, self._to_scalar_quaternion(right))def __rmul__(self, left: Union[torch.Tensor, float]) -> "Quaternion":"""Right multiplication (left * self) where left is a scalar or torch.Tensor."""- left_quat = self._to_scalar_quaternion(left)- new_real = left_quat.real * self.real - batched_dot_product(left_quat.vec, self.vec)- new_vec = (- left_quat.real[..., None] * self.vec- + self.real[..., None] * left_quat.vec- + torch.linalg.cross(left_quat.vec, self.vec, dim=-1)- )- return Quaternion(torch.cat((new_real[..., None], new_vec), -1))+ return _hamilton_product(self._to_scalar_quaternion(left), self)def __div__(self, right: Union[torch.Tensor, "Quaternion", float]) -> "Quaternion":if isinstance(right, Quaternion):@@ -718,6 +695,27 @@ class Quaternion(nn.Module):return batched_dot_product(self.vec, self.vec) + self.real**2+def _hamilton_product(left: "Quaternion", right: "Quaternion") -> "Quaternion":+ """Return ``left * right``, broadcasting an unbatched operand, or batch shapes of equal rank, against the other."""+ left_batch, right_batch = left.data.shape[:-1], right.data.shape[:-1]+ shape: Optional[torch.Size] = None+ if len(left_batch) == 0 or len(right_batch) == 0 or len(left_batch) == len(right_batch):+ try:+ shape = torch.broadcast_shapes(left.data.shape, right.data.shape)+ except RuntimeError:+ shape = None+ if shape is None:+ raise ValueError(+ f"Cannot multiply quaternions of batch shapes {tuple(left_batch)} and {tuple(right_batch)}. One must be "+ "unbatched, or both must have the same number of batch axes, each equal or of size 1."+ )+ a, b = left.data.expand(shape), right.data.expand(shape)+ a_real, a_vec, b_real, b_vec = a[..., 0], a[..., 1:], b[..., 0], b[..., 1:]+ new_real = a_real * b_real - batched_dot_product(a_vec, b_vec)+ new_vec = a_real[..., None] * b_vec + b_real[..., None] * a_vec + torch.linalg.cross(a_vec, b_vec, dim=-1)+ return Quaternion(torch.cat((new_real[..., None], new_vec), -1))++def average_quaternions(Q: "Quaternion", w: Optional[torch.Tensor] = None) -> "Quaternion":r"""Compute (weighted) average of multiple quaternions.diff --git a/tests/geometry/liegroup/test_se3.py b/tests/geometry/liegroup/test_se3.pyindex 12e472126..8cbb270c5 100644--- a/tests/geometry/liegroup/test_se3.py+++ b/tests/geometry/liegroup/test_se3.py@@ -253,6 +253,19 @@ class TestSe3(BaseTester):self.assert_close(s4s4inv.r.q.data, so3_expected.q.data)self.assert_close(s4s4inv.t, zeros_vec)+ @pytest.mark.parametrize(("left_batch", "right_batch"), [(None, 3), (3, None)])+ def test_mul_unbatched_with_batched(self, device, dtype, left_batch, right_batch):+ # #6481: composing an unbatched Se3 with a batch used to raise in torch.linalg.cross+ s1 = self._make_rand_se3d(device, dtype, left_batch)+ s2 = self._make_rand_se3d(device, dtype, right_batch)+ out = s1 * s2+ assert out.t.shape == (3, 3)+ self.assert_close(out.matrix(), s1.matrix() @ s2.matrix())++ def test_mul_mismatched_batches_raise(self, device, dtype):+ with pytest.raises(ValueError, match="Cannot multiply quaternions of batch shapes"):+ Se3.random(3, device, dtype) * Se3.random(2, device, dtype)+@pytest.mark.parametrize("batch_size", [None, 1, 2, 5])def test_exp(self, device, dtype, batch_size):omega = torch.zeros(3, device=device, dtype=dtype)diff --git a/tests/geometry/liegroup/test_so3.py b/tests/geometry/liegroup/test_so3.pyindex 51c837f3b..40f772223 100644--- a/tests/geometry/liegroup/test_so3.py+++ b/tests/geometry/liegroup/test_so3.py@@ -334,6 +334,19 @@ class TestSo3(BaseTester):self.assert_close((s2 * s2.inverse()).q.data, s1.q.data)self.assert_close((s1 * t), t)+ @pytest.mark.parametrize(("left_batch", "right_batch"), [(None, 3), (3, None)])+ def test_mul_unbatched_with_batched(self, device, dtype, left_batch, right_batch):+ # #6481: composing an unbatched So3 with a batch used to raise in torch.linalg.cross+ s1 = So3(Quaternion.random(left_batch, device, dtype))+ s2 = So3(Quaternion.random(right_batch, device, dtype))+ out = s1 * s2+ assert out.q.shape == (3, 4)+ self.assert_close(out.matrix(), s1.matrix() @ s2.matrix())++ def test_mul_mismatched_batches_raise(self, device, dtype):+ with pytest.raises(ValueError, match="Cannot multiply quaternions of batch shapes"):+ So3.random(3, device, dtype) * So3.random(2, device, dtype)+@pytest.mark.parametrize("batch_size", [None, 1, 2, 5])def test_unit_norm(self, device, dtype, batch_size):q1 = Quaternion.random(batch_size, device, dtype)diff --git a/tests/geometry/test_quaternion.py b/tests/geometry/test_quaternion.pyindex 3160ad1f9..ce6982f2d 100644--- a/tests/geometry/test_quaternion.py+++ b/tests/geometry/test_quaternion.py@@ -317,6 +317,30 @@ class TestQuaternion(BaseTester):# The quaternion's parameter should have gradientsassert q.data.grad is not None+ @pytest.mark.parametrize(("left_batch", "right_batch"), [(None, 3), (3, None), (1, 3), (3, 1)])+ def test_mul_broadcasts_an_unbatched_or_size_one_batch(self, device, dtype, left_batch, right_batch):+ # #6481: the Hamilton product used to raise in torch.linalg.cross when one operand was unbatched+ q1 = Quaternion.random(left_batch, device, dtype)+ q2 = Quaternion.random(right_batch, device, dtype)+ expected = torch.stack(+ [(Quaternion(a) * Quaternion(b)).data for a, b in zip(*torch.broadcast_tensors(q1.data, q2.data))]+ )+ self.assert_close((q1 * q2).data, expected)++ def test_mul_unbatched_by_a_tensor_of_scalars(self, device, dtype):+ q = Quaternion.random(None, device, dtype)+ s = torch.tensor([1.0, 2.0, -3.0], device=device, dtype=dtype)+ expected = s[:, None] * q.data+ self.assert_close((q * s).data, expected)+ self.assert_close((s * q).data, expected)++ @pytest.mark.parametrize(("left_shape", "right_shape"), [((3, 4), (2, 4)), ((2, 3, 4), (3, 4))])+ def test_mul_incompatible_batches_raise(self, device, dtype, left_shape, right_shape):+ q1 = Quaternion(torch.rand(left_shape, device=device, dtype=dtype))+ q2 = Quaternion(torch.rand(right_shape, device=device, dtype=dtype))+ with pytest.raises(ValueError, match="Cannot multiply quaternions of batch shapes"):+ q1 * q2+@pytest.mark.parametrize("batch_size", [None, 1, 2, 5])def test_inverse(self, device, dtype, batch_size):q1 = Quaternion.random(batch_size, device, dtype)