Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

fix(geometry): So2, Se2 and Se3 reject inputs their methods cannot use at construction (#5925)

Dmytro Mishkin0674172d2eed
diff --git a/changelog.d/5925.breaking.md b/changelog.d/5925.breaking.md
new file mode 100644
index 000000000..a0bb36afb
--- /dev/null
+++ b/changelog.d/5925.breaking.md
@@ -0,0 +1,12 @@
+`So2`, `Se2` and `Se3` now reject at construction the inputs their methods cannot use. `So2(z)` with a real
+floating-point `z` used to construct, and `inverse()`, `adjoint()`, `__getitem__` and `So2 * So2` worked on it while
+`matrix()`, `log()` and `So2 * points` raised torch's "imag is not implemented"; it now raises `TypeCheckError`
+naming `z` and its dtype (build `z` with `torch.complex`). `Se2` / `Se3` with a translation whose dtype differs from
+the rotation's (for example a float64 rotation and a float32 translation) used to construct, and `matrix()`,
+`inverse()`, `__mul__` and `__getitem__` worked on some of them while `log()` (`Se2`) or `inverse()`, `adjoint()` and
+`Se3 * Se3` (`Se3`) raised torch's "expected scalar type" error; they now raise `TypeCheckError`. A complex `Se2` / `Se3` translation and an integer or bool `nn.Parameter` translation, which used to construct, also
+raise `TypeCheckError`. A translation on another device than the rotation, which made `matrix()`, `log()`, `inverse()`,
+`adjoint()` and `*` fail, now raises `DeviceError`. A bfloat16 `Se2` translation beside a complex32, complex64 or complex128 rotation stays accepted, because `.bfloat16()` leaves exactly
+that state, and every `Se2` method now works on it: `log()` used to raise torch's dtype error, and `inverse()` and
+`pose * pose` return a translation of the rotation's real dtype (float32 or float64 as before, but float16 instead of
+float32 for a complex32 rotation, which the new check would reject).
diff --git a/kornia/geometry/liegroup/se2.py b/kornia/geometry/liegroup/se2.py
index ae83d5924..b502163d0 100644
--- a/kornia/geometry/liegroup/se2.py
+++ b/kornia/geometry/liegroup/se2.py
@@ -26,6 +26,7 @@ import torch.nn.functional as F
from torch import nn
from kornia.core.check import KORNIA_CHECK, KORNIA_CHECK_SAME_DEVICES, KORNIA_CHECK_SHAPE, KORNIA_CHECK_TYPE
+from kornia.core.exceptions import DeviceError, TypeCheckError
from kornia.core.utils import register_module_state
from kornia.geometry.liegroup.so2 import So2
from kornia.geometry.liegroup.so3 import _so3_small_angle_coefficients
@@ -46,6 +47,38 @@ def _check_se2_r_t_shape(r: So2, t: torch.Tensor) -> None:
)
+def _check_se2_r_t_dtype_device(r: So2, t: torch.Tensor) -> None:
+ """Reject a translation the rotation's methods cannot combine with: another dtype or another device."""
+ r_dtype = r.z.real.dtype
+ # ``.bfloat16()`` keeps the complex rotation's precision (PyTorch has no complex bfloat16) and casts the
+ # translation, so a bfloat16 translation beside a complex rotation is the module's own converted state.
+ if t.is_complex():
+ raise TypeCheckError(
+ f"Se2 translation must be a real floating-point tensor; got {t.dtype}.",
+ actual_type=t.dtype,
+ )
+ if not t.is_floating_point():
+ # register_module_state keeps an existing nn.Parameter as given, so it cannot reject an integer one
+ raise TypeCheckError(
+ f"Se2 stores 'translation' as module state, which needs a floating-point tensor; got {t.dtype}. "
+ "Cast it first, for example with `.float()`.",
+ actual_type=t.dtype,
+ )
+ if t.dtype not in (r_dtype, torch.bfloat16):
+ raise TypeCheckError(
+ f"Se2 translation must have the dtype of its rotation, {r_dtype} (z is {r.z.dtype}); got {t.dtype}. "
+ "Cast one of them first, for example with `.to(dtype)`.",
+ actual_type=t.dtype,
+ expected_type=r_dtype,
+ )
+ if t.device != r.z.device:
+ raise DeviceError(
+ f"Se2 translation must be on the device of its rotation, {r.z.device}; got {t.device}.",
+ actual_devices=[r.z.device, t.device],
+ expected_device=r.z.device,
+ )
+
+
class Se2(nn.Module):
r"""Base class to represent the Se2 group.
@@ -92,10 +125,16 @@ class Se2(nn.Module):
Args:
rotation: So2 group encompassing a rotation.
translation: translation torch.Tensor with the shape of :math:`(B, 2)`, or a Vector2 wrapping one; the
- tensor is what gets stored.
+ tensor is what gets stored. 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, which
+ is what ``.bfloat16()`` leaves (PyTorch has no complex bfloat16). Every method then reads the
+ translation at the rotation's precision, and ``inverse`` and ``g * g`` return a translation of the
+ rotation's real dtype.
Raises:
- TypeCheckError: if the translation is an integer or bool tensor.
+ TypeCheckError: if the translation is an integer, bool or complex tensor (an ``nn.Parameter`` too), or its
+ dtype differs from the rotation's (``log`` and the other methods cannot combine them).
+ DeviceError: if the translation is on another device than the rotation.
Example:
>>> so2 = So2.identity(1)
@@ -114,6 +153,7 @@ class Se2(nn.Module):
raise TypeError(f"translation type is {type(translation)}")
_t_data = translation.data if isinstance(translation, Vector2) else translation
_check_se2_r_t_shape(rotation, _t_data) # TODO remove
+ _check_se2_r_t_dtype_device(rotation, _t_data)
self._translation: torch.Tensor
self._rotation: So2 = rotation
register_module_state(self, "_translation", _t_data)
@@ -128,7 +168,9 @@ class Se2(nn.Module):
so2 = self.so2
t = self.t
_r = so2 * right.so2
- _t = t + so2 * right.t
+ # 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)
return Se2(_r, _t)
@overload
@@ -250,7 +292,8 @@ 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 @ self.t[..., None]
+ # the translation is read at the rotation's precision, so a bfloat16 translation beside a wider rotation works
+ upsilon = V_inv @ self.t.to(theta.dtype)[..., None]
return torch.stack((upsilon[..., 0, 0], upsilon[..., 1, 0], theta), -1)
@staticmethod
@@ -350,7 +393,8 @@ class Se2(nn.Module):
[0., 0., 1.]]], grad_fn=<CopySlices>)
"""
- rt = torch.cat((self.r.matrix(), self.t[..., None]), -1)
+ r_matrix = self.r.matrix()
+ rt = torch.cat((r_matrix, self.t.to(r_matrix.dtype)[..., None]), -1)
rt_3x3 = F.pad(rt, (0, 0, 0, 1)) # add last row torch.zeros
rt_3x3[..., -1, -1] = 1.0
return rt_3x3
@@ -391,7 +435,8 @@ class Se2(nn.Module):
"""
r_inv: So2 = self.r.inverse()
- return Se2(r_inv, r_inv * (-1 * self.t))
+ # the rotation's real dtype, as in ``__mul__``
+ return Se2(r_inv, (r_inv * (-1 * self.t)).to(r_inv.z.real.dtype))
@classmethod
def random(
diff --git a/kornia/geometry/liegroup/se3.py b/kornia/geometry/liegroup/se3.py
index ee7e91274..b0fef85c3 100644
--- a/kornia/geometry/liegroup/se3.py
+++ b/kornia/geometry/liegroup/se3.py
@@ -26,6 +26,7 @@ import torch.nn.functional as F
from torch import nn
from kornia.core.check import KORNIA_CHECK, KORNIA_CHECK_SAME_DEVICES, KORNIA_CHECK_SHAPE
+from kornia.core.exceptions import DeviceError, TypeCheckError
from kornia.core.utils import register_module_state
from kornia.geometry.liegroup.so3 import So3, _so3_small_angle_coefficients
from kornia.geometry.linalg import batched_dot_product
@@ -33,6 +34,37 @@ from kornia.geometry.quaternion import Quaternion
from kornia.geometry.vector import Vector3
+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
+ q_data = q.data
+ if t.is_complex():
+ raise TypeCheckError(
+ f"Se3 translation must be a real floating-point tensor; got {t.dtype}.",
+ actual_type=t.dtype,
+ )
+ if not t.is_floating_point():
+ # register_module_state keeps an existing nn.Parameter as given, so it cannot reject an integer one
+ raise TypeCheckError(
+ f"Se3 stores 'translation' as module state, which needs a floating-point tensor; got {t.dtype}. "
+ "Cast it first, for example with `.float()`.",
+ actual_type=t.dtype,
+ )
+ if t.dtype != q_data.dtype:
+ raise TypeCheckError(
+ f"Se3 translation must have the dtype of its rotation, {q_data.dtype}; got {t.dtype}. "
+ "Cast one of them first, for example with `.to(dtype)`.",
+ actual_type=t.dtype,
+ expected_type=q_data.dtype,
+ )
+ if t.device != q_data.device:
+ raise DeviceError(
+ f"Se3 translation must be on the device of its rotation, {q_data.device}; got {t.device}.",
+ actual_devices=[q_data.device, t.device],
+ expected_device=q_data.device,
+ )
+
+
class Se3(nn.Module):
r"""Base class to represent the Se3 group.
@@ -76,10 +108,12 @@ class Se3(nn.Module):
rotation: So3 group encompassing a rotation, or a Quaternion to wrap in one; it is stored as given, and
a non-unit quaternion stands for the rotation of its direction.
translation: translation torch.Tensor with the shape of :math:`(B, 3)`, or a Vector3 wrapping one; the
- tensor is what gets stored.
+ tensor is what gets stored. It must have the rotation's dtype and device.
Raises:
- TypeCheckError: if the translation is an integer or bool tensor.
+ TypeCheckError: if the translation is an integer, bool or complex tensor (an ``nn.Parameter`` too), or its
+ dtype 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.
Example:
>>> from kornia.geometry.quaternion import Quaternion
@@ -101,6 +135,7 @@ class Se3(nn.Module):
raise TypeError(f"translation type is {type(translation)}")
_t_data = translation.data if isinstance(translation, Vector3) else translation
KORNIA_CHECK_SHAPE(_t_data, ["*", "3"])
+ _check_se3_r_t_dtype_device(rotation, _t_data)
self._translation: torch.Tensor
self._rotation: So3
register_module_state(self, "_translation", _t_data)
diff --git a/kornia/geometry/liegroup/so2.py b/kornia/geometry/liegroup/so2.py
index bb82644ca..6925c6873 100644
--- a/kornia/geometry/liegroup/so2.py
+++ b/kornia/geometry/liegroup/so2.py
@@ -26,6 +26,7 @@ import torch
from torch import nn
from kornia.core.check import KORNIA_CHECK, KORNIA_CHECK_IS_TENSOR, KORNIA_CHECK_SHAPE
+from kornia.core.exceptions import TypeCheckError
from kornia.core.tensor_wrapper import _unwrap
from kornia.core.utils import is_exporting, register_module_state
from kornia.geometry.vector import Vector2
@@ -75,7 +76,7 @@ class So2(nn.Module):
z: Complex number with the shape of :math:`(B,)` or :math:`()`; :math:`(B, 1)` is read as :math:`(B,)`.
Raises:
- TypeCheckError: if ``z`` is an integer or bool tensor.
+ TypeCheckError: if ``z`` is not a complex tensor (an integer, bool or real floating-point tensor).
Example:
>>> real = torch.tensor(0.6)
@@ -87,6 +88,12 @@ class So2(nn.Module):
"""
super().__init__()
KORNIA_CHECK_IS_TENSOR(z)
+ if not z.is_complex():
+ # Every method reads z.real and z.imag, and a real z (or an integer one) only fails there, inside torch.
+ raise TypeCheckError(
+ f"So2 stores 'z' as a complex tensor; got {z.dtype}. Build it with `torch.complex(real, imag)`.",
+ actual_type=z.dtype,
+ )
# check_so2_z_shape(z)
is_scalar = len(z.shape) == 0
is_flat = KORNIA_CHECK_SHAPE(z, ["B"], raises=False)
diff --git a/tests/geometry/liegroup/test_se2.py b/tests/geometry/liegroup/test_se2.py
index 254ec52b5..ed5ee6745 100644
--- a/tests/geometry/liegroup/test_se2.py
+++ b/tests/geometry/liegroup/test_se2.py
@@ -20,13 +20,19 @@ import math
import pytest
import torch
-from kornia.core.exceptions import BaseError, TypeCheckError
+from kornia.core.exceptions import BaseError, DeviceError, TypeCheckError
from kornia.geometry.liegroup import Se2, So2
+from kornia.geometry.pose import NamedPose
from kornia.geometry.vector import Vector2
from testing.base import DYNAMO_UNAVAILABLE_REASON, BaseTester, dynamo_is_available
+def _complex_dtype(dtype: torch.dtype) -> torch.dtype:
+ """Complex dtype whose real dtype is ``dtype``; bfloat16 has none, and Se2 pairs its rotation with complex64."""
+ return {torch.float16: torch.chalf, torch.float64: torch.cdouble}.get(dtype, torch.cfloat)
+
+
class TestSe2(BaseTester):
def _make_rand_data(self, device, dtype, input_shape):
batch_size = input_shape[0]
@@ -34,7 +40,7 @@ class TestSe2(BaseTester):
return torch.rand(shape, device=device, dtype=dtype)
def test_smoke(self, device, dtype):
- z = torch.rand((2,), dtype=torch.cfloat, device=device)
+ z = torch.rand((2,), dtype=torch.cfloat, device=device).to(_complex_dtype(dtype))
so2 = So2(z)
t = torch.rand((1, 2), device=device, dtype=dtype)
s = Se2(so2, t)
@@ -134,7 +140,7 @@ class TestSe2(BaseTester):
@pytest.mark.parametrize("batch_size", [1, 2, 5])
def test_getitem(self, device, dtype, batch_size):
- z = torch.rand(batch_size, dtype=torch.cfloat, device=device)
+ z = torch.rand(batch_size, dtype=torch.cfloat, device=device).to(_complex_dtype(dtype))
t = torch.rand((batch_size, 2), device=device, dtype=dtype)
s = Se2(So2(z), t)
for i in range(batch_size):
@@ -412,6 +418,123 @@ class TestSe2(BaseTester):
with pytest.raises(TypeCheckError, match=r"Se2 stores 'translation'.*torch.int64"):
Se2(So2.identity(1, device), torch.tensor([[1, 2]], device=device))
+ @pytest.mark.parametrize(
+ "pair",
+ [
+ (torch.float64, torch.float32),
+ (torch.float32, torch.float64),
+ (torch.float32, torch.float16),
+ (torch.float16, torch.float32),
+ ],
+ )
+ def test_mixed_dtype_translation_raises_5913(self, device, pair):
+ # The mix used to construct, then log() raised torch's "expected scalar type Double but found Float".
+ if device.type == "mps" and (torch.float64 in pair or pair[0] == torch.float16):
+ pytest.skip("MPS has no float64 or complex32")
+ r_dtype, t_dtype = pair
+ rotation = So2.identity(1, device, r_dtype)
+ with pytest.raises(
+ TypeCheckError, match=r"Se2 translation must have the dtype of its rotation.*" + str(t_dtype)
+ ):
+ Se2(rotation, torch.zeros(1, 2, device=device, dtype=t_dtype))
+ with pytest.raises(TypeCheckError, match=r"Se2 translation"):
+ Se2(rotation, Vector2(torch.zeros(1, 2, device=device, dtype=t_dtype)))
+ with pytest.raises(TypeCheckError, match=r"Se2 translation"):
+ Se2(So2.identity(None, device, r_dtype), torch.zeros(2, device=device, dtype=t_dtype))
+
+ def test_same_dtype_translation_is_accepted_5913(self, device, dtype):
+ if dtype == torch.bfloat16:
+ pytest.skip("torch.complex has no bfloat16 overload, so So2 cannot be built at all")
+ s = Se2(So2.identity(2, device, dtype), torch.zeros(2, 2, device=device, dtype=dtype))
+ assert s.t.dtype == dtype
+ assert s.r.z.real.dtype == dtype
+
+ @pytest.mark.parametrize("real_dtype", [torch.float16, torch.float32, torch.float64])
+ def test_bfloat16_module_state_is_closed_5913(self, device, real_dtype):
+ # ``.bfloat16()`` keeps the complex rotation (complex32/64/128) and casts the translation (documented in
+ # the class Convention). Every method must keep working on that state: log/matrix/adjoint read the
+ # translation at the rotation's precision, and inverse/pose * pose return a translation of its real dtype.
+ if device.type == "mps" and real_dtype != torch.float32:
+ pytest.skip("MPS supports complex64 only")
+ v = torch.tensor([[0.5, 0.2, 0.3], [0.1, 0.4, -0.2]], device=device, dtype=real_dtype)
+ cdtype = {torch.float16: torch.chalf, torch.float32: torch.cfloat, torch.float64: torch.cdouble}[real_dtype]
+ s = Se2.exp(v).bfloat16()
+ assert s.t.dtype == torch.bfloat16
+ assert s.r.z.dtype == cdtype
+ tol = {"atol": 0.05, "rtol": 0.05}
+ log = s.log()
+ assert log.dtype == real_dtype
+ self.assert_close(log, v, **tol)
+ assert s[0].t.dtype == torch.bfloat16
+ for pose in (s[0], s.inverse(), s * s, s.inverse().inverse(), s * s.inverse()):
+ assert isinstance(pose, Se2)
+ assert pose.r.z.dtype == cdtype
+ # inverse() and pose * pose build a translation of the rotation's real dtype
+ for pose in (s.inverse(), s * s, s * s.inverse()):
+ assert pose.t.dtype == real_dtype
+ assert s.inverse().log().dtype == real_dtype
+ self.assert_close((s * s.inverse()).log(), torch.zeros_like(v), **tol)
+ matrix = s.matrix()
+ assert matrix.dtype == real_dtype
+ self.assert_close((s * s).matrix(), matrix @ matrix, **tol)
+ assert s.adjoint().dtype == real_dtype
+ points = torch.ones(2, 2, device=device, dtype=real_dtype)
+ out = s * points
+ assert out.is_floating_point()
+ expected = (matrix[:, :2, :2] @ points[..., None])[..., 0] + matrix[:, :2, 2]
+ self.assert_close(out.to(real_dtype), expected, **tol)
+ Se2(So2.identity(1, device), torch.zeros(1, 2, device=device, dtype=torch.bfloat16))
+
+ @pytest.mark.skipif(not dynamo_is_available(), reason=DYNAMO_UNAVAILABLE_REASON)
+ def test_dynamo_constructor_checks_5913(self, device, torch_optimizer):
+ def build(real, imag, t):
+ return Se2(So2(torch.complex(real, imag)), t).matrix()
+
+ args = (torch.rand(2, device=device), torch.rand(2, device=device), torch.rand(2, 2, device=device))
+ self.assert_close(torch_optimizer(build, fullgraph=True)(*args), build(*args))
+
+ @pytest.mark.parametrize("cdtype", [torch.cfloat, torch.cdouble])
+ def test_complex_translation_raises_5913(self, device, cdtype):
+ # the translation is a real vector; a complex one used to construct (its imaginary part silently dropped)
+ if device.type == "mps" and cdtype != torch.cfloat:
+ pytest.skip("MPS supports complex64 only")
+ with pytest.raises(TypeCheckError, match=r"Se2 translation must be a real floating-point tensor.*complex"):
+ Se2(So2.identity(1, device), torch.zeros(1, 2, device=device, dtype=cdtype))
+
+ @pytest.mark.parametrize("int_dtype", [torch.int64, torch.bool])
+ def test_integer_parameter_translation_raises_5913(self, device, int_dtype):
+ # register_module_state keeps an existing nn.Parameter as given, so an integer one used to get through
+ translation = torch.nn.Parameter(torch.zeros(1, 2, device=device, dtype=int_dtype), requires_grad=False)
+ with pytest.raises(TypeCheckError, match=r"Se2 stores 'translation'.*" + str(int_dtype)):
+ Se2(So2.identity(1, device), translation)
+
+ def test_translation_on_another_device_raises_5913(self, device):
+ # Rotation and translation on different devices fail in every method (matrix, log, inverse, __mul__);
+ # the meta device stands in for a second accelerator.
+ with pytest.raises(DeviceError, match=r"Se2 translation must be on the device of its rotation"):
+ Se2(So2.identity(1, device), torch.zeros(1, 2, device="meta"))
+
+ def test_internal_constructions_still_build_5913(self, device, dtype):
+ if dtype == torch.bfloat16:
+ pytest.skip("torch.complex has no bfloat16 overload, so So2 cannot be built at all")
+ a = Se2.exp(torch.tensor([[0.5, 0.2, 0.3], [0.1, 0.4, -0.2]], device=device, dtype=dtype))
+ built = [
+ Se2.identity(None, device, dtype),
+ Se2.identity(2, device, dtype),
+ Se2.random(None, device, dtype),
+ Se2.random(2, device, dtype),
+ Se2.from_matrix(a.matrix().detach()),
+ Se2.trans(torch.ones(2, device=device, dtype=dtype), torch.zeros(2, device=device, dtype=dtype)),
+ Se2.trans_x(torch.ones(2, device=device, dtype=dtype)),
+ Se2.trans_y(torch.ones(2, device=device, dtype=dtype)),
+ a[0],
+ a.inverse(),
+ a * a,
+ NamedPose.from_rt(So2.identity(1, device, dtype), torch.zeros(1, 2, device=device, dtype=dtype)).pose,
+ ]
+ assert all(isinstance(s, Se2) for s in built)
+ assert all(s.t.dtype == dtype and s.r.z.real.dtype == dtype for s in built)
+
def test_derived_state_moves_and_serializes(self, device, dtype):
# A group built from a tensor with autograd history keeps that history; its state must
# still be registered so ``state_dict`` and ``.to()`` / ``.double()`` reach it.
diff --git a/tests/geometry/liegroup/test_se3.py b/tests/geometry/liegroup/test_se3.py
index d7cdd0d9f..36048703e 100644
--- a/tests/geometry/liegroup/test_se3.py
+++ b/tests/geometry/liegroup/test_se3.py
@@ -20,13 +20,14 @@ import math
import pytest
import torch
-from kornia.core.exceptions import TypeCheckError
+from kornia.core.exceptions import DeviceError, TypeCheckError
from kornia.geometry.conversions import euler_from_quaternion, rotation_matrix_to_quaternion
from kornia.geometry.liegroup import Se3, So3
+from kornia.geometry.pose import NamedPose
from kornia.geometry.quaternion import Quaternion
from kornia.geometry.vector import Vector3
-from testing.base import BaseTester
+from testing.base import DYNAMO_UNAVAILABLE_REASON, BaseTester, dynamo_is_available
class TestSe3(BaseTester):
@@ -427,6 +428,84 @@ class TestSe3(BaseTester):
with pytest.raises(TypeCheckError, match=r"Se3 stores 'translation'.*torch.int64"):
Se3(Quaternion.identity(1, device), torch.tensor([[1, 2, 3]], device=device))
+ @pytest.mark.parametrize(
+ "pair",
+ [
+ (torch.float64, torch.float32),
+ (torch.float32, torch.float64),
+ (torch.float32, torch.float16),
+ (torch.float16, torch.float32),
+ ],
+ )
+ @pytest.mark.parametrize("wrap", ["so3", "quaternion"])
+ def test_mixed_dtype_translation_raises_5913(self, device, pair, wrap):
+ # The mix used to construct, then inverse()/adjoint()/__mul__ raised torch's "expected scalar type" error.
+ if device.type == "mps" and torch.float64 in pair:
+ pytest.skip("MPS has no float64")
+ r_dtype, t_dtype = pair
+ rotation = So3.identity(1, device, r_dtype) if wrap == "so3" else Quaternion.identity(1, device, r_dtype)
+ with pytest.raises(
+ TypeCheckError, match=r"Se3 translation must have the dtype of its rotation.*" + str(t_dtype)
+ ):
+ Se3(rotation, torch.zeros(1, 3, device=device, dtype=t_dtype))
+ with pytest.raises(TypeCheckError, match=r"Se3 translation"):
+ Se3(rotation, Vector3(torch.zeros(1, 3, device=device, dtype=t_dtype)))
+
+ def test_same_dtype_translation_is_accepted_5913(self, device, dtype):
+ s = Se3(So3.identity(2, device, dtype), torch.zeros(2, 3, device=device, dtype=dtype))
+ assert s.t.dtype == s.quaternion.data.dtype == dtype
+
+ @pytest.mark.skipif(not dynamo_is_available(), reason=DYNAMO_UNAVAILABLE_REASON)
+ def test_dynamo_constructor_checks_5913(self, device, torch_optimizer):
+ def build(q, t):
+ return Se3(Quaternion(q), t).matrix()
+
+ args = (torch.rand(2, 4, device=device), torch.rand(2, 3, device=device))
+ self.assert_close(torch_optimizer(build, fullgraph=True)(*args), build(*args))
+
+ @pytest.mark.parametrize("cdtype", [torch.cfloat, torch.cdouble])
+ def test_complex_translation_raises_5913(self, device, cdtype):
+ if device.type == "mps" and cdtype != torch.cfloat:
+ pytest.skip("MPS supports complex64 only")
+ with pytest.raises(TypeCheckError, match=r"Se3 translation must be a real floating-point tensor.*complex"):
+ Se3(So3.identity(1, device), torch.zeros(1, 3, device=device, dtype=cdtype))
+
+ @pytest.mark.parametrize("int_dtype", [torch.int64, torch.bool])
+ def test_integer_parameter_translation_raises_5913(self, device, int_dtype):
+ translation = torch.nn.Parameter(torch.zeros(1, 3, device=device, dtype=int_dtype), requires_grad=False)
+ with pytest.raises(TypeCheckError, match=r"Se3 stores 'translation'.*" + str(int_dtype)):
+ Se3(So3.identity(1, device), translation)
+
+ def test_translation_on_another_device_raises_5913(self, device):
+ # the meta device stands in for a second accelerator.
+ with pytest.raises(DeviceError, match=r"Se3 translation must be on the device of its rotation"):
+ Se3(So3.identity(1, device), torch.zeros(1, 3, device="meta"))
+
+ def test_internal_constructions_still_build_5913(self, device, dtype):
+ a = Se3.exp(torch.rand(2, 6, device=device, dtype=dtype))
+ x = torch.rand(2, device=device, dtype=dtype)
+ built = [
+ Se3.identity(None, device, dtype),
+ Se3.identity(2, device, dtype),
+ Se3.random(None, device, dtype),
+ Se3.random(2, device, dtype),
+ Se3.from_matrix(a.matrix().detach()),
+ Se3.from_qxyz(torch.rand(2, 7, device=device, dtype=dtype)),
+ Se3.rot_x(x),
+ Se3.rot_y(x),
+ Se3.rot_z(x),
+ Se3.trans(x, x, x),
+ Se3.trans_x(x),
+ Se3.trans_y(x),
+ Se3.trans_z(x),
+ a[0],
+ a.inverse(),
+ a * a,
+ NamedPose.from_rt(So3.identity(1, device, dtype), torch.zeros(1, 3, device=device, dtype=dtype)).pose,
+ ]
+ assert all(isinstance(s, Se3) for s in built)
+ assert all(s.t.dtype == dtype for s in built)
+
def test_derived_state_moves_and_serializes(self, device, dtype):
v = torch.rand(2, 6, device=device, dtype=dtype, requires_grad=True)
s = Se3.exp(v)
diff --git a/tests/geometry/liegroup/test_so2.py b/tests/geometry/liegroup/test_so2.py
index 6dd229e7e..e40b72f37 100644
--- a/tests/geometry/liegroup/test_so2.py
+++ b/tests/geometry/liegroup/test_so2.py
@@ -39,6 +39,54 @@ class TestSo2(BaseTester):
with pytest.raises(TypeCheckError, match=r"So2 stores 'z'.*torch.int64"):
So2(torch.tensor([1], device=device))
+ @pytest.mark.parametrize("real_dtype", [torch.float16, torch.bfloat16, torch.float32, torch.float64])
+ def test_real_z_raises_5913(self, device, real_dtype):
+ # A real z only fails inside matrix()/log()/__mul__ with torch's "imag is not implemented"; the constructor
+ # rejects it with a kornia error naming the argument and dtype.
+ if real_dtype == torch.float64 and device.type == "mps":
+ pytest.skip("MPS has no float64")
+ for z in (
+ torch.tensor([0.6, 0.8], device=device, dtype=real_dtype),
+ torch.tensor(0.5, device=device, dtype=real_dtype),
+ ):
+ with pytest.raises(TypeCheckError, match=r"So2 stores 'z' as a complex tensor.*" + str(real_dtype)):
+ So2(z)
+ with pytest.raises(TypeCheckError, match=r"So2 stores 'z'.*torch.bool"):
+ So2(torch.tensor([True], device=device))
+ with pytest.raises(TypeCheckError, match=r"So2 stores 'z'"):
+ So2(torch.nn.Parameter(torch.tensor([0.6], device=device, dtype=real_dtype)))
+
+ @pytest.mark.skipif(not dynamo_is_available(), reason=DYNAMO_UNAVAILABLE_REASON)
+ def test_dynamo_constructor_checks_5913(self, device, torch_optimizer):
+ # the dtype check is static: it adds no graph break to a traced constructor
+ def build(real, imag):
+ return So2(torch.complex(real, imag)).matrix()
+
+ real, imag = torch.rand(2, device=device), torch.rand(2, device=device)
+ self.assert_close(torch_optimizer(build, fullgraph=True)(real, imag), build(real, imag))
+
+ @pytest.mark.parametrize("cdtype", [torch.chalf, torch.cfloat, torch.cdouble])
+ @pytest.mark.filterwarnings("ignore:ComplexHalf support is experimental")
+ def test_every_complex_dtype_is_accepted_5913(self, device, cdtype):
+ if device.type == "mps" and cdtype != torch.cfloat:
+ pytest.skip("MPS supports complex64 only")
+ z = torch.complex(torch.tensor([0.6, 0.8]), torch.tensor([0.8, 0.6])).to(cdtype).to(device)
+ s = So2(z)
+ assert s.z.dtype == cdtype
+ assert s[0].z.dtype == cdtype
+
+ def test_internal_constructions_still_build_5913(self, device, dtype):
+ if dtype == torch.bfloat16:
+ pytest.skip("torch has no complex bfloat16 dtype, which So2 stores its rotation in")
+ a = So2.exp(torch.tensor([0.3, -0.4], device=device, dtype=dtype))
+ b = So2.identity(2, device, dtype)
+ assert isinstance(a * b, So2)
+ assert isinstance(a.inverse(), So2)
+ assert isinstance(a[0], So2)
+ assert isinstance(So2.random(2, device, dtype), So2)
+ assert isinstance(So2.from_matrix(a.matrix().detach()), So2)
+ assert all(s.z.is_complex() for s in (a, a * b, a.inverse()))
+
@pytest.mark.parametrize("cdtype", [torch.cfloat, torch.cdouble])
def test_smoke(self, device, cdtype):
z = torch.randn(2, 1, dtype=cdtype, device=device)