π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
fix(geometry): read a (B,) slerp ratio as one ratio per quaternion (#4993)
RitiGrover2178bec5c5bc
diff --git a/changelog.d/4993.fixed.md b/changelog.d/4993.fixed.mdnew file mode 100644index 000000000..7e384c4ce--- /dev/null+++ b/changelog.d/4993.fixed.md@@ -0,0 +1,2 @@+`Quaternion.slerp` now reads a `(B,)` tensor ratio as one ratio per quaternion, like `(B, 1)`. With `B == 3` it+scaled the components of each rotation vector instead and returned a wrong result, and other `B > 1` raised (#4991).diff --git a/kornia/geometry/quaternion.py b/kornia/geometry/quaternion.pyindex 97b928c66..794623acb 100644--- a/kornia/geometry/quaternion.py+++ b/kornia/geometry/quaternion.py@@ -584,7 +584,7 @@ class Quaternion(nn.Module):q4 = r1.sqrt() * (2 * pi * r3).cos()return cls(torch.stack((q1, q2, q3, q4), -1))- def slerp(self, q1: "Quaternion", t: float) -> "Quaternion":+ def slerp(self, q1: "Quaternion", t: Union[float, torch.Tensor]) -> "Quaternion":"""Return a unit quaternion spherically interpolated between quaternions self.q and q1.The interpolation follows the shorter arc between the two rotations, whatever the signs of the stored@@ -599,7 +599,8 @@ class Quaternion(nn.Module):Args:q1: second quaternion to be interpolated between.t: interpolation ratio, ``0`` at ``self`` and ``1`` at ``q1``. It is not validated: values outside- ``[0, 1]`` extrapolate along the same arc. A per-batch ratio has shape :math:`(B, 1)`.+ ``[0, 1]`` extrapolate along the same arc. A per-batch ratio has shape :math:`(B,)`, like+ ``self.w``, or :math:`(B, 1)`.Example:>>> q0 = Quaternion.identity()@@ -613,6 +614,10 @@ class Quaternion(nn.Module):# q0 * exp(t * log(q0^-1 q1)): the principal log of the relative rotation selects the shorter arc, and both# conversions keep a finite gradient at the identity (q0 == q1).rel = quaternion_to_axis_angle((q0.inv() * q1).data)+ if isinstance(t, torch.Tensor) and t.dim() > 0 and t.dim() == rel.dim() - 1:+ # One ratio per quaternion, of the shape of ``w``: scale each rotation vector, not its components. A 0-d+ # ratio is left alone: it multiplies as a scalar, whatever its device and dtype, and would not with an axis.+ t = t[..., None]return q0 * Quaternion(axis_angle_to_quaternion(t * rel))def norm(self, keepdim: bool = False) -> torch.Tensor:diff --git a/tests/geometry/test_quaternion.py b/tests/geometry/test_quaternion.pyindex 6892932fa..8136c5490 100644--- a/tests/geometry/test_quaternion.py+++ b/tests/geometry/test_quaternion.py@@ -414,6 +414,32 @@ class TestQuaternion(BaseTester):assert torch.isfinite(q0.grad).all()assert torch.isfinite(q1.grad).all()+ @pytest.mark.parametrize("batch_size", [1, 2, 3, 4])+ def test_slerp_per_batch_ratio_4991(self, device, dtype, batch_size):+ # #4991: a (B,) ratio is one ratio per quaternion, like a (B, 1) one. With B == 3 it used to scale the+ # x, y and z components of every rotation vector instead, and other B > 1 raised.+ torch.manual_seed(0)+ q0 = Quaternion(torch.nn.functional.normalize(torch.randn(batch_size, 4, device=device, dtype=dtype), dim=-1))+ q1 = Quaternion(torch.nn.functional.normalize(torch.randn(batch_size, 4, device=device, dtype=dtype), dim=-1))+ t = torch.linspace(0.1, 0.9, batch_size, device=device, dtype=dtype)+ expected = torch.cat([q0[i : i + 1].slerp(q1[i : i + 1], float(t[i])).data for i in range(batch_size)])+ self.assert_close(q0.slerp(q1, t).data, expected)+ self.assert_close(q0.slerp(q1, t[:, None]).data, expected)++ @pytest.mark.parametrize("batch_size", [None, 2])+ def test_slerp_scalar_tensor_ratio(self, device, dtype, batch_size):+ # A 0-d tensor ratio is a scalar, like a float, also on another device or in another dtype: giving it a+ # trailing axis for #4991 made it a (1,) tensor, which an unbatched quaternion then refused.+ q0 = Quaternion.identity(batch_size, device=device, dtype=dtype)+ q1 = Quaternion(torch.tensor([1.0, 0.5, 0.0, 0.0], device=device, dtype=dtype))+ if batch_size is not None:+ q1 = Quaternion(q1.data.repeat(batch_size, 1))+ expected = q0.slerp(q1, 0.3).data+ for t in (torch.tensor(0.3, device=device, dtype=dtype), torch.tensor(0.3, dtype=torch.float64)):+ out = q0.slerp(q1, t).data+ assert out.dtype == dtype+ self.assert_close(out, expected)+def test_slerp_gradcheck(self, device):q0 = Quaternion.from_axis_angle(torch.tensor([[0.3, 0.2, -0.1]], device=device, dtype=torch.float64)).dataq1 = Quaternion.from_axis_angle(torch.tensor([[0.5, 0.1, 0.15]], device=device, dtype=torch.float64)).data