π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
fix(geometry): integer poses keep their dtype on CUDA (#6096)
Dmytro Mishkin43fec2f83b61
diff --git a/changelog.d/6096.fixed.md b/changelog.d/6096.fixed.mdnew file mode 100644index 000000000..6b00439d7--- /dev/null+++ b/changelog.d/6096.fixed.md@@ -0,0 +1 @@+`camtoworld_to_worldtocam_Rt`, `worldtocam_to_camtoworld_Rt`, `camtoworld_graphics_to_vision_4x4` and `camtoworld_vision_to_graphics_4x4` now return a result in the input's dtype for `uint8`, `int8`, `int16`, `int32` and `int64` input on CUDA, as they already did on the CPU and MPS. CUDA has no integer matrix multiplication, so these functions used to raise `NotImplementedError: "baddbmm_cuda" not implemented for 'Long'` (or the matching error for another integer dtype) there.diff --git a/kornia/geometry/conversions.py b/kornia/geometry/conversions.pyindex 92072a4cb..3f3ff18ee 100644--- a/kornia/geometry/conversions.py+++ b/kornia/geometry/conversions.py@@ -2653,6 +2653,25 @@ def matrix4x4_to_Rt(extrinsics: torch.Tensor) -> tuple[torch.Tensor, torch.Tensoreturn R, t+def _integer_safe_matmul(a: torch.Tensor, b: torch.Tensor) -> torch.Tensor:+ # ``a @ b`` for the frame and pose functions that accept integer input (see the Rt_to_matrix4x4 Note).+ # CUDA has no integer matmul kernels ("baddbmm_cuda" not implemented for 'Long'), so a pair of one integer+ # dtype is multiplied out and summed instead, on every device so that CPU covers this branch too. Integer+ # products and sums wrap the same way in either form, so the result is bitwise CPU's integer ``a @ b``.+ # Every other pair (floating, complex, bool, the unsigned dtypes CPU matmul lacks, mixed dtypes) keeps+ # ``a @ b``, its rounding and its errors. So does a pair whose inner sizes differ, which only reaches here+ # with checks disabled: broadcasting would stretch a size-1 inner dimension where ``a @ b`` raises.+ if (+ a.dtype == b.dtype+ and a.dtype in [torch.uint8, torch.int8, torch.int16, torch.int32, torch.int64]+ and a.dim() > 1+ and b.dim() > 1+ and a.shape[-1] == b.shape[-2]+ ):+ return (a.unsqueeze(-1) * b.unsqueeze(-3)).sum(-2, dtype=a.dtype)+ return a @ b++def camtoworld_graphics_to_vision_4x4(extrinsics_graphics: torch.Tensor) -> torch.Tensor:r"""Convert a camera-to-world pose from the graphics frame (e.g. OpenGL) to the vision frame (e.g. OpenCV).@@ -2694,7 +2713,8 @@ def camtoworld_graphics_to_vision_4x4(extrinsics_graphics: torch.Tensor) -> torc.. warning::Integer input is not guarded: this function returns ``int64`` for an- ``int64`` matrix (on backends with integer batched matmul), while+ ``int64`` matrix on every device, CUDA (which has no integer matmul)+ included, while:func:`~kornia.geometry.conversions.camtoworld_graphics_to_vision_Rt`raises ``ValueError`` naming the unsupported dtype; see:func:`~kornia.geometry.conversions.Rt_to_matrix4x4`.@@ -2720,7 +2740,7 @@ def camtoworld_graphics_to_vision_4x4(extrinsics_graphics: torch.Tensor) -> torcdtype=extrinsics_graphics.dtype,device=extrinsics_graphics.device,)- return extrinsics_graphics @ invert_yz+ return _integer_safe_matmul(extrinsics_graphics, invert_yz)def camtoworld_graphics_to_vision_Rt(R: torch.Tensor, t: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor]:@@ -2813,7 +2833,7 @@ def camtoworld_vision_to_graphics_4x4(extrinsics_vision: torch.Tensor) -> torch.dtype=extrinsics_vision.dtype,device=extrinsics_vision.device,)- return extrinsics_vision @ invert_yz+ return _integer_safe_matmul(extrinsics_vision, invert_yz)def camtoworld_vision_to_graphics_Rt(R: torch.Tensor, t: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor]:@@ -2932,6 +2952,10 @@ def camtoworld_to_worldtocam_Rt(returns ``R`` exactly and ``t`` to rounding- the shapes are :math:`(B, 3, 3)` and :math:`(B, 3, 1)`, and ``R`` and ``t``must carry the same batch size: a mismatched pair raises ``ShapeError``+ - an ``R`` and ``t`` of one integer dtype (``uint8``, ``int8``, ``int16``,+ ``int32`` or ``int64``) are accepted on every device, CUDA (which has+ no integer matmul) included, and the result keeps that dtype, wrapping+ on overflow; ``check_rotation=True`` checks such an ``R`` in ``float32``.. warning::``R`` is **assumed** to be a rotation and by default this is not@@ -2971,7 +2995,7 @@ def camtoworld_to_worldtocam_Rt(_check_is_rotation(R, "camtoworld_to_worldtocam_Rt")R_inv = R.transpose(1, 2)- new_t: torch.Tensor = -R_inv @ t+ new_t: torch.Tensor = _integer_safe_matmul(-R_inv, t)return (R_inv, new_t)@@ -3025,7 +3049,7 @@ def worldtocam_to_camtoworld_Rt(_check_is_rotation(R, "worldtocam_to_camtoworld_Rt")R_inv = R.transpose(1, 2)- new_t: torch.Tensor = -R_inv @ t+ new_t: torch.Tensor = _integer_safe_matmul(-R_inv, t)return (R_inv, new_t)diff --git a/tests/geometry/test_conversions.py b/tests/geometry/test_conversions.pyindex c014f05e2..9a66aa06c 100644--- a/tests/geometry/test_conversions.py+++ b/tests/geometry/test_conversions.py@@ -28,6 +28,7 @@ from types import TracebackTypeimport numpy as npimport pytestimport torch+from torch.utils._python_dispatch import TorchDispatchModeimport korniafrom kornia.core.check import KORNIA_CHECK, KORNIA_CHECK_SHAPE, are_checks_enabled, disable_checks, enable_checks@@ -318,6 +319,24 @@ def _asymmetric_pose(device: torch.device, dtype: torch.dtype) -> tuple[torch.Te)+_MATMUL_OPS = frozenset({"mm", "bmm", "baddbmm", "addmm", "addbmm", "matmul", "mv", "dot"})+++class _RecordMatmulOps(TorchDispatchMode):+ # Records the matmul-family aten ops dispatched under it. CUDA has no integer kernel for any of them, so an+ # integer pose that reaches one raises there; recording the dispatch lets a CPU run, which has the kernels and+ # returns the right values regardless, see the same defect.+ def __init__(self) -> None:+ super().__init__()+ self.matmul_ops: set[str] = set()++ def __torch_dispatch__(self, func, types, args=(), kwargs=None):+ name = func.overloadpacket.__name__+ if name in _MATMUL_OPS:+ self.matmul_ops.add(name)+ return func(*args, **(kwargs or {}))++# Shared inputs for the same reason as _ASYMMETRIC_R above: pins cross-reference each other as# using "the same input", and a shared definition makes that true by construction instead of by# inspection of copied literals. Plain nested lists, materialised per test, no tensor shared.@@ -4644,9 +4663,9 @@ class TestRt2Extrinsics(BaseTester):def test_wart_int64_Rt_raises_while_4x4_and_pose_forms_accept_3959(self, device):_skip_if_dtype_unavailable(device, torch.int64)# Wart pin for kornia#3959: Rt_to_matrix4x4 and the two frame functions built on it reject an int64- # pose in a kornia guard, while the _4x4 forms of the same map and the pose pair return int64 wherever- # the backend has integer batched matmul, and fail inside torch elsewhere. Both sides are classified by- # _raised_by_a_kornia_guard, so the pin flips when the _4x4 side gains a guard or integers are promoted.+ # pose in a kornia guard, while the _4x4 forms of the same map and the pose pair return int64 on every+ # backend, CUDA (no integer matmul kernels) included. The pin flips when the _4x4 side gains a guard+ # (classified by _raised_by_a_kornia_guard), fails inside torch, or promotes integers.rotation = torch.eye(3, device=device, dtype=torch.int64)[None]translation = torch.ones(1, 3, 1, device=device, dtype=torch.int64)extrinsics = torch.eye(4, device=device, dtype=torch.int64)[None]@@ -4664,8 +4683,7 @@ class TestRt2Extrinsics(BaseTester):(camtoworld_to_worldtocam_Rt, (rotation, translation)),(worldtocam_to_camtoworld_Rt, (rotation, translation)),]- # Preserve both backend outcomes: an int64 result or a torch error is valid,- # while a new Kornia guard must still fail the pin after the except block.+ # Any raise fails the pin; a kornia guard fails it with the message naming the warning to update.for op, args in accepting:error: Exception | None = Nonetry:@@ -4676,11 +4694,11 @@ class TestRt2Extrinsics(BaseTester):assert not _raised_by_a_kornia_guard(error), (f"kornia#3959: {op.__name__} now rejects int64 input in a guard of its own -- update the warning")- else:- outputs = out if isinstance(out, tuple) else (out,)- assert all(o.dtype == torch.int64 for o in outputs), (- f"kornia#3959: {op.__name__} no longer returns int64 for int64 input"- )+ raise AssertionError(f"{op.__name__} no longer accepts int64 input on {device}") from error+ outputs = out if isinstance(out, tuple) else (out,)+ assert all(o.dtype == torch.int64 for o in outputs), (+ f"kornia#3959: {op.__name__} no longer returns int64 for int64 input"+ )@pytest.mark.parametrize(("op_name", "shapes"),@@ -4895,6 +4913,32 @@ class TestCamtoworldGraphicsToVision(BaseTester):rtol=0.0,)+ @pytest.mark.parametrize("op_name", ["camtoworld_graphics_to_vision_4x4", "camtoworld_vision_to_graphics_4x4"])+ @pytest.mark.parametrize("int_dtype", [torch.uint8, torch.int8, torch.int16, torch.int32, torch.int64])+ def test_integer_input_keeps_its_dtype(self, op_name, int_dtype, device):+ # An integer matrix is flipped in its own dtype on every device. CUDA has no integer matmul kernels, so+ # extrinsics @ diag(1, -1, -1, 1) used to raise there ("baddbmm_cuda" not implemented for 'Long') while+ # CPU returned this result. uint8 wraps the negated entries (-2 -> 254, -1 -> 255), like the+ # int64 -> uint8 cast of the literal below. No matmul kernel may be dispatched, so CPU, which has+ # integer matmul, fails where CUDA would.+ # Snippet used to generate expected (torch only, executed on cpu, int64 matmul):+ # M = [[1, 2, 0, 1], [0, 1, 1, 2], [3, 0, 1, 3], [0, 0, 0, 1]]+ # M @ diag(1, -1, -1, 1) -> [[1, -2, 0, 1], [0, -1, -1, 2], [3, 0, -1, 3], [0, 0, 0, 1]]+ op = getattr(kornia.geometry.conversions, op_name)+ extrinsics = torch.tensor([[[1, 2, 0, 1], [0, 1, 1, 2], [3, 0, 1, 3], [0, 0, 0, 1]]], device=device)++ recorder, float_recorder = _RecordMatmulOps(), _RecordMatmulOps()+ with recorder:+ flipped = op(extrinsics.to(int_dtype))+ with float_recorder: # the recorder sees the matmul that floating point input keeps+ op(extrinsics.to(torch.float32))++ expected = torch.tensor([[[1, -2, 0, 1], [0, -1, -1, 2], [3, 0, -1, 3], [0, 0, 0, 1]]], device=device)+ assert recorder.matmul_ops == set()+ assert float_recorder.matmul_ops != set()+ assert flipped.dtype == int_dtype+ assert torch.equal(flipped, expected.to(int_dtype))+@pytest.mark.parametrize(("forward_name", "backward_name"),[@@ -5134,6 +5178,60 @@ class TestCamtoworldRtToPoseRt(BaseTester):with pytest.raises(ValueError, match="not a rotation matrix"):fn(rotation, translation, check_rotation=True)+ @pytest.mark.parametrize("fn", [camtoworld_to_worldtocam_Rt, worldtocam_to_camtoworld_Rt])+ @pytest.mark.parametrize("int_dtype", [torch.uint8, torch.int8, torch.int16, torch.int32, torch.int64])+ def test_integer_input_keeps_its_dtype(self, fn, int_dtype, device):+ # An integer pose is computed in its own dtype on every device. CUDA has no integer matmul kernels, so+ # -R^T @ t used to raise there ("baddbmm_cuda" not implemented for 'Long') while CPU returned this+ # result. R is not a permutation, so every row of -R^T @ t sums several products; all values fit int8,+ # and uint8 wraps -(10, 4, 5) to (246, 252, 251), like the int64 -> uint8 cast of the literal below.+ # No matmul kernel may be dispatched, so CPU, which has integer matmul, fails where CUDA would.+ # Snippet used to generate expected (torch only, executed on cpu, int64 matmul):+ # R = [[1, 2, 0], [0, 1, 1], [3, 0, 1]], t = (1, 2, 3)+ # -R.transpose(1, 2) @ t -> (-10, -4, -5)+ rotation = torch.tensor([[[1, 2, 0], [0, 1, 1], [3, 0, 1]]], device=device).to(int_dtype)+ translation = torch.tensor([[[1], [2], [3]]], device=device).to(int_dtype)+ recorder, float_recorder = _RecordMatmulOps(), _RecordMatmulOps()+ with recorder:+ out_R, out_t = fn(rotation, translation)+ with float_recorder: # the recorder sees the matmul that floating point input keeps+ fn(rotation.to(torch.float32), translation.to(torch.float32))+ assert recorder.matmul_ops == set()+ assert float_recorder.matmul_ops != set()+ assert out_R.dtype == int_dtype+ assert out_t.dtype == int_dtype+ assert torch.equal(out_R, rotation.transpose(1, 2))+ assert torch.equal(out_t, torch.tensor([[[-10], [-4], [-5]]], device=device).to(int_dtype))++ @pytest.mark.parametrize("fn", [camtoworld_to_worldtocam_Rt, worldtocam_to_camtoworld_Rt])+ @pytest.mark.parametrize(("r_dtype", "t_dtype"), [(torch.int64, torch.float32), (torch.int32, torch.int64)])+ def test_mixed_dtype_pair_keeps_the_matmul_error(self, fn, r_dtype, t_dtype, device):+ # Only a pair of one integer dtype is summed in that dtype. A mixed pair keeps -R^T @ t and the error torch+ # raises for it, rather than an int64 R truncating a float32 t.+ rotation = torch.tensor(_ASYMMETRIC_R, device=device).to(r_dtype)+ translation = torch.tensor(_ASYMMETRIC_T, device=device).to(t_dtype)+ with pytest.raises(RuntimeError) as excinfo:+ fn(rotation, translation)+ assert not _raised_by_a_kornia_guard(excinfo.value)++ @pytest.mark.parametrize("fn", [camtoworld_to_worldtocam_Rt, worldtocam_to_camtoworld_Rt])+ @pytest.mark.parametrize("pair_dtype", [torch.int64, torch.float32])+ def test_row_translation_raises_with_checks_disabled(self, fn, pair_dtype, device):+ # disable_checks() turns the shape guards off, so a (1, 1, 3) row translation reaches -R^T @ t, whose inner+ # sizes (3 and 1) do not match. Integer input must raise there like float input does, instead of+ # broadcasting the size-1 dimension into a (1, 3, 3) "translation".+ rotation = torch.tensor(_ASYMMETRIC_R, device=device).to(pair_dtype)+ translation = torch.tensor(_ASYMMETRIC_T, device=device).to(pair_dtype).transpose(1, 2)+ checks_were_enabled = are_checks_enabled()+ disable_checks()+ try:+ with pytest.raises(RuntimeError) as excinfo:+ fn(rotation, translation)+ finally:+ if checks_were_enabled:+ enable_checks()+ assert not _raised_by_a_kornia_guard(excinfo.value)+@pytest.mark.parametrize("fn", [camtoworld_to_worldtocam_Rt, worldtocam_to_camtoworld_Rt])@pytest.mark.parametrize("matrix",