Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

fix(geometry): liegroup half precision - So3/Se3 compute in float32, bfloat16 So2/Se2 raise TypeCheckError (#5936)

Dmytro Mishkin1b031ae8dc65
diff --git a/changelog.d/5936.fixed.md b/changelog.d/5936.fixed.md
new file mode 100644
index 000000000..39e14dd42
--- /dev/null
+++ b/changelog.d/5936.fixed.md
@@ -0,0 +1,9 @@
+`So3.matrix()` (and `adjoint()`), `So3 * So3`, `So3 * points`, `Se3 * Se3` and `Se3 * points` now compute in float32
+for float16 and bfloat16 inputs and return the input dtype, rounding once; `Se3.matrix()` and `Se3.inverse()` follow
+through `So3`. Evaluated in half precision, each drifted 3 to 6 units of roundoff from the exact result, and
+identities such as `R.T @ R == I`, `(s * s.inverse()).t == 0` and chained point transforms missed by up to about 12
+units; they now hold to about 2. float32 and float64 results are unchanged. Building a bfloat16 `So2` or `Se2`
+(`exp`, `identity`, `random`, `from_matrix`, `Se2.trans`, `trans_x`, `trans_y`, and a `NamedPose` of an `Se2` pose)
+used to fail inside `torch.complex` with a `RuntimeError`, since PyTorch has no complex bfloat16 dtype; it now raises
+`TypeCheckError` naming the limitation. `.bfloat16()` on a built `So2` or `Se2` keeps working and keeps the
+rotation's complex precision.
diff --git a/docs/source/get-started/precision.rst b/docs/source/get-started/precision.rst
index 1f12b6b08..1339d55b3 100644
--- a/docs/source/get-started/precision.rst
+++ b/docs/source/get-started/precision.rst
@@ -87,12 +87,13 @@ precision, so the table says nothing about those backends.
- The DLT solvers run (``_torch_svd_cast`` promotes the SVD to float32) but miss the clean-point accuracy
checks, including the iterated and line-based variants.
* - ``kornia.geometry.liegroup``
+ - ✅ Yes
- ⚠️ Partial
- - ⚠️ Partial
- - 4 / 130
- - ``So2`` and ``Se2`` store complex tensors; float16 inverses are computed in complex64. PyTorch has no
- complex bfloat16 dtype, so most bfloat16 ``So2`` / ``Se2`` tests raise (119 entries). ``So3`` and ``Se3``
- miss a few composition, point-transform and orthogonality accuracy checks.
+ - 0 / 0
+ - ``So3`` and ``Se3`` compute ``matrix()``, composition and point transforms in float32 for float16/bfloat16
+ inputs and return the input dtype. ``So2`` and ``Se2`` store complex tensors; float16 inverses are computed
+ in complex64. PyTorch has no complex bfloat16 dtype, so building a bfloat16 ``So2`` or ``Se2`` raises
+ ``TypeCheckError``, while ``.bfloat16()`` on a built one keeps the rotation's complex precision.
* - ``kornia.geometry.solvers``
- ⚠️ Partial
- ⚠️ Partial
@@ -117,8 +118,9 @@ precision, so the table says nothing about those backends.
* - ``kornia.geometry`` (other)
- ⚠️ Partial
- ⚠️ Partial
- - 8 / 17
- - Accuracy in boxes, depth and line utilities; a bfloat16 ``NamedPose`` of an ``Se2`` pose cannot be built (``So2`` stores a complex number).
+ - 7 / 14
+ - Accuracy of the box transforms and depth utilities. A bfloat16 ``NamedPose`` of an ``Se2`` pose raises as
+ ``Se2`` does.
* - ``kornia.image``
- ⚠️ Partial
- ⚠️ Partial
diff --git a/kornia/geometry/liegroup/se2.py b/kornia/geometry/liegroup/se2.py
index b502163d0..168ca121d 100644
--- a/kornia/geometry/liegroup/se2.py
+++ b/kornia/geometry/liegroup/se2.py
@@ -103,7 +103,9 @@ class Se2(nn.Module):
reads it back, so ``matrix_exp(hat(v))`` equals ``exp(v).matrix()``.
- Module conversions follow :class:`~kornia.geometry.liegroup.So2`'s dtype policy for the rotation and
PyTorch's native policy for the translation. A bfloat16 cast changes the translation precision while
- keeping the rotation's existing complex precision; both follow any requested device move.
+ keeping the rotation's existing complex precision; both follow any requested device move. Building a
+ pose from bfloat16 values (``exp``, ``identity``, ``random``, ``from_matrix`` or ``trans*``) raises
+ ``TypeCheckError``, as for ``So2``.
Example:
>>> so2 = So2.identity(1)
diff --git a/kornia/geometry/liegroup/se3.py b/kornia/geometry/liegroup/se3.py
index b0fef85c3..35aa03756 100644
--- a/kornia/geometry/liegroup/se3.py
+++ b/kornia/geometry/liegroup/se3.py
@@ -19,7 +19,7 @@
# https://github.com/strasdat/Sophus/blob/master/sympy/sophus/se3.py
from __future__ import annotations
-from typing import Optional, Union
+from typing import Optional, Union, overload
import torch
import torch.nn.functional as F
@@ -28,7 +28,7 @@ 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.liegroup.so3 import So3, _so3_rotate, _so3_small_angle_coefficients
from kornia.geometry.linalg import batched_dot_product
from kornia.geometry.quaternion import Quaternion
from kornia.geometry.vector import Vector3
@@ -87,6 +87,9 @@ class Se3(nn.Module):
- ``state_dict()``, ``load_state_dict()`` and module device/dtype conversions include both the rotation
and translation. Rotation state follows :class:`~kornia.geometry.quaternion.Quaternion`'s
buffer/parameter convention.
+ - ``a * b`` and ``g * p`` compute in float32 for float16/bfloat16 inputs and return the input dtype,
+ rounding :math:`R p + t` once; ``matrix()`` and ``inverse()`` take the rotation from
+ :class:`~kornia.geometry.liegroup.So3`, which does the same.
Example:
>>> q = Quaternion.identity()
@@ -152,12 +155,24 @@ class Se3(nn.Module):
def _mul_se3(self, right: Se3) -> Se3:
_r = self.r * right.r
- _t = self.t + self.r * right.t
+ # t + R t2 is rounded once, so float16/bfloat16 sum the float32 rotated translation
+ _t = (self.t + _so3_rotate(self.r.q, right.t)).to(torch.promote_types(self.t.dtype, right.t.dtype))
return Se3(_r, _t)
- def __mul__(self, right: Se3) -> Se3 | Vector3 | torch.Tensor:
+ @overload
+ def __mul__(self, right: Se3) -> Se3: ...
+
+ @overload
+ def __mul__(self, right: Vector3) -> Vector3: ...
+
+ @overload
+ def __mul__(self, right: torch.Tensor) -> torch.Tensor: ...
+
+ def __mul__(self, right: Se3 | Vector3 | torch.Tensor) -> Se3 | Vector3 | torch.Tensor:
"""Compose two Se3 transformations, or transform points.
+ Both compute in float32 for float16/bfloat16 inputs and return the input dtype.
+
Args:
right: the other Se3 transformation, or points as a tensor or ``Vector3`` with the batch shape of the
pose and a last dimension of 3.
@@ -174,7 +189,9 @@ class Se3(nn.Module):
if isinstance(right, (Vector3, torch.Tensor)):
_right_data = right if isinstance(right, torch.Tensor) else right.data
KORNIA_CHECK_SHAPE(_right_data, ["*", "N"])
- return so3 * right + t
+ # R p + t is rounded once, so float16/bfloat16 add the translation to the float32 rotated point
+ out = (_so3_rotate(so3.q, _right_data) + t).to(torch.promote_types(t.dtype, _right_data.dtype))
+ return Vector3(out) if isinstance(right, Vector3) else out
raise TypeError(f"Unsupported type: {type(right)}")
@property
diff --git a/kornia/geometry/liegroup/so2.py b/kornia/geometry/liegroup/so2.py
index 6925c6873..8813e8e59 100644
--- a/kornia/geometry/liegroup/so2.py
+++ b/kornia/geometry/liegroup/so2.py
@@ -32,6 +32,19 @@ from kornia.core.utils import is_exporting, register_module_state
from kornia.geometry.vector import Vector2
+def _complex_rotation(real: torch.Tensor, imag: torch.Tensor) -> torch.Tensor:
+ """Build the complex ``z`` an So2 stores, rejecting bfloat16 parts, for which PyTorch has no complex dtype."""
+ if torch.bfloat16 in (real.dtype, imag.dtype):
+ # torch.complex would raise a RuntimeError that names neither So2 nor a way out
+ raise TypeCheckError(
+ "So2 stores its rotation as a complex tensor, and PyTorch has no complex bfloat16 dtype; got a bfloat16 "
+ "real or imaginary part. Build the rotation in float16, float32 or float64; `.bfloat16()` on a built So2 "
+ "or Se2 keeps the rotation's complex precision.",
+ actual_type=torch.bfloat16,
+ )
+ return torch.complex(real, imag)
+
+
class So2(nn.Module):
r"""Base class to represent the So2 group.
@@ -44,7 +57,8 @@ class So2(nn.Module):
``z`` or angle is accepted and read as :math:`(B,)`. For unit :math:`z = \cos\theta + i \sin\theta`,
``matrix()`` is :math:`[[\cos\theta, -\sin\theta], [\sin\theta, \cos\theta]]`. Non-unit ``z = a + i b``
is accepted and produces :math:`[[a, -b], [b, a]]`, which rotates and scales by :math:`|z|`. The complex
- storage has no bfloat16 counterpart in PyTorch.
+ storage has no bfloat16 counterpart in PyTorch, so ``exp``, ``identity``, ``random`` and ``from_matrix``
+ raise ``TypeCheckError`` for bfloat16 values.
- A positive angle rotates the x axis toward the y axis: counter-clockwise in a y-up frame, clockwise as
displayed on y-down image axes. For a unit rotation, ``matrix()`` is the transpose of
:func:`~kornia.geometry.conversions.angle_to_rotation_matrix`, which takes degrees.
@@ -185,6 +199,9 @@ class So2(nn.Module):
Args:
theta: angle in radians of shape :math:`(B,)` or :math:`()`; :math:`(B, 1)` is squeezed to :math:`(B,)`.
+ Raises:
+ TypeCheckError: if ``theta`` is bfloat16, which has no complex dtype in PyTorch.
+
Example:
>>> v = torch.tensor([3.1415/2])
>>> s = So2.exp(v)
@@ -199,7 +216,7 @@ class So2(nn.Module):
is_column = KORNIA_CHECK_SHAPE(theta, ["B", "1"], raises=False)
if not (is_scalar or is_flat or is_column):
raise ValueError(f"Invalid input size, we expect [], [B], or [B, 1]. Got: {theta.shape}")
- return So2(torch.complex(torch.cos(theta), torch.sin(theta)))
+ return So2(_complex_rotation(torch.cos(theta), torch.sin(theta)))
def log(self) -> torch.Tensor:
"""Convert elements of lie group to elements of lie algebra.
@@ -290,6 +307,9 @@ class So2(nn.Module):
Args:
matrix: the rotation matrix to convert of shape :math:`(B, 2, 2)`.
+ Raises:
+ TypeCheckError: if ``matrix`` is bfloat16, which has no complex dtype in PyTorch.
+
Example:
>>> m = torch.eye(2)
>>> s = So2.from_matrix(m)
@@ -313,7 +333,7 @@ class So2(nn.Module):
mask_off_diag = torch.allclose(matrix[..., 0, 1], -matrix[..., 1, 0])
if not (mask_diag and mask_off_diag):
raise ValueError("Invalid SO2 rotation matrix: constraints m00==m11 and m01==-m10 not met.")
- z = torch.complex(matrix[..., 0, 0], matrix[..., 1, 0])
+ z = _complex_rotation(matrix[..., 0, 0], matrix[..., 1, 0])
return cls(z)
@classmethod
@@ -330,6 +350,9 @@ class So2(nn.Module):
device: device to place the result on.
dtype: dtype of the result.
+ Raises:
+ TypeCheckError: if ``dtype`` is bfloat16, which has no complex dtype in PyTorch.
+
Example:
>>> s = So2.identity(batch_size=2)
>>> s
@@ -343,7 +366,7 @@ class So2(nn.Module):
KORNIA_CHECK(batch_size >= 1, msg="batch_size must be positive")
real_data = real_data.repeat(batch_size)
imag_data = imag_data.repeat(batch_size)
- return cls(torch.complex(real_data, imag_data))
+ return cls(_complex_rotation(real_data, imag_data))
def inverse(self) -> So2:
"""Return the inverse transformation.
@@ -376,6 +399,9 @@ class So2(nn.Module):
device: device to place the result on.
dtype: dtype of the result.
+ Raises:
+ TypeCheckError: if ``dtype`` is bfloat16, which has no complex dtype in PyTorch.
+
Example:
>>> s = So2.random()
>>> s = So2.random(batch_size=3)
diff --git a/kornia/geometry/liegroup/so3.py b/kornia/geometry/liegroup/so3.py
index 57c090b44..22271a361 100644
--- a/kornia/geometry/liegroup/so3.py
+++ b/kornia/geometry/liegroup/so3.py
@@ -19,7 +19,7 @@
# https://github.com/strasdat/Sophus/blob/master/sympy/sophus/so3.py
from __future__ import annotations
-from typing import Optional, Union
+from typing import Optional, Union, overload
import torch
from torch import nn
@@ -71,6 +71,27 @@ def _so3_small_angle_coefficients(theta: torch.Tensor) -> tuple[torch.Tensor, to
return a, b, c
+def _computes_in_float32(dtype: torch.dtype) -> bool:
+ """Whether So3 and Se3 evaluate an operation of this result dtype in float32 and round it once."""
+ return dtype in (torch.float16, torch.bfloat16)
+
+
+def _so3_rotate(q: Quaternion, points: torch.Tensor) -> torch.Tensor:
+ """Rotate points of shape :math:`(*, 3)` by the unit direction of ``q`` as :math:`q p q^*`.
+
+ A float16/bfloat16 result is computed in float32 and returned in float32, for the caller to add to it or round it
+ once; any other dtype combination is evaluated as given.
+ """
+ KORNIA_CHECK_SHAPE(points, ["*", "3"])
+ if _computes_in_float32(torch.promote_types(q.data.dtype, points.dtype)):
+ q, points = q.to(torch.float32), points.float()
+ w = torch.zeros(*points.shape[:-1], 1, device=points.device, dtype=points.dtype)
+ quat = Quaternion(torch.cat((w, points), -1))
+ # q p q* scales p by |q|^2, so rotate by the unit direction of q
+ q = q.normalize()
+ return (q * quat * q.conj()).vec
+
+
class So3(nn.Module):
r"""Base class to represent the So3 group.
@@ -103,6 +124,8 @@ class So3(nn.Module):
- The quaternion is registered as module state following
:class:`~kornia.geometry.quaternion.Quaternion`'s buffer/parameter convention, including rotations
produced by ``exp``, ``identity``, ``random``, ``from_matrix`` and group operations.
+ - ``matrix()``, ``adjoint()``, ``a * b`` and ``s * p`` compute in float32 for float16/bfloat16 inputs and
+ return the input dtype, rounding once; float32 and float64 are evaluated in their own dtype.
Example:
>>> q = Quaternion.identity()
@@ -136,9 +159,20 @@ class So3(nn.Module):
def __getitem__(self, idx: int | slice) -> So3:
return So3(self._q[idx])
- def __mul__(self, right: So3) -> So3:
+ @overload
+ def __mul__(self, right: So3) -> So3: ...
+
+ @overload
+ def __mul__(self, right: Vector3) -> Vector3: ...
+
+ @overload
+ def __mul__(self, right: torch.Tensor) -> torch.Tensor: ...
+
+ def __mul__(self, right: So3 | Vector3 | torch.Tensor) -> So3 | Vector3 | torch.Tensor:
"""Compose two So3 transformations, or rotate points.
+ Both compute in float32 for float16/bfloat16 inputs and return the input dtype.
+
Args:
right: the other So3 transformation, or points of shape :math:`(B, 3)` as a tensor or a ``Vector3``.
@@ -148,15 +182,14 @@ class So3(nn.Module):
"""
# https://github.com/strasdat/Sophus/blob/master/sympy/sophus/so3.py#L98
if isinstance(right, So3):
+ dtype = torch.promote_types(self.q.data.dtype, right.q.data.dtype)
+ if _computes_in_float32(dtype):
+ product = self.q.to(torch.float32) * right.q.to(torch.float32)
+ return So3(Quaternion(product.data.to(dtype)))
return So3(self.q * right.q)
if isinstance(right, (torch.Tensor, Vector3)):
_right_data = _unwrap(right)
- KORNIA_CHECK_SHAPE(_right_data, ["*", "3"])
- w = torch.zeros(*right.shape[:-1], 1, device=right.device, dtype=right.dtype)
- quat = Quaternion(torch.cat((w, _right_data), -1))
- # q p q* scales p by |q|^2, so rotate by the unit direction of q
- q = self.q.normalize()
- out = (q * quat * q.conj()).vec
+ out = _so3_rotate(self.q, _right_data).to(torch.promote_types(self.q.data.dtype, _right_data.dtype))
return Vector3(out) if isinstance(right, Vector3) else out
raise TypeError(f"Not So3 or torch.Tensor type. Got: {type(right)}")
@@ -284,6 +317,8 @@ class So3(nn.Module):
2xy+2zw & 1-2x^2-2z^2 & 2yz-2xw \\
2xz-2yw & 2yz+2xw & 1-2x^2-2y^2\end{bmatrix}
+ It computes in float32 for float16/bfloat16 inputs and returns the input dtype.
+
Example:
>>> s = So3.identity()
>>> m = s.matrix()
@@ -295,7 +330,9 @@ class So3(nn.Module):
"""
# The formula below holds for a unit quaternion only. Normalising here rather than in the constructor keeps
# the stored quaternion, possibly an nn.Parameter, as the module state.
- q = self.q.normalize()
+ dtype = self.q.data.dtype
+ q = self.q.to(torch.float32) if _computes_in_float32(dtype) else self.q
+ q = q.normalize()
w = q.w[..., None]
x, y, z = q.x[..., None], q.y[..., None], q.z[..., None]
q0 = 1 - 2 * y**2 - 2 * z**2
@@ -310,7 +347,7 @@ class So3(nn.Module):
q1 = 2 * y * z + 2 * x * w
q2 = 1 - 2 * x**2 - 2 * y**2
row2 = torch.cat((q0, q1, q2), -1)
- return torch.stack((row0, row1, row2), -2)
+ return torch.stack((row0, row1, row2), -2).to(dtype)
@classmethod
def from_matrix(cls, matrix: torch.Tensor, check_rotation: bool = False) -> So3:
diff --git a/testing/half_precision_xfails/cpu_bfloat16.txt b/testing/half_precision_xfails/cpu_bfloat16.txt
index c30cf3ce1..2e217b6ab 100644
--- a/testing/half_precision_xfails/cpu_bfloat16.txt
+++ b/testing/half_precision_xfails/cpu_bfloat16.txt
@@ -154,136 +154,6 @@ call builtins.NotImplementedError tests/geometry/epipolar/test_projection.py::Te
call builtins.NotImplementedError tests/geometry/epipolar/test_projection.py::TestKRtFromProjection::test_simple[cpu-bfloat16]
call builtins.NotImplementedError tests/geometry/epipolar/test_projection.py::TestKRtFromProjection::test_smoke[cpu-bfloat16]
call builtins.NotImplementedError tests/geometry/epipolar/test_projection.py::TestProjectionFromKRt::test_krt_from_projection[cpu-bfloat16]
-call builtins.RuntimeError tests/geometry/liegroup/test_se2.py::TestSe2::test_cardinality[cpu-bfloat16-input_shape0]
-call builtins.RuntimeError tests/geometry/liegroup/test_se2.py::TestSe2::test_cardinality[cpu-bfloat16-input_shape1]
-call builtins.RuntimeError tests/geometry/liegroup/test_se2.py::TestSe2::test_cardinality[cpu-bfloat16-input_shape2]
-call builtins.RuntimeError tests/geometry/liegroup/test_se2.py::TestSe2::test_cardinality[cpu-bfloat16-input_shape3]
-call builtins.RuntimeError tests/geometry/liegroup/test_se2.py::TestSe2::test_derived_state_moves_and_serializes[cpu-bfloat16]
-call builtins.RuntimeError tests/geometry/liegroup/test_se2.py::TestSe2::test_exception[cpu-bfloat16-1]
-call builtins.RuntimeError tests/geometry/liegroup/test_se2.py::TestSe2::test_exception[cpu-bfloat16-2]
-call builtins.RuntimeError tests/geometry/liegroup/test_se2.py::TestSe2::test_exception[cpu-bfloat16-5]
-call builtins.RuntimeError tests/geometry/liegroup/test_se2.py::TestSe2::test_exp[cpu-bfloat16-1]
-call builtins.RuntimeError tests/geometry/liegroup/test_se2.py::TestSe2::test_exp[cpu-bfloat16-2]
-call builtins.RuntimeError tests/geometry/liegroup/test_se2.py::TestSe2::test_exp[cpu-bfloat16-5]
-call builtins.RuntimeError tests/geometry/liegroup/test_se2.py::TestSe2::test_exp[cpu-bfloat16-None]
-call builtins.RuntimeError tests/geometry/liegroup/test_se2.py::TestSe2::test_exp_log[cpu-bfloat16-1]
-call builtins.RuntimeError tests/geometry/liegroup/test_se2.py::TestSe2::test_exp_log[cpu-bfloat16-2]
-call builtins.RuntimeError tests/geometry/liegroup/test_se2.py::TestSe2::test_exp_log[cpu-bfloat16-5]
-call builtins.RuntimeError tests/geometry/liegroup/test_se2.py::TestSe2::test_exp_log[cpu-bfloat16-None]
-call builtins.RuntimeError tests/geometry/liegroup/test_se2.py::TestSe2::test_from_matrix[cpu-bfloat16-1]
-call builtins.RuntimeError tests/geometry/liegroup/test_se2.py::TestSe2::test_from_matrix[cpu-bfloat16-2]
-call builtins.RuntimeError tests/geometry/liegroup/test_se2.py::TestSe2::test_from_matrix[cpu-bfloat16-5]
-call builtins.RuntimeError tests/geometry/liegroup/test_se2.py::TestSe2::test_from_matrix[cpu-bfloat16-None]
-call builtins.RuntimeError tests/geometry/liegroup/test_se2.py::TestSe2::test_init[cpu-bfloat16-1]
-call builtins.RuntimeError tests/geometry/liegroup/test_se2.py::TestSe2::test_init[cpu-bfloat16-2]
-call builtins.RuntimeError tests/geometry/liegroup/test_se2.py::TestSe2::test_init[cpu-bfloat16-5]
-call builtins.RuntimeError tests/geometry/liegroup/test_se2.py::TestSe2::test_init[cpu-bfloat16-None]
-call builtins.RuntimeError tests/geometry/liegroup/test_se2.py::TestSe2::test_inverse[cpu-bfloat16-1]
-call builtins.RuntimeError tests/geometry/liegroup/test_se2.py::TestSe2::test_inverse[cpu-bfloat16-2]
-call builtins.RuntimeError tests/geometry/liegroup/test_se2.py::TestSe2::test_inverse[cpu-bfloat16-5]
-call builtins.RuntimeError tests/geometry/liegroup/test_se2.py::TestSe2::test_inverse[cpu-bfloat16-None]
-call builtins.RuntimeError tests/geometry/liegroup/test_se2.py::TestSe2::test_log[cpu-bfloat16-1]
-call builtins.RuntimeError tests/geometry/liegroup/test_se2.py::TestSe2::test_log[cpu-bfloat16-2]
-call builtins.RuntimeError tests/geometry/liegroup/test_se2.py::TestSe2::test_log[cpu-bfloat16-5]
-call builtins.RuntimeError tests/geometry/liegroup/test_se2.py::TestSe2::test_log[cpu-bfloat16-None]
-call builtins.RuntimeError tests/geometry/liegroup/test_se2.py::TestSe2::test_matrix[cpu-bfloat16-1]
-call builtins.RuntimeError tests/geometry/liegroup/test_se2.py::TestSe2::test_matrix[cpu-bfloat16-2]
-call builtins.RuntimeError tests/geometry/liegroup/test_se2.py::TestSe2::test_matrix[cpu-bfloat16-5]
-call builtins.RuntimeError tests/geometry/liegroup/test_se2.py::TestSe2::test_matrix[cpu-bfloat16-None]
-call builtins.RuntimeError tests/geometry/liegroup/test_se2.py::TestSe2::test_mul[cpu-bfloat16-1]
-call builtins.RuntimeError tests/geometry/liegroup/test_se2.py::TestSe2::test_mul[cpu-bfloat16-2]
-call builtins.RuntimeError tests/geometry/liegroup/test_se2.py::TestSe2::test_mul[cpu-bfloat16-5]
-call builtins.RuntimeError tests/geometry/liegroup/test_se2.py::TestSe2::test_mul[cpu-bfloat16-None]
-call builtins.RuntimeError tests/geometry/liegroup/test_se2.py::TestSe2::test_mul_vector[cpu-bfloat16-1]
-call builtins.RuntimeError tests/geometry/liegroup/test_se2.py::TestSe2::test_mul_vector[cpu-bfloat16-2]
-call builtins.RuntimeError tests/geometry/liegroup/test_se2.py::TestSe2::test_mul_vector[cpu-bfloat16-5]
-call builtins.RuntimeError tests/geometry/liegroup/test_se2.py::TestSe2::test_mul_vector[cpu-bfloat16-None]
-call builtins.RuntimeError tests/geometry/liegroup/test_se2.py::TestSe2::test_random[cpu-bfloat16-1]
-call builtins.RuntimeError tests/geometry/liegroup/test_se2.py::TestSe2::test_random[cpu-bfloat16-2]
-call builtins.RuntimeError tests/geometry/liegroup/test_se2.py::TestSe2::test_random[cpu-bfloat16-5]
-call builtins.RuntimeError tests/geometry/liegroup/test_se2.py::TestSe2::test_random[cpu-bfloat16-None]
-call builtins.RuntimeError tests/geometry/liegroup/test_se2.py::TestSe2::test_trans[cpu-bfloat16-1]
-call builtins.RuntimeError tests/geometry/liegroup/test_se2.py::TestSe2::test_trans[cpu-bfloat16-2]
-call builtins.RuntimeError tests/geometry/liegroup/test_se2.py::TestSe2::test_trans[cpu-bfloat16-5]
-call builtins.RuntimeError tests/geometry/liegroup/test_se2.py::TestSe2::test_trans[cpu-bfloat16-None]
-call builtins.RuntimeError tests/geometry/liegroup/test_se2.py::TestSe2::test_trans_x[cpu-bfloat16-1]
-call builtins.RuntimeError tests/geometry/liegroup/test_se2.py::TestSe2::test_trans_x[cpu-bfloat16-2]
-call builtins.RuntimeError tests/geometry/liegroup/test_se2.py::TestSe2::test_trans_x[cpu-bfloat16-5]
-call builtins.RuntimeError tests/geometry/liegroup/test_se2.py::TestSe2::test_trans_x[cpu-bfloat16-None]
-call builtins.RuntimeError tests/geometry/liegroup/test_se2.py::TestSe2::test_trans_y[cpu-bfloat16-1]
-call builtins.RuntimeError tests/geometry/liegroup/test_se2.py::TestSe2::test_trans_y[cpu-bfloat16-2]
-call builtins.RuntimeError tests/geometry/liegroup/test_se2.py::TestSe2::test_trans_y[cpu-bfloat16-5]
-call builtins.RuntimeError tests/geometry/liegroup/test_se2.py::TestSe2::test_trans_y[cpu-bfloat16-None]
-call builtins.AssertionError tests/geometry/liegroup/test_se3.py::TestSe3::test_mul[cpu-bfloat16-2]
-call builtins.AssertionError tests/geometry/liegroup/test_se3.py::TestSe3::test_mul[cpu-bfloat16-None]
-call builtins.AssertionError tests/geometry/liegroup/test_se3.py::TestSe3::test_mul_point[cpu-bfloat16-1]
-call builtins.AssertionError tests/geometry/liegroup/test_se3.py::TestSe3::test_mul_point[cpu-bfloat16-2]
-call builtins.AssertionError tests/geometry/liegroup/test_se3.py::TestSe3::test_mul_point[cpu-bfloat16-5]
-call builtins.AssertionError tests/geometry/liegroup/test_se3.py::TestSe3::test_mul_point[cpu-bfloat16-None]
-call builtins.AssertionError tests/geometry/liegroup/test_se3.py::TestSe3::test_mul_vector[cpu-bfloat16-2]
-call builtins.AssertionError tests/geometry/liegroup/test_se3.py::TestSe3::test_mul_vector[cpu-bfloat16-5]
-call builtins.AssertionError tests/geometry/liegroup/test_se3.py::TestSe3::test_mul_vector[cpu-bfloat16-None]
-call builtins.RuntimeError tests/geometry/liegroup/test_so2.py::TestSo2::test_adjoint[cpu-bfloat16-1]
-call builtins.RuntimeError tests/geometry/liegroup/test_so2.py::TestSo2::test_adjoint[cpu-bfloat16-2]
-call builtins.RuntimeError tests/geometry/liegroup/test_so2.py::TestSo2::test_adjoint[cpu-bfloat16-5]
-call builtins.RuntimeError tests/geometry/liegroup/test_so2.py::TestSo2::test_adjoint[cpu-bfloat16-None]
-call builtins.RuntimeError tests/geometry/liegroup/test_so2.py::TestSo2::test_cardinality[cpu-bfloat16-cdtype0-input_shape0]
-call builtins.RuntimeError tests/geometry/liegroup/test_so2.py::TestSo2::test_cardinality[cpu-bfloat16-cdtype0-input_shape1]
-call builtins.RuntimeError tests/geometry/liegroup/test_so2.py::TestSo2::test_cardinality[cpu-bfloat16-cdtype0-input_shape2]
-call builtins.RuntimeError tests/geometry/liegroup/test_so2.py::TestSo2::test_cardinality[cpu-bfloat16-cdtype0-input_shape3]
-call builtins.RuntimeError tests/geometry/liegroup/test_so2.py::TestSo2::test_cardinality[cpu-bfloat16-cdtype1-input_shape0]
-call builtins.RuntimeError tests/geometry/liegroup/test_so2.py::TestSo2::test_cardinality[cpu-bfloat16-cdtype1-input_shape1]
-call builtins.RuntimeError tests/geometry/liegroup/test_so2.py::TestSo2::test_cardinality[cpu-bfloat16-cdtype1-input_shape2]
-call builtins.RuntimeError tests/geometry/liegroup/test_so2.py::TestSo2::test_cardinality[cpu-bfloat16-cdtype1-input_shape3]
-call builtins.RuntimeError tests/geometry/liegroup/test_so2.py::TestSo2::test_derived_state_moves_and_serializes[cpu-bfloat16]
-call builtins.RuntimeError tests/geometry/liegroup/test_so2.py::TestSo2::test_exception[cpu-bfloat16-cdtype0-1]
-call builtins.RuntimeError tests/geometry/liegroup/test_so2.py::TestSo2::test_exception[cpu-bfloat16-cdtype0-2]
-call builtins.RuntimeError tests/geometry/liegroup/test_so2.py::TestSo2::test_exception[cpu-bfloat16-cdtype0-5]
-call builtins.RuntimeError tests/geometry/liegroup/test_so2.py::TestSo2::test_exception[cpu-bfloat16-cdtype1-1]
-call builtins.RuntimeError tests/geometry/liegroup/test_so2.py::TestSo2::test_exception[cpu-bfloat16-cdtype1-2]
-call builtins.RuntimeError tests/geometry/liegroup/test_so2.py::TestSo2::test_exception[cpu-bfloat16-cdtype1-5]
-call builtins.RuntimeError tests/geometry/liegroup/test_so2.py::TestSo2::test_exp[cpu-bfloat16-1]
-call builtins.RuntimeError tests/geometry/liegroup/test_so2.py::TestSo2::test_exp[cpu-bfloat16-2]
-call builtins.RuntimeError tests/geometry/liegroup/test_so2.py::TestSo2::test_exp[cpu-bfloat16-5]
-call builtins.RuntimeError tests/geometry/liegroup/test_so2.py::TestSo2::test_exp[cpu-bfloat16-None]
-call builtins.RuntimeError tests/geometry/liegroup/test_so2.py::TestSo2::test_exp_log[cpu-bfloat16-1]
-call builtins.RuntimeError tests/geometry/liegroup/test_so2.py::TestSo2::test_exp_log[cpu-bfloat16-2]
-call builtins.RuntimeError tests/geometry/liegroup/test_so2.py::TestSo2::test_exp_log[cpu-bfloat16-5]
-call builtins.RuntimeError tests/geometry/liegroup/test_so2.py::TestSo2::test_exp_log[cpu-bfloat16-None]
-call builtins.RuntimeError tests/geometry/liegroup/test_so2.py::TestSo2::test_from_matrix[cpu-bfloat16-1]
-call builtins.RuntimeError tests/geometry/liegroup/test_so2.py::TestSo2::test_from_matrix[cpu-bfloat16-2]
-call builtins.RuntimeError tests/geometry/liegroup/test_so2.py::TestSo2::test_from_matrix[cpu-bfloat16-5]
-call builtins.RuntimeError tests/geometry/liegroup/test_so2.py::TestSo2::test_from_matrix[cpu-bfloat16-None]
-call builtins.RuntimeError tests/geometry/liegroup/test_so2.py::TestSo2::test_init[cpu-bfloat16-cdtype0-1]
-call builtins.RuntimeError tests/geometry/liegroup/test_so2.py::TestSo2::test_init[cpu-bfloat16-cdtype0-2]
-call builtins.RuntimeError tests/geometry/liegroup/test_so2.py::TestSo2::test_init[cpu-bfloat16-cdtype0-5]
-call builtins.RuntimeError tests/geometry/liegroup/test_so2.py::TestSo2::test_init[cpu-bfloat16-cdtype0-None]
-call builtins.RuntimeError tests/geometry/liegroup/test_so2.py::TestSo2::test_init[cpu-bfloat16-cdtype1-1]
-call builtins.RuntimeError tests/geometry/liegroup/test_so2.py::TestSo2::test_init[cpu-bfloat16-cdtype1-2]
-call builtins.RuntimeError tests/geometry/liegroup/test_so2.py::TestSo2::test_init[cpu-bfloat16-cdtype1-5]
-call builtins.RuntimeError tests/geometry/liegroup/test_so2.py::TestSo2::test_init[cpu-bfloat16-cdtype1-None]
-call builtins.RuntimeError tests/geometry/liegroup/test_so2.py::TestSo2::test_matrix[cpu-bfloat16-1]
-call builtins.RuntimeError tests/geometry/liegroup/test_so2.py::TestSo2::test_matrix[cpu-bfloat16-2]
-call builtins.RuntimeError tests/geometry/liegroup/test_so2.py::TestSo2::test_matrix[cpu-bfloat16-5]
-call builtins.RuntimeError tests/geometry/liegroup/test_so2.py::TestSo2::test_matrix[cpu-bfloat16-None]
-call builtins.RuntimeError tests/geometry/liegroup/test_so2.py::TestSo2::test_matrix_cardinality[cpu-bfloat16-input_shape0]
-call builtins.RuntimeError tests/geometry/liegroup/test_so2.py::TestSo2::test_matrix_cardinality[cpu-bfloat16-input_shape1]
-call builtins.RuntimeError tests/geometry/liegroup/test_so2.py::TestSo2::test_matrix_cardinality[cpu-bfloat16-input_shape2]
-call builtins.RuntimeError tests/geometry/liegroup/test_so2.py::TestSo2::test_matrix_cardinality[cpu-bfloat16-input_shape3]
-call builtins.RuntimeError tests/geometry/liegroup/test_so2.py::TestSo2::test_mul[cpu-bfloat16-1]
-call builtins.RuntimeError tests/geometry/liegroup/test_so2.py::TestSo2::test_mul[cpu-bfloat16-2]
-call builtins.RuntimeError tests/geometry/liegroup/test_so2.py::TestSo2::test_mul[cpu-bfloat16-5]
-call builtins.RuntimeError tests/geometry/liegroup/test_so2.py::TestSo2::test_mul[cpu-bfloat16-None]
-call builtins.RuntimeError tests/geometry/liegroup/test_so2.py::TestSo2::test_mul_vector[cpu-bfloat16-1]
-call builtins.RuntimeError tests/geometry/liegroup/test_so2.py::TestSo2::test_mul_vector[cpu-bfloat16-2]
-call builtins.RuntimeError tests/geometry/liegroup/test_so2.py::TestSo2::test_mul_vector[cpu-bfloat16-5]
-call builtins.RuntimeError tests/geometry/liegroup/test_so2.py::TestSo2::test_mul_vector[cpu-bfloat16-None]
-call builtins.RuntimeError tests/geometry/liegroup/test_so2.py::TestSo2::test_random[cpu-bfloat16-1]
-call builtins.RuntimeError tests/geometry/liegroup/test_so2.py::TestSo2::test_random[cpu-bfloat16-2]
-call builtins.RuntimeError tests/geometry/liegroup/test_so2.py::TestSo2::test_random[cpu-bfloat16-5]
-call builtins.RuntimeError tests/geometry/liegroup/test_so2.py::TestSo2::test_random[cpu-bfloat16-None]
-call builtins.AssertionError tests/geometry/liegroup/test_so3.py::TestSo3::test_ortho[cpu-bfloat16-2]
-call builtins.AssertionError tests/geometry/liegroup/test_so3.py::TestSo3::test_ortho[cpu-bfloat16-5]
call builtins.AssertionError tests/geometry/subpix/test_dsnt.py::TestRenderGaussian2d::test_normalized_coordinates[cpu-bfloat16]
call builtins.AssertionError tests/geometry/subpix/test_dsnt.py::TestRenderGaussian2d::test_pixel_coordinates[cpu-bfloat16]
call builtins.AssertionError tests/geometry/subpix/test_spatial_softargmax.py::TestConvQuadInterp3dModule::test_diag[cpu-bfloat16]
@@ -336,8 +206,6 @@ call builtins.AssertionError tests/geometry/test_homography.py::TestFindHomograp
call builtins.AssertionError tests/geometry/test_homography.py::TestFindHomographyFromLinesDLT::test_clean_points_iter[cpu-bfloat16-1]
call builtins.AssertionError tests/geometry/test_homography.py::TestFindHomographyFromLinesDLT::test_clean_points_iter[cpu-bfloat16-2]
call builtins.AssertionError tests/geometry/test_homography.py::TestFindHomographyFromLinesDLT::test_clean_points_iter[cpu-bfloat16-5]
-call builtins.RuntimeError tests/geometry/test_pose.py::TestNamedPose::test_from_matrix[cpu-bfloat16]
-call builtins.RuntimeError tests/geometry/test_pose.py::TestNamedPose::test_from_rt[cpu-bfloat16]
call builtins.AssertionError tests/geometry/test_quaternion.py::TestQuaternion::test_from_to_euler_values[cpu-bfloat16]
call builtins.AssertionError tests/geometry/test_quaternion.py::TestQuaternion::test_inverse[cpu-bfloat16-5]
call builtins.AssertionError tests/geometry/test_quaternion.py::TestQuaternion::test_pow[cpu-bfloat16-5]
diff --git a/testing/half_precision_xfails/cpu_float16.txt b/testing/half_precision_xfails/cpu_float16.txt
index c0351b942..b62e6013d 100644
--- a/testing/half_precision_xfails/cpu_float16.txt
+++ b/testing/half_precision_xfails/cpu_float16.txt
@@ -142,10 +142,6 @@ call builtins.NotImplementedError tests/geometry/epipolar/test_projection.py::Te
call builtins.NotImplementedError tests/geometry/epipolar/test_projection.py::TestKRtFromProjection::test_simple[cpu-float16]
call builtins.NotImplementedError tests/geometry/epipolar/test_projection.py::TestKRtFromProjection::test_smoke[cpu-float16]
call builtins.NotImplementedError tests/geometry/epipolar/test_projection.py::TestProjectionFromKRt::test_krt_from_projection[cpu-float16]
-call builtins.AssertionError tests/geometry/liegroup/test_se3.py::TestSe3::test_mul[cpu-float16-5]
-call builtins.AssertionError tests/geometry/liegroup/test_se3.py::TestSe3::test_mul_point[cpu-float16-5]
-call builtins.AssertionError tests/geometry/liegroup/test_se3.py::TestSe3::test_mul_vector[cpu-float16-5]
-call builtins.AssertionError tests/geometry/liegroup/test_so3.py::TestSo3::test_ortho[cpu-float16-2]
call builtins.AssertionError tests/geometry/subpix/test_spatial_softargmax.py::TestConvQuadInterp3dModule::test_diag[cpu-float16]
call builtins.AssertionError tests/geometry/subpix/test_spatial_softargmax.py::TestSpatialSoftArgmax2d::test_batch2_n2[cpu-float16]
call builtins.AssertionError tests/geometry/subpix/test_spatial_softargmax.py::TestSpatialSoftArgmax2d::test_bottom_right[cpu-float16]
diff --git a/tests/geometry/liegroup/test_se2.py b/tests/geometry/liegroup/test_se2.py
index ed5ee6745..610cf498d 100644
--- a/tests/geometry/liegroup/test_se2.py
+++ b/tests/geometry/liegroup/test_se2.py
@@ -51,6 +51,8 @@ class TestSe2(BaseTester):
@pytest.mark.parametrize("input_shape", [(1,), (2,), (5,), ()])
def test_cardinality(self, device, dtype, input_shape):
+ if dtype == torch.bfloat16:
+ pytest.skip("torch has no complex bfloat16 dtype, which So2 stores its rotation in")
t_input_shape = (*input_shape, 2)
z = torch.randn((*input_shape, 2), dtype=dtype, device=device)
t = torch.randn(t_input_shape, dtype=dtype, device=device)
@@ -70,6 +72,10 @@ class TestSe2(BaseTester):
@pytest.mark.parametrize("batch_size", [1, 2, 5])
def test_exception(self, device, dtype, batch_size):
+ # A bfloat16 identity raises TypeCheckError, a TypeError, so the TypeError check below would pass for
+ # the wrong reason; test_bfloat16_rotation_raises pins that error instead.
+ if dtype == torch.bfloat16:
+ pytest.skip("torch has no complex bfloat16 dtype, which So2 stores its rotation in")
r = So2.random(batch_size)
t1 = torch.randn((batch_size, 1), dtype=dtype, device=device)
t2 = torch.randn((batch_size, 3), dtype=dtype, device=device)
@@ -132,6 +138,8 @@ class TestSe2(BaseTester):
@pytest.mark.parametrize("batch_size", [None, 1, 2, 5])
def test_init(self, device, dtype, batch_size):
+ if dtype == torch.bfloat16:
+ pytest.skip("torch has no complex bfloat16 dtype, which So2 stores its rotation in")
s1 = Se2.random(batch_size, device, dtype)
s2 = Se2(s1.r, s1.t)
assert isinstance(s2, Se2)
@@ -150,6 +158,8 @@ class TestSe2(BaseTester):
@pytest.mark.parametrize("batch_size", [None, 1, 2, 5])
def test_mul(self, device, dtype, batch_size):
+ if dtype == torch.bfloat16:
+ pytest.skip("torch has no complex bfloat16 dtype, which So2 stores its rotation in")
s1 = Se2.identity(batch_size, device, dtype)
s2 = Se2.random(batch_size, device, dtype)
s1_pose_s2 = s1 * s2
@@ -166,6 +176,8 @@ class TestSe2(BaseTester):
@pytest.mark.parametrize("batch_size", [None, 1, 2, 5])
def test_mul_vector(self, device, dtype, batch_size):
+ if dtype == torch.bfloat16:
+ pytest.skip("torch has no complex bfloat16 dtype, which So2 stores its rotation in")
s1 = Se2.identity(batch_size, device, dtype)
shape = () if batch_size is None else (batch_size,)
s2 = Se2(So2.identity(batch_size, device, dtype), Vector2.random(shape, device, dtype))
@@ -183,6 +195,8 @@ class TestSe2(BaseTester):
@pytest.mark.parametrize("batch_size", [None, 1, 2, 5])
def test_exp(self, device, dtype, batch_size):
+ if dtype == torch.bfloat16:
+ pytest.skip("torch has no complex bfloat16 dtype, which So2 stores its rotation in")
t = self._make_rand_data(device, dtype, (batch_size, 2))
theta = torch.zeros(batch_size if batch_size is not None else (), device=device, dtype=dtype)
s = Se2.exp(torch.cat((t, theta[..., None]), -1))
@@ -192,6 +206,8 @@ class TestSe2(BaseTester):
@pytest.mark.parametrize("batch_size", [None, 1, 2, 5])
def test_log(self, device, dtype, batch_size):
+ if dtype == torch.bfloat16:
+ pytest.skip("torch has no complex bfloat16 dtype, which So2 stores its rotation in")
t = self._make_rand_data(device, dtype, (batch_size, 2))
s = Se2(So2.identity(batch_size, device, dtype), t)
# V(0)^-1 is the identity, so the log of a pure translation is (t, 0) (#4924)
@@ -199,6 +215,8 @@ class TestSe2(BaseTester):
@pytest.mark.parametrize("batch_size", [None, 1, 2, 5])
def test_exp_log(self, device, dtype, batch_size):
+ if dtype == torch.bfloat16:
+ pytest.skip("torch has no complex bfloat16 dtype, which So2 stores its rotation in")
a = self._make_rand_data(device, dtype, (batch_size, 3))
b = Se2.exp(a).log()
self.assert_close(b, a, low_tolerance=True)
@@ -320,6 +338,8 @@ class TestSe2(BaseTester):
@pytest.mark.parametrize("batch_size", [None, 1, 2, 5])
def test_matrix(self, device, dtype, batch_size):
+ if dtype == torch.bfloat16:
+ pytest.skip("torch has no complex bfloat16 dtype, which So2 stores its rotation in")
theta = self._make_rand_data(device, dtype, (batch_size,))
t = self._make_rand_data(device, dtype, (batch_size, 2))
s = So2.exp(theta)
@@ -329,6 +349,8 @@ class TestSe2(BaseTester):
@pytest.mark.parametrize("batch_size", [None, 1, 2, 5])
def test_from_matrix(self, device, dtype, batch_size):
+ if dtype == torch.bfloat16:
+ pytest.skip("torch has no complex bfloat16 dtype, which So2 stores its rotation in")
theta = self._make_rand_data(device, dtype, (batch_size,))
t = self._make_rand_data(device, dtype, (batch_size, 2))
s = So2.exp(theta)
@@ -342,6 +364,8 @@ class TestSe2(BaseTester):
@pytest.mark.parametrize("batch_size", [None, 1, 2, 5])
def test_inverse(self, device, batch_size, dtype):
+ if dtype == torch.bfloat16:
+ pytest.skip("torch has no complex bfloat16 dtype, which So2 stores its rotation in")
s = Se2.random(batch_size, device, dtype)
s_in_in = s.inverse().inverse()
self.assert_close(s_in_in.so2.z.real, s.so2.z.real)
@@ -350,6 +374,8 @@ class TestSe2(BaseTester):
@pytest.mark.parametrize("batch_size", [None, 1, 2, 5])
def test_random(self, device, dtype, batch_size):
+ if dtype == torch.bfloat16:
+ pytest.skip("torch has no complex bfloat16 dtype, which So2 stores its rotation in")
s = So2.random(batch_size=batch_size, device=device, dtype=dtype)
t = self._make_rand_data(device, dtype, (batch_size, 2))
se2 = Se2(s, t)
@@ -372,6 +398,8 @@ class TestSe2(BaseTester):
@pytest.mark.parametrize("batch_size", [None, 1, 2, 5])
def test_trans(self, device, dtype, batch_size):
+ if dtype == torch.bfloat16:
+ pytest.skip("torch has no complex bfloat16 dtype, which So2 stores its rotation in")
trans = self._make_rand_data(device, dtype, (batch_size, 2))
x, y = trans[..., 0], trans[..., 1]
se2 = Se2.trans(x, y)
@@ -380,6 +408,8 @@ class TestSe2(BaseTester):
@pytest.mark.parametrize("batch_size", [None, 1, 2, 5])
def test_trans_x(self, device, dtype, batch_size):
+ if dtype == torch.bfloat16:
+ pytest.skip("torch has no complex bfloat16 dtype, which So2 stores its rotation in")
x = self._make_rand_data(device, dtype, (batch_size, 1)).squeeze(-1)
zs = torch.zeros_like(x)
se2 = Se2.trans_x(x)
@@ -388,6 +418,8 @@ class TestSe2(BaseTester):
@pytest.mark.parametrize("batch_size", [None, 1, 2, 5])
def test_trans_y(self, device, dtype, batch_size):
+ if dtype == torch.bfloat16:
+ pytest.skip("torch has no complex bfloat16 dtype, which So2 stores its rotation in")
y = self._make_rand_data(device, dtype, (batch_size, 1)).squeeze(-1)
zs = torch.zeros_like(y)
se2 = Se2.trans_y(y)
@@ -535,7 +567,30 @@ class TestSe2(BaseTester):
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_bfloat16_rotation_raises(self, device):
+ # Every Se2 builder goes through an So2 builder, which raises a kornia error naming bfloat16 because PyTorch
+ # has no complex bfloat16 dtype; torch.complex raised a RuntimeError there before. ``.bfloat16()`` on a
+ # built pose keeps working (test_bfloat16_module_state_is_closed_5913).
+ bf16 = torch.bfloat16
+ ones = torch.ones(2, device=device, dtype=bf16)
+ builders = {
+ "exp": lambda: Se2.exp(torch.ones(2, 3, device=device, dtype=bf16)),
+ "identity": lambda: Se2.identity(2, device, bf16),
+ "random": lambda: Se2.random(2, device, bf16),
+ "from_matrix": lambda: Se2.from_matrix(torch.eye(3, device=device, dtype=bf16)),
+ "trans": lambda: Se2.trans(ones, ones),
+ "trans_x": lambda: Se2.trans_x(ones),
+ "trans_y": lambda: Se2.trans_y(ones),
+ }
+ message = r"So2 stores its rotation as a complex tensor.*no complex bfloat16 dtype"
+ for name, build in builders.items():
+ with pytest.raises(TypeCheckError, match=message) as err:
+ build()
+ assert err.value.actual_type == bf16, name
+
def test_derived_state_moves_and_serializes(self, device, dtype):
+ if dtype == torch.bfloat16:
+ pytest.skip("torch has no complex bfloat16 dtype, which So2 stores its rotation in")
# 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.
v = torch.rand(2, 3, device=device, dtype=dtype, requires_grad=True)
diff --git a/tests/geometry/liegroup/test_se3.py b/tests/geometry/liegroup/test_se3.py
index 36048703e..829db2b1a 100644
--- a/tests/geometry/liegroup/test_se3.py
+++ b/tests/geometry/liegroup/test_se3.py
@@ -46,6 +46,24 @@ class TestSe3(BaseTester):
shape = [] if batch_size is None else [batch_size]
return torch.rand([*shape, dims], device=device, dtype=dtype)
+ def _assert_chains_agree(self, actual, expected, p, t1, t2):
+ """Compare two chains of point transforms through poses with translations t1 and t2 that meet at one point."""
+ if actual.dtype not in (torch.float16, torch.bfloat16):
+ self.assert_close(actual, expected)
+ return
+ # Every Se3 operation computes in float32 and rounds once (TestSe3HalfPrecision pins that). A rounded point or
+ # translation v moves the end of its chain by at most u |v| (u = eps / 2), since only rotations and sums follow
+ # it, and the rounded quaternion of s12 = s1^-1 * s2 turns each vector it rotates by at most 2 u |v|. For the
+ # longer pair, pt_in_s2 against s12^-1 * pt_in_s1, the roundings cost: s2^-1.t, u |t2|; pt_in_s2,
+ # u (|p| + |t2|); s1^-1.t, computed for pt_in_s1 and for s12, 2 u |t1|; pt_in_s1, u (|p| + |t1|); s12.t and
+ # s12^-1.t, u (|t1| + |t2|) each; the result, u (|p| + |t2|); and s12's quaternion, applied to pt_in_s1 and
+ # s12.t, 2 u (|p| + 2 |t1| + |t2|). That sums to u (5 |p| + 9 |t1| + 7 |t2|) <= 9 u S with
+ # S = |p| + |t1| + |t2|; the other pair sums to u (5 |p| + 5 |t1| + 5 |t2|). The default half tolerance, about
+ # 2 u, does not cover either.
+ u = torch.finfo(actual.dtype).eps / 2
+ s = sum(x.detach().cpu().double().norm(dim=-1) for x in (p, t1, t2)).max().item()
+ self.assert_close(actual.detach().cpu().double(), expected.detach().cpu().double(), rtol=0.0, atol=9 * u * s)
+
def test_smoke(self, device, dtype):
q = Quaternion.from_coeffs(1.0, 0.0, 0.0, 0.0)
q = q.to(device, dtype)
@@ -161,8 +179,9 @@ class TestSe3(BaseTester):
pt_in_s2 = world_pose_s2.inverse() * pt_in_world
pt_in_s1_in_s2 = s1_pose_s2.inverse() * pt_in_s1
pt_in_s2_in_s1 = s1_pose_s2 * pt_in_s2
- self.assert_close(pt_in_s1, pt_in_s2_in_s1)
- self.assert_close(pt_in_s2, pt_in_s1_in_s2)
+ translations = (world_pose_s1.t, world_pose_s2.t)
+ self._assert_chains_agree(pt_in_s1, pt_in_s2_in_s1, pt_in_world, *translations)
+ self._assert_chains_agree(pt_in_s2, pt_in_s1_in_s2, pt_in_world, *translations)
@pytest.mark.parametrize("batch_size", [None, 1, 2, 5])
def test_mul_vector(self, device, dtype, batch_size):
@@ -183,8 +202,9 @@ class TestSe3(BaseTester):
if batch_size is not None:
zeros_vec = zeros_vec.repeat(batch_size, 1)
so3_expected = So3.identity(batch_size, device, dtype)
- self.assert_close(pt_in_s1, pt_in_s2_in_s1)
- self.assert_close(pt_in_s2, pt_in_s1_in_s2)
+ translations = (world_pose_s1.t, world_pose_s2.t)
+ self._assert_chains_agree(pt_in_s1, pt_in_s2_in_s1, pt_in_world, *translations)
+ self._assert_chains_agree(pt_in_s2, pt_in_s1_in_s2, pt_in_world, *translations)
self.assert_close(s3s4.r.q.data, s4.r.q.data)
self.assert_close(s3s4.t, s4.t)
self.assert_close(s4s4inv.r.q.data, so3_expected.q.data)
@@ -692,3 +712,81 @@ class TestSe3(BaseTester):
assert t.min() >= 0, (t.min(), t.max())
assert t.max() <= 1, (t.min(), t.max())
assert 0.45 < t.mean() < 0.55, t.mean()
+
+
+class TestSe3HalfPrecision(BaseTester):
+ # g * p and a * b compute in float32 for float16/bfloat16 inputs and round once to the input dtype, and the
+ # rotation follows So3 (TestSo3HalfPrecision). Evaluated in half precision, the chains of test_mul, test_mul_point
+ # and test_mul_vector drifted past their 1-2 unit tolerances.
+
+ @staticmethod
+ def _poses(device, dtype, n):
+ # translations in [-0.5, 0.5): every output below stays under 2 in magnitude
+ a = Se3(So3.random(n, device, dtype), torch.rand(n, 3, device=device, dtype=dtype) - 0.5)
+ b = Se3(So3.random(n, device, dtype), torch.rand(n, 3, device=device, dtype=dtype) - 0.5)
+ return a, b, torch.rand(n, 3, device=device, dtype=dtype) - 0.5
+
+ @staticmethod
+ def _cast(s, dtype):
+ """The same pose in ``dtype``; a float64 copy goes to the CPU, since MPS has no float64."""
+ q, t = s.r.q.data, s.t
+ if dtype == torch.float64:
+ q, t = q.cpu(), t.cpu()
+ return Se3(So3(Quaternion(q.to(dtype))), t.to(dtype))
+
+ def test_float32_and_float64_are_evaluated_in_their_own_dtype(self, device, dtype):
+ if dtype not in (torch.float32, torch.float64):
+ pytest.skip("float16 and bfloat16 are computed in float32 (test_half_precision_rounds_float32_once)")
+ a, b, p = self._poses(device, dtype, 5)
+ # bit for bit the group formulas in the input dtype, with no detour through another dtype
+ assert torch.equal(a * p, a.r * p + a.t)
+ assert torch.equal((a * Vector3(p)).data, a.r * p + a.t)
+ assert torch.equal((a * b).t, a.t + a.r * b.t)
+ assert torch.equal((a * b).r.q.data, (a.r * b.r).q.data)
+ assert torch.equal(a.inverse().t, a.r.inverse() * (-1 * a.t))
+ assert torch.equal(a.matrix()[..., :3, :3], a.r.matrix())
+
+ def test_half_precision_rounds_float32_once(self, device, dtype):
+ if dtype not in (torch.float16, torch.bfloat16):
+ pytest.skip("only float16 and bfloat16 inputs are computed in float32")
+ a, b, p = self._poses(device, dtype, 5)
+ a32, b32 = self._cast(a, torch.float32), self._cast(b, torch.float32)
+ for actual, wide in (
+ (a * p, a32 * p.float()),
+ ((a * Vector3(p)).data, a32 * p.float()),
+ ((a * b).t, (a32 * b32).t),
+ ((a * b).r.q.data, (a32 * b32).r.q.data),
+ (a.inverse().t, a32.inverse().t),
+ (a.matrix(), a32.matrix()),
+ ):
+ assert actual.dtype == dtype
+ assert torch.equal(actual, wide.to(dtype))
+
+ def test_half_precision_matches_float64_within_one_rounding(self, device, dtype):
+ if dtype not in (torch.float16, torch.bfloat16):
+ pytest.skip("float32 and float64 are evaluated in their own dtype")
+ # The reference is float64 from the same rounded inputs. Every output is below 2 in magnitude, where one
+ # rounding costs at most eps / 2 (plus a float32 error far below it); evaluated in half precision, g * p
+ # rounded the rotated point and then the sum.
+ eps = torch.finfo(dtype).eps
+ a, b, p = self._poses(device, dtype, 1000)
+ a64, b64, p64 = self._cast(a, torch.float64), self._cast(b, torch.float64), p.cpu().double()
+ self.assert_close((a * p).cpu().double(), a64 * p64, rtol=0.0, atol=eps)
+ self.assert_close((a * b).t.cpu().double(), (a64 * b64).t, rtol=0.0, atol=eps)
+ self.assert_close(a.inverse().t.cpu().double(), a64.inverse().t, rtol=0.0, atol=eps)
+
+ def test_half_precision_backward(self, device, dtype):
+ if dtype not in (torch.float16, torch.bfloat16):
+ pytest.skip("float32 and float64 gradients are covered by test_gradcheck")
+ a, b, p = self._poses(device, dtype, 4)
+ leaves = [a.r.q.data.detach(), a.t.detach(), b.t.detach(), p.detach()]
+ leaves = [x.requires_grad_(True) for x in leaves]
+ leaves32 = [x.detach().float().requires_grad_(True) for x in leaves]
+ for q, t, t_b, x in (leaves, leaves32):
+ s = Se3(So3(Quaternion(q)), t)
+ s_b = Se3(Quaternion(b.r.q.data.to(q.dtype)), t_b)
+ ((s * x).sum() + (s * s_b).t.sum() + s.inverse().t.sum() + s.matrix().sum()).backward()
+ for grad, grad32 in zip((x.grad for x in leaves), (x.grad for x in leaves32)):
+ assert grad.dtype == dtype
+ assert bool(torch.isfinite(grad).all())
+ self.assert_close(grad, grad32.to(dtype), low_tolerance=True)
diff --git a/tests/geometry/liegroup/test_so2.py b/tests/geometry/liegroup/test_so2.py
index e40b72f37..bff54e1b1 100644
--- a/tests/geometry/liegroup/test_so2.py
+++ b/tests/geometry/liegroup/test_so2.py
@@ -87,6 +87,24 @@ class TestSo2(BaseTester):
assert isinstance(So2.from_matrix(a.matrix().detach()), So2)
assert all(s.z.is_complex() for s in (a, a * b, a.inverse()))
+ def test_bfloat16_rotation_raises(self, device):
+ # PyTorch has no complex bfloat16 dtype, so each builder that would store a bfloat16 rotation raises a kornia
+ # error naming the dtype; torch.complex raised a RuntimeError there before. A built So2 keeps its complex
+ # precision under ``.bfloat16()`` (test_bfloat16_conversion_keeps_the_rotation_4923).
+ bf16 = torch.bfloat16
+ builders = {
+ "exp": lambda: So2.exp(torch.tensor([0.3, -0.4], device=device, dtype=bf16)),
+ "identity": lambda: So2.identity(2, device, bf16),
+ "unbatched identity": lambda: So2.identity(device=device, dtype=bf16),
+ "random": lambda: So2.random(2, device, bf16),
+ "from_matrix": lambda: So2.from_matrix(torch.eye(2, device=device, dtype=bf16)),
+ }
+ message = r"So2 stores its rotation as a complex tensor.*no complex bfloat16 dtype"
+ for name, build in builders.items():
+ with pytest.raises(TypeCheckError, match=message) as err:
+ build()
+ assert err.value.actual_type == bf16, name
+
@pytest.mark.parametrize("cdtype", [torch.cfloat, torch.cdouble])
def test_smoke(self, device, cdtype):
z = torch.randn(2, 1, dtype=cdtype, device=device)
@@ -98,6 +116,8 @@ class TestSo2(BaseTester):
@pytest.mark.parametrize("input_shape", [(1,), (2,), (5,), ()])
@pytest.mark.parametrize("cdtype", [torch.cfloat, torch.cdouble])
def test_cardinality(self, device, dtype, input_shape, cdtype):
+ if dtype == torch.bfloat16:
+ pytest.skip("torch has no complex bfloat16 dtype, which So2 stores its rotation in")
z = torch.randn(input_shape, dtype=cdtype, device=device)
s = So2(z)
theta = torch.rand(input_shape, dtype=dtype, device=device)
@@ -111,6 +131,8 @@ class TestSo2(BaseTester):
@pytest.mark.parametrize("input_shape", [(1, 2, 2), (2, 2, 2), (5, 2, 2), (2, 2)])
def test_matrix_cardinality(self, device, dtype, input_shape):
+ if dtype == torch.bfloat16:
+ pytest.skip("torch has no complex bfloat16 dtype, which So2 stores its rotation in")
matrix = torch.rand(input_shape, dtype=dtype, device=device)
matrix[..., 0, 1] = -matrix[..., 1, 0]
matrix[..., 1, 1] = matrix[..., 0, 0]
@@ -120,6 +142,10 @@ class TestSo2(BaseTester):
@pytest.mark.parametrize("batch_size", [1, 2, 5])
@pytest.mark.parametrize("cdtype", [torch.cfloat, torch.cdouble])
def test_exception(self, batch_size, device, dtype, cdtype):
+ # A bfloat16 identity raises TypeCheckError, a TypeError, so the TypeError check below would pass for
+ # the wrong reason; test_bfloat16_rotation_raises pins that error instead.
+ if dtype == torch.bfloat16:
+ pytest.skip("torch has no complex bfloat16 dtype, which So2 stores its rotation in")
z = torch.randn(batch_size, 2, dtype=cdtype, device=device)
with pytest.raises(ValueError):
assert So2(z)
@@ -155,6 +181,8 @@ class TestSo2(BaseTester):
@pytest.mark.parametrize("batch_size", [None, 1, 2, 5])
@pytest.mark.parametrize("cdtype", [torch.cfloat, torch.cdouble])
def test_init(self, device, dtype, batch_size, cdtype):
+ if dtype == torch.bfloat16:
+ pytest.skip("torch has no complex bfloat16 dtype, which So2 stores its rotation in")
z1 = self._make_rand_data(device, cdtype, (batch_size,))
z2 = self._make_rand_data(device, cdtype, (batch_size, 1))
z3_real = self._make_rand_data(device, dtype, (batch_size,))
@@ -185,6 +213,8 @@ class TestSo2(BaseTester):
@pytest.mark.parametrize("batch_size", [None, 1, 2, 5])
def test_mul(self, device, dtype, batch_size):
+ if dtype == torch.bfloat16:
+ pytest.skip("torch has no complex bfloat16 dtype, which So2 stores its rotation in")
s1 = So2.identity(batch_size, device, dtype)
z = self._make_rand_data(device, dtype, (batch_size, 2))
s2 = So2(torch.complex(z[..., 0], z[..., 1]))
@@ -201,6 +231,8 @@ class TestSo2(BaseTester):
@pytest.mark.parametrize("batch_size", [None, 1, 2, 5])
def test_mul_vector(self, device, dtype, batch_size):
+ if dtype == torch.bfloat16:
+ pytest.skip("torch has no complex bfloat16 dtype, which So2 stores its rotation in")
s1 = So2.identity(batch_size, device, dtype)
shape = () if batch_size is None else (batch_size,)
t1 = Vector2.random(shape, device, dtype)
@@ -210,6 +242,8 @@ class TestSo2(BaseTester):
@pytest.mark.parametrize("batch_size", [None, 1, 2, 5])
def test_exp(self, device, dtype, batch_size):
+ if dtype == torch.bfloat16:
+ pytest.skip("torch has no complex bfloat16 dtype, which So2 stores its rotation in")
theta = self._make_rand_data(device, dtype, (batch_size, 1))
s = So2.exp(theta)
self.assert_close(s.z.real, theta.flatten().cos())
@@ -224,6 +258,8 @@ class TestSo2(BaseTester):
@pytest.mark.parametrize("batch_size", [None, 1, 2, 5])
def test_exp_log(self, device, dtype, batch_size):
+ if dtype == torch.bfloat16:
+ pytest.skip("torch has no complex bfloat16 dtype, which So2 stores its rotation in")
theta = self._make_rand_data(device, dtype, (batch_size, 1))
self.assert_close(So2.exp(theta).log(), theta.flatten())
@@ -253,6 +289,8 @@ class TestSo2(BaseTester):
@pytest.mark.parametrize("batch_size", [None, 1, 2, 5])
def test_matrix(self, device, dtype, batch_size):
+ if dtype == torch.bfloat16:
+ pytest.skip("torch has no complex bfloat16 dtype, which So2 stores its rotation in")
theta = self._make_rand_data(device, dtype, (batch_size,))
t = self._make_rand_data(device, dtype, (batch_size, 2))
s = So2.exp(theta)
@@ -262,6 +300,8 @@ class TestSo2(BaseTester):
@pytest.mark.parametrize("batch_size", [None, 1, 2, 5])
def test_from_matrix(self, device, dtype, batch_size):
+ if dtype == torch.bfloat16:
+ pytest.skip("torch has no complex bfloat16 dtype, which So2 stores its rotation in")
matrix = torch.eye(2, device=device, dtype=dtype)
if batch_size is not None:
matrix = matrix.repeat(batch_size, 1, 1)
@@ -285,6 +325,8 @@ class TestSo2(BaseTester):
@pytest.mark.parametrize("batch_size", [None, 1, 2, 5])
def test_random(self, device, dtype, batch_size):
+ if dtype == torch.bfloat16:
+ pytest.skip("torch has no complex bfloat16 dtype, which So2 stores its rotation in")
s = So2.random(batch_size=batch_size, device=device, dtype=dtype)
s_in_s = s.inverse() * s
i = So2.identity(batch_size=batch_size, device=device, dtype=dtype)
@@ -314,6 +356,8 @@ class TestSo2(BaseTester):
@pytest.mark.parametrize("batch_size", [None, 1, 2, 5])
def test_adjoint(self, device, dtype, batch_size):
+ if dtype == torch.bfloat16:
+ pytest.skip("torch has no complex bfloat16 dtype, which So2 stores its rotation in")
s = So2.identity(batch_size, device=device, dtype=dtype)
self.assert_close(s.matrix(), s.adjoint())
@@ -330,6 +374,8 @@ class TestSo2(BaseTester):
assert "_z" in s.state_dict()
def test_derived_state_moves_and_serializes(self, device, dtype):
+ if dtype == torch.bfloat16:
+ pytest.skip("torch has no complex bfloat16 dtype, which So2 stores its rotation in")
theta = torch.rand(2, device=device, dtype=dtype, requires_grad=True)
s = So2.exp(theta)
assert s.z.grad_fn is not None
diff --git a/tests/geometry/liegroup/test_so3.py b/tests/geometry/liegroup/test_so3.py
index ac22af468..05d51ef80 100644
--- a/tests/geometry/liegroup/test_so3.py
+++ b/tests/geometry/liegroup/test_so3.py
@@ -728,3 +728,83 @@ class TestSo3Conventions(BaseTester):
assert result.missing_keys == ["_q._data"]
assert result.unexpected_keys == []
self.assert_close(rotation.q.data, torch.tensor([[1.0, 0.0, 0.0, 0.0]], device=device, dtype=dtype))
+
+
+def _quaternion_rotate(q: Quaternion, p: torch.Tensor) -> torch.Tensor:
+ """q p q* for the unit direction of q, evaluated in the input dtype."""
+ q = q.normalize()
+ return (q * Quaternion(torch.cat((torch.zeros_like(p[..., :1]), p), -1)) * q.conj()).vec
+
+
+def _quaternion_matrix(q: Quaternion) -> torch.Tensor:
+ """The rotation matrix of So3.matrix's docstring for the unit direction of q, evaluated in the input dtype."""
+ q = q.normalize()
+ w, x, y, z = q.w[..., None], q.x[..., None], q.y[..., None], q.z[..., None]
+ row0 = torch.cat((1 - 2 * y**2 - 2 * z**2, 2 * x * y - 2 * z * w, 2 * x * z + 2 * y * w), -1)
+ row1 = torch.cat((2 * x * y + 2 * z * w, 1 - 2 * x**2 - 2 * z**2, 2 * y * z - 2 * x * w), -1)
+ row2 = torch.cat((2 * x * z - 2 * y * w, 2 * y * z + 2 * x * w, 1 - 2 * x**2 - 2 * y**2), -1)
+ return torch.stack((row0, row1, row2), -2)
+
+
+class TestSo3HalfPrecision(BaseTester):
+ # matrix() and s * x compute in float32 for float16/bfloat16 inputs and round once to the input dtype. Evaluated
+ # in half precision, their ~10 roundings drifted 3-6 units of roundoff from the exact result, and chains of them
+ # missed the 1-2 unit tolerances of test_ortho and Se3's test_mul* tests.
+
+ def test_float32_and_float64_are_evaluated_in_their_own_dtype(self, device, dtype):
+ if dtype not in (torch.float32, torch.float64):
+ pytest.skip("float16 and bfloat16 are computed in float32 (test_half_precision_rounds_float32_once)")
+ a, b = So3.random(5, device, dtype), So3.random(5, device, dtype)
+ p = torch.rand(5, 3, device=device, dtype=dtype)
+ # bit for bit the quaternion formulas in the input dtype, with no detour through another dtype
+ assert torch.equal(a.matrix(), _quaternion_matrix(a.q))
+ assert torch.equal((a * b).q.data, (a.q * b.q).data)
+ assert torch.equal(a * p, _quaternion_rotate(a.q, p))
+ assert torch.equal((a * Vector3(p)).data, _quaternion_rotate(a.q, p))
+
+ def test_half_precision_rounds_float32_once(self, device, dtype):
+ if dtype not in (torch.float16, torch.bfloat16):
+ pytest.skip("only float16 and bfloat16 inputs are computed in float32")
+ a, b = So3.random(5, device, dtype), So3.random(5, device, dtype)
+ p = torch.rand(5, 3, device=device, dtype=dtype)
+ a32, b32 = So3(Quaternion(a.q.data.float())), So3(Quaternion(b.q.data.float()))
+ for actual, wide in (
+ (a.matrix(), a32.matrix()),
+ (a.adjoint(), a32.adjoint()),
+ ((a * b).q.data, (a32 * b32).q.data),
+ (a * p, a32 * p.float()),
+ ((a * Vector3(p)).data, a32 * p.float()),
+ ):
+ assert actual.dtype == dtype
+ assert torch.equal(actual, wide.to(dtype))
+
+ def test_half_precision_matches_float64_within_one_rounding(self, device, dtype):
+ if dtype not in (torch.float16, torch.bfloat16):
+ pytest.skip("float32 and float64 are evaluated in their own dtype")
+ # The reference is float64 from the same rounded inputs. Every output is below 2 in magnitude, where one
+ # rounding costs at most eps / 2 (plus a float32 error far below it); evaluated in half precision, matrix() and
+ # s * p reached 3 eps.
+ eps = torch.finfo(dtype).eps
+ a, b = So3.random(1000, device, dtype), So3.random(1000, device, dtype)
+ p = 2 * torch.rand(1000, 3, device=device, dtype=dtype) - 1
+ a64 = So3(Quaternion(a.q.data.cpu().double()))
+ b64 = So3(Quaternion(b.q.data.cpu().double()))
+ p64 = p.cpu().double()
+ self.assert_close(a.matrix().cpu().double(), a64.matrix(), rtol=0.0, atol=eps)
+ self.assert_close((a * b).q.data.cpu().double(), (a64 * b64).q.data, rtol=0.0, atol=eps)
+ self.assert_close((a * p).cpu().double(), a64 * p64, rtol=0.0, atol=eps)
+
+ def test_half_precision_backward(self, device, dtype):
+ if dtype not in (torch.float16, torch.bfloat16):
+ pytest.skip("float32 and float64 gradients are covered by test_gradcheck")
+ data = So3.random(4, device, dtype).q.data.detach().requires_grad_(True)
+ p = torch.rand(4, 3, device=device, dtype=dtype, requires_grad=True)
+ data32 = data.detach().float().requires_grad_(True)
+ p32 = p.detach().float().requires_grad_(True)
+ for q, x in ((data, p), (data32, p32)):
+ s = So3(Quaternion(q))
+ ((s * x).sum() + s.matrix().sum() + (s * s).q.data.sum()).backward()
+ for grad, grad32 in ((data.grad, data32.grad), (p.grad, p32.grad)):
+ assert grad.dtype == dtype
+ assert bool(torch.isfinite(grad).all())
+ self.assert_close(grad, grad32.to(dtype), low_tolerance=True)
diff --git a/tests/geometry/test_pose.py b/tests/geometry/test_pose.py
index d7478553e..425ad22e3 100644
--- a/tests/geometry/test_pose.py
+++ b/tests/geometry/test_pose.py
@@ -75,18 +75,21 @@ class TestNamedPose(BaseTester):
assert isinstance(b_from_a, NamedPose)
assert isinstance(b_from_a.pose, Se3)
- b_from_a_rotation = So2.random(device=device, dtype=dtype)
- b_from_a_translation = torch.tensor([1.0, 2.0], device=device, dtype=dtype)
- b_from_a = NamedPose.from_rt(b_from_a_rotation, b_from_a_translation, frame_src="frame_a", frame_dst="frame_b")
- assert isinstance(b_from_a, NamedPose)
- assert isinstance(b_from_a.pose, Se2)
-
b_from_a_rotation = torch.eye(3, device=device, dtype=dtype)
b_from_a_translation = torch.tensor([1.0, 2.0, 3.0], device=device, dtype=dtype)
b_from_a = NamedPose.from_rt(b_from_a_rotation, b_from_a_translation, frame_src="frame_a", frame_dst="frame_b")
assert isinstance(b_from_a, NamedPose)
assert isinstance(b_from_a.pose, Se3)
+ # the Se2 poses below cannot be built in bfloat16; test_se2_pose_in_bfloat16_raises pins that error
+ if dtype == torch.bfloat16:
+ pytest.skip("torch has no complex bfloat16 dtype, which So2 stores its rotation in")
+ b_from_a_rotation = So2.random(device=device, dtype=dtype)
+ b_from_a_translation = torch.tensor([1.0, 2.0], device=device, dtype=dtype)
+ b_from_a = NamedPose.from_rt(b_from_a_rotation, b_from_a_translation, frame_src="frame_a", frame_dst="frame_b")
+ assert isinstance(b_from_a, NamedPose)
+ assert isinstance(b_from_a.pose, Se2)
+
b_from_a_rotation = torch.eye(2, device=device, dtype=dtype)
b_from_a_translation = torch.tensor([1.0, 2.0], device=device, dtype=dtype)
b_from_a = NamedPose.from_rt(b_from_a_rotation, b_from_a_translation, frame_src="frame_a", frame_dst="frame_b")
@@ -159,6 +162,9 @@ class TestNamedPose(BaseTester):
assert isinstance(b_from_a, NamedPose)
assert isinstance(b_from_a.pose, Se3)
+ # the Se2 pose below cannot be built in bfloat16; test_se2_pose_in_bfloat16_raises pins that error
+ if dtype == torch.bfloat16:
+ pytest.skip("torch has no complex bfloat16 dtype, which So2 stores its rotation in")
b_from_a_matrix = torch.eye(3, device=device, dtype=dtype)
b_from_a = NamedPose.from_matrix(b_from_a_matrix, frame_src="frame_a", frame_dst="frame_b")
point_in_a = torch.tensor([1.0, 2.0], device=device, dtype=dtype)
@@ -167,6 +173,20 @@ class TestNamedPose(BaseTester):
assert isinstance(b_from_a, NamedPose)
assert isinstance(b_from_a.pose, Se2)
+ def test_se2_pose_in_bfloat16_raises(self, device):
+ # So2 stores a complex rotation and PyTorch has no complex bfloat16 dtype, so a bfloat16 Se2 pose raises
+ # kornia's error naming the dtype (torch.complex raised a RuntimeError before). A pose built in float32 and
+ # converted with ``.bfloat16()`` keeps its complex rotation and composes as usual.
+ bf16 = torch.bfloat16
+ with pytest.raises(TypeCheckError, match=r"no complex bfloat16"):
+ NamedPose.from_rt(torch.eye(2, device=device, dtype=bf16), torch.ones(2, device=device, dtype=bf16))
+ with pytest.raises(TypeCheckError, match=r"no complex bfloat16"):
+ NamedPose.from_matrix(torch.eye(3, device=device, dtype=bf16))
+ converted = Se2.exp(torch.tensor([0.5, -1.0, 0.3], device=device)).bfloat16()
+ b_from_a = NamedPose(converted, frame_src="a", frame_dst="b")
+ assert b_from_a.translation.dtype == bf16
+ assert isinstance((b_from_a.inverse() * b_from_a).pose, Se2)
+
def test_inverse(self, device, dtype):
b_from_a = NamedPose(
Se3.trans_x(torch.tensor([1.0], device=device, dtype=dtype)), frame_src="frame_a", frame_dst="frame_b"