π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
fix(geometry): clarify unsupported Rt packing dtypes (#5894)
Hsnb0376018f9f3
diff --git a/changelog.d/5894.fixed.md b/changelog.d/5894.fixed.mdnew file mode 100644index 000000000..55124d971--- /dev/null+++ b/changelog.d/5894.fixed.md@@ -0,0 +1 @@+`Rt_to_matrix4x4`, `camtoworld_graphics_to_vision_Rt` and `camtoworld_vision_to_graphics_Rt` raise `ValueError` naming the dtype when `R` and `t` promote to an integer or boolean dtype. They used to raise torch's `RuntimeError: result type Float can't be cast to the desired output type Long` (or `Int`, `Bool`, ...) from inside the 3x4 to 4x4 homography conversion, so code that caught that `RuntimeError` has to catch `ValueError` now. Pairs that promote to a floating point or complex dtype, mixed integer/floating pairs included, return the same matrices as before.diff --git a/kornia/geometry/conversions.py b/kornia/geometry/conversions.pyindex 7a36bad99..5a041ee77 100644--- a/kornia/geometry/conversions.py+++ b/kornia/geometry/conversions.py@@ -2500,12 +2500,12 @@ def Rt_to_matrix4x4(R: torch.Tensor, t: torch.Tensor) -> torch.Tensor:only when the bottom row is already ``[0, 0, 0, 1]``, because:func:`~kornia.geometry.conversions.matrix4x4_to_Rt` drops it- .. warning::- Integer input is not guarded: an ``int64`` ``(R, t)`` raises from inside- torch here and in the two ``camtoworld_*_Rt`` frame functions built on- it, while the ``_4x4`` frame functions and the- ``camtoworld_to_worldtocam_Rt`` pair return ``int64`` (on backends with- integer batched matmul). Tracked in+ Note:+ ``R`` and ``t`` must promote to a floating point or complex dtype;+ an integer or boolean pair raises ``ValueError`` naming its dtype.+ Mixed integer/floating inputs keep torch's promotion. The integer-safe+ ``_4x4`` frame functions and ``camtoworld_to_worldtocam_Rt`` keep their+ existing behavior; the broader dtype consistency question is tracked in`#3959 <https://github.com/kornia/kornia/issues/3959>`_.Args:@@ -2528,6 +2528,8 @@ def Rt_to_matrix4x4(R: torch.Tensor, t: torch.Tensor) -> torch.Tensor:KORNIA_CHECK_SHAPE(t, ["B", "3", "1"])_check_Rt_same_batch(R, t, "Rt_to_matrix4x4")Rt = torch.cat([R, t], dim=2)+ if not Rt.is_floating_point() and not Rt.is_complex():+ raise ValueError(f"R and t must promote to a floating point or complex dtype. Got {Rt.dtype}.")return convert_affinematrix_to_homography3d(Rt)@@ -2616,7 +2618,7 @@ def camtoworld_graphics_to_vision_4x4(extrinsics_graphics: torch.Tensor) -> torcInteger input is not guarded: this function returns ``int64`` for an``int64`` matrix (on backends with integer batched matmul), while:func:`~kornia.geometry.conversions.camtoworld_graphics_to_vision_Rt`- raises from inside torch. Tracked in+ raises ``ValueError`` naming the unsupported dtype. Tracked in`#3959 <https://github.com/kornia/kornia/issues/3959>`_; see:func:`~kornia.geometry.conversions.Rt_to_matrix4x4`.@@ -2662,7 +2664,7 @@ def camtoworld_graphics_to_vision_Rt(R: torch.Tensor, t: torch.Tensor) -> tuple[function and splits the result again, so the two paths agree bitwise.Only the lines below differ- the shapes are strictly :math:`(B, 3, 3)` and :math:`(B, 3, 1)` in and- out, with the same-batch-size rule and the integer-input warning of+ out, with the same-batch-size rule and the integer-input ``ValueError`` of:func:`~kornia.geometry.conversions.Rt_to_matrix4x4`- ``t`` is returned unchanged; only ``R`` has its second and thirdcolumns negateddiff --git a/tests/geometry/test_conversions.py b/tests/geometry/test_conversions.pyindex 0c47f2e47..85326874a 100644--- a/tests/geometry/test_conversions.py+++ b/tests/geometry/test_conversions.py@@ -185,8 +185,8 @@ def _raised_by_a_kornia_guard(err: BaseException) -> bool:# semantic -- it would miss `raise(RuntimeError(...))`, whose missing space before the# parenthesis is not a semantic difference.# Both directions are exercised: test_guard_classifier_reads_the_raising_instruction below- # covers the classifier itself, the #3960 convention pin asserts this is True (in any guard- # style), and the #3959 warts assert it is False.+ # covers the classifier itself, the #3960 convention pin and the Rt side of the int64 Rt wart+ # (#3959) assert this is True (in any guard style), and every other #3959 wart asserts it is False.# The instruction DECIDES; the type tuple is only the fallback for a frame whose instruction# cannot be read. ORing the two instead of falling back would make the instruction check# unreachable for exactly the types kornia's guards raise, so it would score any downstream@@ -4483,28 +4483,65 @@ class TestRt2Extrinsics(BaseTester):self.assert_close(extrinsics[0, :3, 3], torch.zeros(3, device=device, dtype=torch.float32), atol=0.0, rtol=0.0)+ @pytest.mark.parametrize(+ "requested_dtype", [torch.bool, torch.uint8, torch.int8, torch.int16, torch.int32, torch.int64]+ )+ def test_Rt_rejects_nonfloating_dtype_3959(self, device, requested_dtype):+ _skip_if_dtype_unavailable(device, requested_dtype)+ rotation = torch.eye(3, device=device).to(requested_dtype)[None]+ translation = torch.ones(1, 3, 1, device=device, dtype=requested_dtype)+ with pytest.raises(ValueError, match="R and t must promote to a floating point or complex dtype") as excinfo:+ Rt_to_matrix4x4(rotation, translation)+ assert str(excinfo.value).endswith(f"Got {requested_dtype}.")++ def test_Rt_names_the_promoted_dtype_3959(self, device):+ # uint8 and int8 promote to int16, the dtype of neither input, so the message must name the promoted dtype.+ rotation = torch.eye(3, device=device).to(torch.uint8)[None]+ translation = torch.ones(1, 3, 1, device=device, dtype=torch.int8)+ with pytest.raises(ValueError, match=r"Got torch\.int16\.$"):+ Rt_to_matrix4x4(rotation, translation)++ @pytest.mark.parametrize(+ "rotation_dtype,translation_dtype",+ [+ (torch.int64, torch.float32),+ (torch.bool, torch.float32),+ (torch.float32, torch.int64),+ (torch.float32, torch.float64),+ (torch.complex64, torch.float32),+ (torch.float32, torch.complex64),+ ],+ )+ def test_Rt_preserves_promoted_dtype_3959(self, device, rotation_dtype, translation_dtype):+ _skip_if_dtype_unavailable(device, rotation_dtype)+ _skip_if_dtype_unavailable(device, translation_dtype)+ try: # MPS (torch 2.14, macOS 26.5) has no kernel to cat complex with real tensors+ torch.cat([torch.zeros(1, device=device, dtype=d) for d in (rotation_dtype, translation_dtype)])+ except RuntimeError as err:+ pytest.skip(f"torch.cat cannot mix {rotation_dtype} and {translation_dtype} on {device}: {err}")+ rotation = torch.eye(3, device=device, dtype=rotation_dtype)[None]+ translation = torch.ones(1, 3, 1, device=device, dtype=translation_dtype)+ expected_dtype = torch.promote_types(rotation_dtype, translation_dtype)+ expected = torch.eye(4, device=device, dtype=expected_dtype)[None]+ expected[:, :3, 3:] = translation.to(expected_dtype)+ self.assert_close(Rt_to_matrix4x4(rotation, translation), expected, atol=0.0, rtol=0.0)+def test_wart_int64_Rt_raises_while_4x4_and_pose_forms_accept_3959(self, device):- # Wart pin for kornia#3959: no function in this family guards against an int64 pose.- # Rt_to_matrix4x4 and the two frame functions built on it fail inside torch (the appended- # float row cannot be cast to Long), while the _4x4 forms and the pose pair return int64- # wherever the backend has integer batched matmul, and fail inside torch elsewhere. Every- # failure is classified by _raised_by_a_kornia_guard rather than by its type or message, so- # the pin flips when a guard is added to either side or when integers are promoted.- # Snippet used to generate expected (torch only, executed on cpu):- # Rt_to_matrix4x4(eye(3, int64)[None], ones(1, 3, 1, int64)) -> RuntimeError- # camtoworld_graphics_to_vision_4x4(eye(4, int64)[None]).dtype -> torch.int64- # camtoworld_to_worldtocam_Rt(eye(3, int64)[None], ones(1, 3, 1, int64)) -> (int64, int64)+ _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.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]- # These calls fail inside torch with RuntimeError; the classifier still rejects a new Kornia guard.for op in (Rt_to_matrix4x4, camtoworld_graphics_to_vision_Rt, camtoworld_vision_to_graphics_Rt):- with pytest.raises(RuntimeError) as excinfo:+ with pytest.raises(+ ValueError, match="R and t must promote to a floating point or complex dtype"+ ) as excinfo:op(rotation, translation)- assert not _raised_by_a_kornia_guard(excinfo.value), (- f"kornia#3959: {op.__name__} now rejects int64 (R, t) in a guard of its own -- update the warning"- )+ assert _raised_by_a_kornia_guard(excinfo.value)accepting = [(camtoworld_graphics_to_vision_4x4, (extrinsics,)),