Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

Fix quaternion scalar arithmetic gradient issues (Issue #3101) (#3334)

Meggison Oritsemisan764ac7b9d5ac
diff --git a/kornia/geometry/liegroup/se3.py b/kornia/geometry/liegroup/se3.py
index 1643c02d4..19d116911 100644
--- a/kornia/geometry/liegroup/se3.py
+++ b/kornia/geometry/liegroup/se3.py
@@ -53,8 +53,7 @@ class Se3(Module):
>>> q = Quaternion.identity()
>>> s = Se3(q, torch.ones(3))
>>> s.r
- Parameter containing:
- tensor([1., 0., 0., 0.], requires_grad=True)
+ tensor([1., 0., 0., 0.])
>>> s.t
Parameter containing:
tensor([1., 1., 1.], requires_grad=True)
@@ -75,8 +74,7 @@ class Se3(Module):
>>> q = Quaternion.identity(batch_size=1)
>>> s = Se3(q, torch.ones((1, 3)))
>>> s.r
- Parameter containing:
- tensor([[1., 0., 0., 0.]], requires_grad=True)
+ tensor([[1., 0., 0., 0.]])
>>> s.t
Parameter containing:
tensor([[1., 1., 1.]], requires_grad=True)
@@ -174,8 +172,7 @@ class Se3(Module):
>>> v = torch.zeros((1, 6))
>>> s = Se3.exp(v)
>>> s.r
- Parameter containing:
- tensor([[1., 0., 0., 0.]], requires_grad=True)
+ tensor([[1., 0., 0., 0.]])
>>> s.t
Parameter containing:
tensor([[0., 0., 0.]], requires_grad=True)
@@ -203,7 +200,7 @@ class Se3(Module):
>>> from kornia.geometry.quaternion import Quaternion
>>> q = Quaternion.identity()
>>> Se3(q, torch.zeros(3)).log()
- tensor([0., 0., 0., 0., 0., 0.], grad_fn=<CatBackward0>)
+ tensor([0., 0., 0., 0., 0., 0.])
"""
omega = self.r.log()
@@ -278,8 +275,7 @@ class Se3(Module):
Example:
>>> s = Se3.identity()
>>> s.r
- Parameter containing:
- tensor([1., 0., 0., 0.], requires_grad=True)
+ tensor([1., 0., 0., 0.])
>>> s.t
x: 0.0
y: 0.0
@@ -301,7 +297,7 @@ class Se3(Module):
tensor([[1., 0., 0., 1.],
[0., 1., 0., 1.],
[0., 0., 1., 1.],
- [0., 0., 0., 1.]], grad_fn=<CopySlices>)
+ [0., 0., 0., 1.]])
"""
rt = concatenate((self.r.matrix(), self.t.data[..., None]), -1)
@@ -319,8 +315,7 @@ class Se3(Module):
Example:
>>> s = Se3.from_matrix(torch.eye(4))
>>> s.r
- Parameter containing:
- tensor([1., 0., 0., 0.], requires_grad=True)
+ tensor([1., 0., 0., 0.])
>>> s.t
Parameter containing:
tensor([0., 0., 0.], requires_grad=True)
@@ -342,8 +337,7 @@ class Se3(Module):
>>> qxyz = torch.tensor([1., 2., 3., 0., 0., 0., 1.])
>>> s = Se3.from_qxyz(qxyz)
>>> s.r
- Parameter containing:
- tensor([1., 2., 3., 0.], requires_grad=True)
+ tensor([1., 2., 3., 0.])
>>> s.t
x: 0.0
y: 0.0
@@ -361,8 +355,7 @@ class Se3(Module):
>>> s = Se3(So3.identity(), torch.ones(3))
>>> s_inv = s.inverse()
>>> s_inv.r
- Parameter containing:
- tensor([1., -0., -0., -0.], requires_grad=True)
+ tensor([1., -0., -0., -0.])
>>> s_inv.t
Parameter containing:
tensor([-1., -1., -1.], requires_grad=True)
@@ -493,7 +486,7 @@ class Se3(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.]], grad_fn=<CatBackward0>)
+ [0., 0., 0., 0., 0., 1.]])
"""
R = self.so3.matrix()
diff --git a/kornia/geometry/liegroup/so3.py b/kornia/geometry/liegroup/so3.py
index e80df3b25..99166e0f4 100644
--- a/kornia/geometry/liegroup/so3.py
+++ b/kornia/geometry/liegroup/so3.py
@@ -44,8 +44,7 @@ class So3(Module):
>>> q = Quaternion.identity()
>>> s = So3(q)
>>> s.q
- Parameter containing:
- tensor([1., 0., 0., 0.], requires_grad=True)
+ tensor([1., 0., 0., 0.])
"""
@@ -61,9 +60,8 @@ class So3(Module):
>>> data = torch.ones((2, 4))
>>> q = Quaternion(data)
>>> So3(q)
- Parameter containing:
tensor([[1., 1., 1., 1.],
- [1., 1., 1., 1.]], requires_grad=True)
+ [1., 1., 1., 1.]])
"""
super().__init__()
@@ -119,9 +117,8 @@ class So3(Module):
>>> v = torch.zeros((2, 3))
>>> s = So3.exp(v)
>>> s
- Parameter containing:
tensor([[1., 0., 0., 0.],
- [1., 0., 0., 0.]], requires_grad=True)
+ [1., 0., 0., 0.]])
"""
# KORNIA_CHECK_SHAPE(v, ["B", "3"]) # FIXME: resolve shape bugs. @edgarriba
@@ -145,7 +142,7 @@ class So3(Module):
>>> q = Quaternion(data)
>>> So3(q).log()
tensor([[0., 0., 0.],
- [0., 0., 0.]], grad_fn=<WhereBackward0>)
+ [0., 0., 0.]])
"""
theta = batched_dot_product(self.q.vec, self.q.vec).sqrt()
@@ -224,7 +221,7 @@ class So3(Module):
>>> m
tensor([[1., 0., 0.],
[0., 1., 0.],
- [0., 0., 1.]], grad_fn=<StackBackward0>)
+ [0., 0., 1.]])
"""
w = self.q.w[..., None]
@@ -254,8 +251,7 @@ class So3(Module):
>>> m = torch.eye(3)
>>> s = So3.from_matrix(m)
>>> s
- Parameter containing:
- tensor([1., 0., 0., 0.], requires_grad=True)
+ tensor([1., 0., 0., 0.])
"""
return cls(Quaternion.from_matrix(matrix))
@@ -271,8 +267,7 @@ class So3(Module):
>>> q = torch.tensor([1., 0., 0., 0.])
>>> s = So3.from_wxyz(q)
>>> s
- Parameter containing:
- tensor([1., 0., 0., 0.], requires_grad=True)
+ tensor([1., 0., 0., 0.])
"""
# KORNIA_CHECK_SHAPE(wxyz, ["B", "4"]) # FIXME: resolve shape bugs. @edgarriba
@@ -292,14 +287,12 @@ class So3(Module):
Example:
>>> s = So3.identity()
>>> s
- Parameter containing:
- tensor([1., 0., 0., 0.], requires_grad=True)
+ tensor([1., 0., 0., 0.])
>>> s = So3.identity(batch_size=2)
>>> s
- Parameter containing:
tensor([[1., 0., 0., 0.],
- [1., 0., 0., 0.]], requires_grad=True)
+ [1., 0., 0., 0.]])
"""
return cls(Quaternion.identity(batch_size, device, dtype))
@@ -310,8 +303,7 @@ class So3(Module):
Example:
>>> s = So3.identity()
>>> s.inverse()
- Parameter containing:
- tensor([1., -0., -0., -0.], requires_grad=True)
+ tensor([1., -0., -0., -0.])
"""
return So3(self.q.conj())
@@ -375,7 +367,7 @@ class So3(Module):
>>> s.adjoint()
tensor([[1., 0., 0.],
[0., 1., 0.],
- [0., 0., 1.]], grad_fn=<StackBackward0>)
+ [0., 0., 1.]])
"""
return self.matrix()
diff --git a/kornia/geometry/pose.py b/kornia/geometry/pose.py
index 71a4b1e68..785b788f2 100644
--- a/kornia/geometry/pose.py
+++ b/kornia/geometry/pose.py
@@ -46,8 +46,7 @@ class NamedPose:
Example:
>>> b_from_a = NamedPose(Se3.identity(), frame_src="frame_a", frame_dst="frame_b")
>>> b_from_a
- NamedPose(dst_from_src=rotation: Parameter containing:
- tensor([1., 0., 0., 0.], requires_grad=True)
+ NamedPose(dst_from_src=rotation: tensor([1., 0., 0., 0.])
translation: x: 0.0
y: 0.0
z: 0.0,
@@ -87,8 +86,7 @@ class NamedPose:
>>> b_from_a = NamedPose(Se3.identity(), frame_src="frame_a", frame_dst="frame_b")
>>> c_from_b = NamedPose(Se3.identity(), frame_src="frame_b", frame_dst="frame_c")
>>> c_from_b * b_from_a
- NamedPose(dst_from_src=rotation: Parameter containing:
- tensor([1., 0., 0., 0.], requires_grad=True)
+ NamedPose(dst_from_src=rotation: tensor([1., 0., 0., 0.])
translation: x: 0.0
y: 0.0
z: 0.0,
@@ -153,8 +151,7 @@ class NamedPose:
>>> b_from_a_trans = torch.tensor([1., 2., 3.])
>>> b_from_a = NamedPose.from_rt(b_from_a_rot, b_from_a_trans, frame_src="frame_a", frame_dst="frame_b")
>>> b_from_a
- NamedPose(dst_from_src=rotation: Parameter containing:
- tensor([1., 0., 0., 0.], requires_grad=True)
+ NamedPose(dst_from_src=rotation: tensor([1., 0., 0., 0.])
translation: Parameter containing:
tensor([1., 2., 3.], requires_grad=True),
frame_src: frame_a -> frame_dst: frame_b)
@@ -196,8 +193,7 @@ class NamedPose:
>>> b_from_a_matrix = Se3.identity().matrix()
>>> b_from_a = NamedPose.from_matrix(b_from_a_matrix, frame_src="frame_a", frame_dst="frame_b")
>>> b_from_a
- NamedPose(dst_from_src=rotation: Parameter containing:
- tensor([1., 0., 0., 0.], requires_grad=True)
+ NamedPose(dst_from_src=rotation: tensor([1., 0., 0., 0.])
translation: Parameter containing:
tensor([0., 0., 0.], requires_grad=True),
frame_src: frame_a -> frame_dst: frame_b)
@@ -220,8 +216,7 @@ class NamedPose:
Example:
>>> b_from_a = NamedPose(Se3.identity(), frame_src="frame_a", frame_dst="frame_b")
>>> b_from_a.inverse()
- NamedPose(dst_from_src=rotation: Parameter containing:
- tensor([1., -0., -0., -0.], requires_grad=True)
+ NamedPose(dst_from_src=rotation: tensor([1., -0., -0., -0.])
translation: x: 0.0
y: 0.0
z: 0.0,
@@ -242,7 +237,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.], grad_fn=<AddBackward0>)
+ tensor([1., 2., 3.])
"""
return self._dst_from_src * points_in_src
diff --git a/kornia/geometry/quaternion.py b/kornia/geometry/quaternion.py
index 2e67fc1ca..dd7530ad6 100644
--- a/kornia/geometry/quaternion.py
+++ b/kornia/geometry/quaternion.py
@@ -20,7 +20,7 @@
# https://github.com/KieranWynn/pyquaternion/blob/master/pyquaternion/quaternion.py
# https://gitlab.com/libeigen/eigen/-/blob/master/Eigen/src/Geometry/Quaternion.h
from math import pi
-from typing import Optional, Tuple, Union
+from typing import Any, Optional, Tuple, Union
import torch
@@ -60,37 +60,94 @@ class Quaternion(Module):
Example:
>>> q = Quaternion.identity(batch_size=4)
>>> q.data
- Parameter containing:
tensor([[1., 0., 0., 0.],
[1., 0., 0., 0.],
[1., 0., 0., 0.],
- [1., 0., 0., 0.]], requires_grad=True)
+ [1., 0., 0., 0.]])
>>> q.real
- tensor([1., 1., 1., 1.], grad_fn=<SelectBackward0>)
+ tensor([1., 1., 1., 1.])
>>> q.vec
tensor([[0., 0., 0.],
[0., 0., 0.],
[0., 0., 0.],
- [0., 0., 0.]], grad_fn=<SliceBackward0>)
+ [0., 0., 0.]])
"""
- def __init__(self, data: Tensor) -> None:
- """Construct the base class.
+ _data: Union[Tensor, Parameter]
+
+ def __init__(self, data: Union[Tensor, Parameter]) -> None:
+ """Construct a quaternion from tensor or parameter data.
Args:
- data: tensor containing the quaternion data with the sape of :math:`(B, 4)`.
+ data: tensor or parameter containing the quaternion data with the shape of :math:`(B, 4)`.
Example:
- >>> data = torch.rand(2, 4)
- >>> q = Quaternion(data)
- >>> q.shape
- (2, 4)
+ >>> # Create with tensor (no gradients tracked by default)
+ >>> data = torch.tensor([1., 0., 0., 0.])
+ >>> q1 = Quaternion(data)
+ >>> # Create with parameter (gradients tracked)
+ >>> param_data = torch.nn.Parameter(torch.tensor([1., 0., 0., 0.]))
+ >>> q2 = Quaternion(param_data)
"""
super().__init__()
+ if not isinstance(data, (Tensor, Parameter)):
+ raise TypeError(f"Expected Tensor or Parameter, got {type(data)}")
# KORNIA_CHECK_SHAPE(data, ["B", "4"]) # FIXME: resolve shape bugs. @edgarriba
- self._data = Parameter(data)
+ self._data = data
+
+ def to(self, *args: Any, **kwargs: Any) -> "Quaternion":
+ """Move and/or cast the quaternion data.
+
+ Args:
+ *args: Arguments to pass to tensor.to()
+ **kwargs: Keyword arguments to pass to tensor.to()
+
+ Returns:
+ A new Quaternion with converted data.
+ """
+ return Quaternion(self._data.to(*args, **kwargs))
+
+ def _to_scalar_quaternion(self, value: Union[Tensor, float]) -> "Quaternion":
+ """Convert a scalar, tensor, or numeric value to a scalar quaternion.
+
+ A scalar quaternion has the form [real, 0, 0, 0] where real is the input value.
+
+ Args:
+ value: The scalar, tensor, or numeric value to convert.
+
+ Returns:
+ A Quaternion object representing the scalar quaternion.
+ """
+ if isinstance(value, (int, float)):
+ value = torch.tensor(value, device=self.data.device, dtype=self.data.dtype)
+ elif isinstance(value, torch.Tensor):
+ value = value.to(device=self.data.device, dtype=self.data.dtype)
+
+ # Broadcast value to match the shape of self.real
+ try:
+ target_shape = torch.broadcast_shapes(self.real.shape, value.shape)
+ except RuntimeError as e:
+ raise ValueError(f"Cannot broadcast shapes {self.real.shape} and {value.shape}") from e
+
+ broadcasted = self.real.expand(target_shape) + value.expand(target_shape)
+ # Create scalar quaternion: [value, 0, 0, 0]
+ # Expand value to match the broadcasted shape, then add quaternion dimension
+ if value.dim() == 0: # scalar
+ # Expand to match the broadcasted shape
+ expanded_value = value.expand_as(broadcasted)
+ else:
+ # Use broadcasting to get the right shape
+ expanded_value = torch.broadcast_to(value, broadcasted.shape)
+
+ # Create zeros for the imaginary part
+ zeros = torch.zeros_like(expanded_value).unsqueeze(-1).expand(*expanded_value.shape, 3)
+
+ # Stack real and imaginary parts: [real, 0, 0, 0]
+ scalar_quat_data = torch.cat([expanded_value.unsqueeze(-1), zeros], dim=-1)
+
+ return Quaternion(scalar_quat_data)
def __repr__(self) -> str:
return f"{self.data}"
@@ -104,66 +161,133 @@ class Quaternion(Module):
Example:
>>> q = Quaternion.identity()
>>> -q.data
- tensor([-1., -0., -0., -0.], grad_fn=<NegBackward0>)
+ tensor([-1., -0., -0., -0.])
"""
return Quaternion(-self.data)
- def __add__(self, right: "Quaternion") -> "Quaternion":
- """Add a given quaternion.
+ def __add__(self, right: Union["Quaternion", Tensor, float]) -> "Quaternion":
+ """Add a given quaternion, scalar, or tensor.
Args:
- right: the quaternion to add.
+ right: the quaternion, scalar, or tensor to add.
Example:
>>> q1 = Quaternion.identity()
>>> q2 = Quaternion(tensor([2., 0., 1., 1.]))
>>> q3 = q1 + q2
>>> q3.data
- Parameter containing:
- tensor([3., 0., 1., 1.], requires_grad=True)
+ tensor([3., 0., 1., 1.])
"""
- KORNIA_CHECK_TYPE(right, Quaternion)
- return Quaternion(self.data + right.data)
+ if isinstance(right, Quaternion):
+ return Quaternion(self.data + right.data)
+ else:
+ right_quat = self._to_scalar_quaternion(right)
+ return Quaternion(self.data + right_quat.data)
- def __sub__(self, right: "Quaternion") -> "Quaternion":
- """Subtract a given quaternion.
+ def __sub__(self, right: Union["Quaternion", Tensor, float]) -> "Quaternion":
+ """Subtract a given quaternion, scalar, or tensor.
Args:
- right: the quaternion to subtract.
+ right: the quaternion, scalar, or tensor to subtract.
Example:
>>> q1 = Quaternion(tensor([2., 0., 1., 1.]))
>>> q2 = Quaternion.identity()
>>> q3 = q1 - q2
>>> q3.data
- Parameter containing:
- tensor([1., 0., 1., 1.], requires_grad=True)
+ tensor([1., 0., 1., 1.])
"""
- KORNIA_CHECK_TYPE(right, Quaternion)
- return Quaternion(self.data - right.data)
-
- def __mul__(self, right: "Quaternion") -> "Quaternion":
- KORNIA_CHECK_TYPE(right, Quaternion)
- new_real = self.real * right.real - batched_dot_product(self.vec, right.vec)
+ if isinstance(right, Quaternion):
+ return Quaternion(self.data - right.data)
+ else:
+ right_quat = self._to_scalar_quaternion(right)
+ # For scalar operations, ensure we return a tensor to preserve gradients
+ result_data = self.data - right_quat.data
+ if isinstance(result_data, Parameter):
+ result_data = result_data.data # Convert to tensor to preserve gradients
+ return Quaternion(result_data)
+
+ def __mul__(self, right: Union["Quaternion", Tensor, float]) -> "Quaternion":
+ # If right is a Quaternion, do quaternion multiplication
+ if 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(concatenate((new_real[..., None], new_vec), -1))
+
+ # If right is a scalar/tensor, convert to scalar quaternion and multiply
+ else:
+ 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(concatenate((new_real[..., None], new_vec), -1))
+
+ def __rmul__(self, left: Union[Tensor, float]) -> "Quaternion":
+ """Right multiplication (left * self) where left is a scalar or 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 = (
- self.real[..., None] * right.vec
- + right.real[..., None] * self.vec
- + torch.linalg.cross(self.vec, right.vec, dim=-1)
+ left_quat.real[..., None] * self.vec
+ + self.real[..., None] * left_quat.vec
+ + torch.linalg.cross(left_quat.vec, self.vec, dim=-1)
)
return Quaternion(concatenate((new_real[..., None], new_vec), -1))
- def __div__(self, right: Union[Tensor, "Quaternion"]) -> "Quaternion":
- if isinstance(right, Tensor):
- return Quaternion(self.data / right[..., None])
- KORNIA_CHECK_TYPE(right, Quaternion)
- return self * right.inv()
-
- def __truediv__(self, right: "Quaternion") -> "Quaternion":
+ def __div__(self, right: Union[Tensor, "Quaternion", float]) -> "Quaternion":
+ if isinstance(right, Quaternion):
+ return self * right.inv()
+ else:
+ # For scalars/tensors, just divide the quaternion data directly
+ if isinstance(right, (int, float)):
+ right_tensor = torch.tensor(right, device=self.data.device, dtype=self.data.dtype)
+ else:
+ right_tensor = right.to(device=self.data.device, dtype=self.data.dtype)
+
+ # For division by scalar, expand to [right, right, right, right] for element-wise division
+ if right_tensor.dim() == 0: # scalar
+ divisor = right_tensor.expand_as(self.data[..., 0]).unsqueeze(-1).expand_as(self.data)
+ else:
+ # Broadcast the tensor to match the quaternion dimensions
+ divisor = right_tensor.unsqueeze(-1).expand_as(self.data)
+
+ # For scalar operations, ensure we return a tensor to preserve gradients
+ result_data = self.data / divisor
+ if isinstance(result_data, Parameter):
+ result_data = result_data.data # Convert to tensor to preserve gradients
+ return Quaternion(result_data)
+
+ def __truediv__(self, right: Union[Tensor, "Quaternion", float]) -> "Quaternion":
return self.__div__(right)
+ def __radd__(self, left: Union[Tensor, float]) -> "Quaternion":
+ """Right addition (left + self) where left is a scalar or tensor."""
+ left_quat = self._to_scalar_quaternion(left)
+ return left_quat + self
+
+ def __rsub__(self, left: Union[Tensor, float]) -> "Quaternion":
+ """Right subtraction (left - self) where left is a scalar or tensor."""
+ left_quat = self._to_scalar_quaternion(left)
+ return left_quat - self
+
+ def __rtruediv__(self, left: Union[Tensor, float]) -> "Quaternion":
+ """Right division (left / self) where left is a scalar or tensor."""
+ left_quat = self._to_scalar_quaternion(left)
+ return left_quat / self
+
+ def __rdiv__(self, left: Union[Tensor, float]) -> "Quaternion":
+ """Right division (left / self) where left is a scalar or tensor."""
+ return self.__rtruediv__(left)
+
def __pow__(self, t: float) -> "Quaternion":
"""Return the power of a quaternion raised to exponent t.
@@ -255,7 +379,7 @@ class Quaternion(Module):
Example:
>>> q = Quaternion.identity()
>>> q.polar_angle
- tensor(0., grad_fn=<AcosBackward0>)
+ tensor(0.)
"""
return (self.scalar / self.norm()).acos()
@@ -269,7 +393,7 @@ class Quaternion(Module):
>>> m
tensor([[1., 0., 0.],
[0., 1., 0.],
- [0., 0., 1.]], grad_fn=<ViewBackward0>)
+ [0., 0., 1.]])
"""
return quaternion_to_rotation_matrix(self.data)
@@ -285,8 +409,7 @@ class Quaternion(Module):
>>> m = torch.eye(3)[None]
>>> q = Quaternion.from_matrix(m)
>>> q.data
- Parameter containing:
- tensor([[1., 0., 0., 0.]], requires_grad=True)
+ tensor([[1., 0., 0., 0.]])
"""
return cls(rotation_matrix_to_quaternion(matrix))
@@ -304,8 +427,7 @@ class Quaternion(Module):
>>> roll, pitch, yaw = tensor(0), tensor(1), tensor(0)
>>> q = Quaternion.from_euler(roll, pitch, yaw)
>>> q.data
- Parameter containing:
- tensor([0.8776, 0.0000, 0.4794, 0.0000], requires_grad=True)
+ tensor([0.8776, 0.0000, 0.4794, 0.0000])
"""
w, x, y, z = quaternion_from_euler(roll=roll, pitch=pitch, yaw=yaw)
@@ -319,11 +441,11 @@ class Quaternion(Module):
>>> q = Quaternion(tensor([2., 0., 1., 1.]))
>>> roll, pitch, yaw = q.to_euler()
>>> roll
- tensor(2.0344, grad_fn=<Atan2Backward0>)
+ tensor(2.0344)
>>> pitch
- tensor(1.5708, grad_fn=<AsinBackward0>)
+ tensor(1.5708)
>>> yaw
- tensor(2.2143, grad_fn=<Atan2Backward0>)
+ tensor(2.2143)
"""
return euler_from_quaternion(self.w, self.x, self.y, self.z)
@@ -339,8 +461,7 @@ class Quaternion(Module):
>>> axis_angle = torch.tensor([[1., 0., 0.]])
>>> q = Quaternion.from_axis_angle(axis_angle)
>>> q.data
- Parameter containing:
- tensor([[0.8776, 0.4794, 0.0000, 0.0000]], requires_grad=True)
+ tensor([[0.8776, 0.4794, 0.0000, 0.0000]])
"""
return cls(axis_angle_to_quaternion(axis_angle))
@@ -352,7 +473,7 @@ class Quaternion(Module):
>>> q = Quaternion.identity()
>>> axis_angle = q.to_axis_angle()
>>> axis_angle
- tensor([0., 0., 0.], grad_fn=<AsStridedBackward0>)
+ tensor([0., 0., 0.])
"""
return quaternion_to_axis_angle(self.data)
@@ -371,8 +492,7 @@ class Quaternion(Module):
Example:
>>> q = Quaternion.identity()
>>> q.data
- Parameter containing:
- tensor([1., 0., 0., 0.], requires_grad=True)
+ tensor([1., 0., 0., 0.])
"""
data = tensor([1.0, 0.0, 0.0, 0.0], device=device, dtype=dtype)
@@ -393,8 +513,7 @@ class Quaternion(Module):
Example:
>>> q = Quaternion.from_coeffs(1., 0., 0., 0.)
>>> q.data
- Parameter containing:
- tensor([1., 0., 0., 0.], requires_grad=True)
+ tensor([1., 0., 0., 0.])
"""
return cls(tensor([w, x, y, z]))
@@ -460,7 +579,7 @@ class Quaternion(Module):
Example:
>>> q = Quaternion.identity()
>>> q.norm()
- tensor(1., grad_fn=<LinalgVectorNormBackward0>)
+ tensor(1.)
"""
# p==2, dim|axis==-1, keepdim
@@ -514,7 +633,7 @@ class Quaternion(Module):
Example:
>>> q = Quaternion.identity()
>>> q.squared_norm()
- tensor(1., grad_fn=<AddBackward0>)
+ tensor(1.)
"""
return batched_dot_product(self.vec, self.vec) + self.real**2
diff --git a/tests/geometry/test_quaternion.py b/tests/geometry/test_quaternion.py
index cea525805..a0be4153d 100644
--- a/tests/geometry/test_quaternion.py
+++ b/tests/geometry/test_quaternion.py
@@ -19,6 +19,7 @@ from typing import Union
import pytest
import torch
+from torch.nn import Parameter
from kornia.geometry.quaternion import Quaternion, average_quaternions
@@ -164,6 +165,26 @@ class TestQuaternion:
self.assert_close((q1**1), q1)
self.assert_close((q1**2), q1)
+ @pytest.mark.parametrize("batch_size", (None, 1, 2, 5))
+ def test_quaternion_scalar_multiplication(self, device, dtype, batch_size):
+ """Test scalar multiplication for issue #3101."""
+ # Create a quaternion with parameters to test gradient flow
+ q_data = torch.tensor([1.0, 0.0, 0.0, 0.0], device=device, dtype=dtype, requires_grad=True)
+ q = Quaternion(Parameter(q_data))
+
+ # This should not raise a TypeError
+ result = q * q * 5
+
+ # Verify the result has proper gradient tracking
+ assert result.data.requires_grad
+
+ # Backward pass should work
+ loss = result.data.sum()
+ loss.backward()
+
+ # The quaternion's parameter should have gradients
+ assert q.data.grad is not None
+
@pytest.mark.parametrize("batch_size", (None, 1, 2, 5))
def test_inverse(self, device, dtype, batch_size):
q1 = Quaternion.random(batch_size, device, dtype)