Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

fix(geometry): reject mismatched R/t batch sizes with ShapeError in conversions (#5265)

niukanen1ec095080ecbc
diff --git a/changelog.d/5265.breaking.md b/changelog.d/5265.breaking.md
new file mode 100644
index 000000000..1fa654198
--- /dev/null
+++ b/changelog.d/5265.breaking.md
@@ -0,0 +1,8 @@
+`Rt_to_matrix4x4`, `camtoworld_graphics_to_vision_Rt`, `camtoworld_vision_to_graphics_Rt`,
+`camtoworld_to_worldtocam_Rt` and `worldtocam_to_camtoworld_Rt`, and `ARKitQTVecs_to_ColmapQTVecs`, which calls two
+of them, now raise `ShapeError` (a `ValueError`) when `R` and `t` have different batch sizes; `disable_checks()` turns
+the check off like the other kornia checks. Previously `Rt_to_matrix4x4`, the two graphics/vision functions and
+`ARKitQTVecs_to_ColmapQTVecs` failed inside `torch.cat` with torch's `RuntimeError`, and the two worldtocam functions
+broadcast a batch-1 argument: `R` of batch 2 with `t` of batch 1 returned a `(2, 3, 3)`, `(2, 3, 1)` pose, and `R` of
+batch 1 with `t` of batch 2 returned `(1, 3, 3)` and `(2, 3, 1)`. Both calls now raise; any other mismatch used to
+raise `RuntimeError` from the matrix product.
diff --git a/kornia/geometry/conversions.py b/kornia/geometry/conversions.py
index e8a089b20..a144f6cfa 100644
--- a/kornia/geometry/conversions.py
+++ b/kornia/geometry/conversions.py
@@ -25,7 +25,7 @@ import torch
import torch.nn.functional as F
from kornia.core._compat import deprecated
-from kornia.core.check import KORNIA_CHECK, KORNIA_CHECK_SHAPE
+from kornia.core.check import KORNIA_CHECK, KORNIA_CHECK_SHAPE, ShapeError, are_checks_enabled
from kornia.core.utils import _inverse_3x3_closed_form, _torch_inverse_cast, is_compiling
__all__ = [
@@ -2476,19 +2476,14 @@ def Rt_to_matrix4x4(R: torch.Tensor, t: torch.Tensor) -> torch.Tensor:
function's
- shapes are strict: exactly :math:`(B, 3, 3)` and :math:`(B, 3, 1)`.
An unbatched ``(3, 3)``, a ``(B, 3)`` translation, a ``(B, 1, 3)``
- translation and extra leading dimensions each raise ``ShapeError``
+ translation and extra leading dimensions each raise ``ShapeError``;
+ ``R`` and ``t`` must also carry the same batch size: a mismatched
+ pair raises ``ShapeError`` too
- :func:`~kornia.geometry.conversions.matrix4x4_to_Rt` is the inverse:
``Rt -> 4x4 -> Rt`` is bitwise, while ``4x4 -> Rt -> 4x4`` is bitwise
only when the bottom row is already ``[0, 0, 0, 1]``, because
:func:`~kornia.geometry.conversions.matrix4x4_to_Rt` drops it
- .. warning::
- The batch sizes of ``R`` and ``t`` are not compared by a kornia guard:
- a mismatch raises from inside ``torch.cat``, while
- :func:`~kornia.geometry.conversions.camtoworld_to_worldtocam_Rt`
- broadcasts the same pair. Tracked in
- `#4774 <https://github.com/kornia/kornia/issues/4774>`_.
-
.. 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
@@ -2515,6 +2510,7 @@ def Rt_to_matrix4x4(R: torch.Tensor, t: torch.Tensor) -> torch.Tensor:
"""
KORNIA_CHECK_SHAPE(R, ["B", "3", "3"])
KORNIA_CHECK_SHAPE(t, ["B", "3", "1"])
+ _check_Rt_same_batch(R, t, "Rt_to_matrix4x4")
Rt = torch.cat([R, t], dim=2)
return convert_affinematrix_to_homography3d(Rt)
@@ -2650,8 +2646,8 @@ 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; the batch-size and integer-input warnings of
- :func:`~kornia.geometry.conversions.Rt_to_matrix4x4` apply
+ out, with the same-batch-size rule and the integer-input warning of
+ :func:`~kornia.geometry.conversions.Rt_to_matrix4x4`
- ``t`` is returned unchanged; only ``R`` has its second and third
columns negated
@@ -2675,6 +2671,7 @@ def camtoworld_graphics_to_vision_Rt(R: torch.Tensor, t: torch.Tensor) -> tuple[
"""
KORNIA_CHECK_SHAPE(R, ["B", "3", "3"])
KORNIA_CHECK_SHAPE(t, ["B", "3", "1"])
+ _check_Rt_same_batch(R, t, "camtoworld_graphics_to_vision_Rt")
mat4x4 = camtoworld_graphics_to_vision_4x4(Rt_to_matrix4x4(R, t))
return matrix4x4_to_Rt(mat4x4)
@@ -2764,10 +2761,28 @@ def camtoworld_vision_to_graphics_Rt(R: torch.Tensor, t: torch.Tensor) -> tuple[
"""
KORNIA_CHECK_SHAPE(R, ["B", "3", "3"])
KORNIA_CHECK_SHAPE(t, ["B", "3", "1"])
+ _check_Rt_same_batch(R, t, "camtoworld_vision_to_graphics_Rt")
mat4x4 = camtoworld_vision_to_graphics_4x4(Rt_to_matrix4x4(R, t))
return matrix4x4_to_Rt(mat4x4)
+def _check_Rt_same_batch(R: torch.Tensor, t: torch.Tensor, fn_name: str) -> None:
+ # KORNIA_CHECK_SHAPE validates each argument on its own; this guard compares the two batch
+ # sizes, so a mismatched (R, t) pair raises here with both shapes in the message. Like the
+ # KORNIA_CHECK helpers it follows disable_checks(): read the flag at call time, not a copy
+ # bound at import.
+ if not torch.jit.is_scripting():
+ if not are_checks_enabled():
+ return
+
+ if R.shape[0] != t.shape[0]:
+ raise ShapeError(
+ f"{fn_name}: R and t must have the same batch size, got {list(R.shape)} and {list(t.shape)}.",
+ actual_shape=list(t.shape),
+ expected_shape=[str(R.shape[0]), "3", "1"],
+ )
+
+
def _check_is_rotation(R: torch.Tensor, fn_name: str) -> None:
# Opt-in validation behind check_rotation=True; the default path stays unchecked.
# det has no half or integer kernels, so the check runs in float32 unless R is already float64.
@@ -2820,7 +2835,8 @@ def camtoworld_to_worldtocam_Rt(
- :func:`~kornia.geometry.conversions.worldtocam_to_camtoworld_Rt` is
the **same function** under the other name: applying either one twice
returns ``R`` exactly and ``t`` to rounding
- - the shapes are :math:`(B, 3, 3)` and :math:`(B, 3, 1)`
+ - 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``
.. warning::
``R`` is **assumed** to be a rotation and by default this is not
@@ -2830,13 +2846,6 @@ def camtoworld_to_worldtocam_Rt(
raise a ``ValueError`` instead, which also rejects reflections
(``det(R) < 0``).
- .. warning::
- The batch sizes of ``R`` and ``t`` are not checked: ``t`` is broadcast
- across ``R``, where :func:`~kornia.geometry.conversions.Rt_to_matrix4x4`
- raises, and ``R`` of batch 1 with ``t`` of batch 2 returns outputs of
- different batch sizes. Tracked in
- `#4774 <https://github.com/kornia/kornia/issues/4774>`_.
-
Args:
R: Rotation matrix, :math:`(B, 3, 3).`
t: Translation matrix :math:`(B, 3, 1)`.
@@ -2861,6 +2870,7 @@ def camtoworld_to_worldtocam_Rt(
"""
KORNIA_CHECK_SHAPE(R, ["B", "3", "3"])
KORNIA_CHECK_SHAPE(t, ["B", "3", "1"])
+ _check_Rt_same_batch(R, t, "camtoworld_to_worldtocam_Rt")
if check_rotation:
_check_is_rotation(R, "camtoworld_to_worldtocam_Rt")
@@ -2888,7 +2898,7 @@ def worldtocam_to_camtoworld_Rt(
- read the other way round here: the input ``t`` is the world-to-camera
translation and the returned ``-R^T t`` is the camera centre in world
coordinates
- - the shapes and both warnings are as documented there
+ - the shapes and the rotation warning are as documented there
Args:
R: Rotation matrix, :math:`(B, 3, 3).`
@@ -2914,6 +2924,7 @@ def worldtocam_to_camtoworld_Rt(
"""
KORNIA_CHECK_SHAPE(R, ["B", "3", "3"])
KORNIA_CHECK_SHAPE(t, ["B", "3", "1"])
+ _check_Rt_same_batch(R, t, "worldtocam_to_camtoworld_Rt")
if check_rotation:
_check_is_rotation(R, "worldtocam_to_camtoworld_Rt")
diff --git a/tests/geometry/test_conversions.py b/tests/geometry/test_conversions.py
index ee815442a..732b6dbae 100644
--- a/tests/geometry/test_conversions.py
+++ b/tests/geometry/test_conversions.py
@@ -4558,34 +4558,58 @@ class TestRt2Extrinsics(BaseTester):
def test_convention_shapes_are_strictly_batched(self, op_name, shapes, device):
# Convention pin: both functions go through KORNIA_CHECK_SHAPE and accept exactly
# (B, 3, 3) + (B, 3, 1) and (B, 4, 4) -- no unbatched form, no (B, 3) translation, no
- # transposed (B, 1, 3) translation, no extra leading batch dimensions. This is the strict
- # end of the family: camtoworld_to_worldtocam_Rt broadcasts a (1, 3, 1) translation across
- # a (2, 3, 3) rotation where Rt_to_matrix4x4 raises, which
- # test_wart_batch_size_mismatch_is_not_guarded_4774 below pins. Assertion policy and the
- # float32 hardcoding are documented once on the shared _assert_strictly_batched helper.
+ # transposed (B, 1, 3) translation, no extra leading batch dimensions. The same-batch
+ # rule for (R, t) pairs is pinned by test_convention_batch_size_mismatch_raises_4774
+ # below. Assertion policy and the float32 hardcoding are documented once on the shared
+ # _assert_strictly_batched helper.
_assert_strictly_batched(op_name, shapes, device)
- def test_wart_batch_size_mismatch_is_not_guarded_4774(self, device):
- # Wart pin for kornia#4774: no kornia guard compares the batch sizes of R and t.
- # Rt_to_matrix4x4 fails inside torch.cat, while camtoworld_to_worldtocam_Rt broadcasts the
- # same pair -- and with R of batch 1 and t of batch 2 returns outputs of different batch
- # sizes. Flips under either fix: a shared guard (the Rt_to_matrix4x4 failure becomes a
- # guard's, and the pose pair raises) or consistent broadcasting.
- rotation_batch_2 = torch.eye(3, device=device, dtype=torch.float32).expand(2, 3, 3)
- translation_batch_1 = torch.ones(1, 3, 1, device=device, dtype=torch.float32)
-
- with pytest.raises(Exception) as excinfo:
- Rt_to_matrix4x4(rotation_batch_2, translation_batch_1)
- assert not _raised_by_a_kornia_guard(excinfo.value), (
- "kornia#4774: Rt_to_matrix4x4 now rejects mismatched batch sizes in a guard of its own"
- )
-
- inverted_R, inverted_t = camtoworld_to_worldtocam_Rt(
- torch.eye(3, device=device, dtype=torch.float32)[None], torch.ones(2, 3, 1, device=device)
- )
- assert (inverted_R.shape[0], inverted_t.shape[0]) == (1, 2), (
- "kornia#4774: camtoworld_to_worldtocam_Rt no longer returns mismatched batch sizes"
- )
+ @pytest.mark.parametrize(
+ "op_name",
+ [
+ "Rt_to_matrix4x4",
+ "camtoworld_graphics_to_vision_Rt",
+ "camtoworld_vision_to_graphics_Rt",
+ "camtoworld_to_worldtocam_Rt",
+ "worldtocam_to_camtoworld_Rt",
+ ],
+ )
+ @pytest.mark.parametrize("batch_pair", [(2, 1), (1, 2)], ids=["R2-t1", "R1-t2"])
+ def test_convention_batch_size_mismatch_raises_4774(self, op_name, batch_pair, device):
+ # Convention pin: every (R, t) function in the family rejects a batch-size mismatch in a
+ # guard of its own -- a ShapeError naming the function and both shapes -- before torch.cat
+ # can fail or the matmul can broadcast. The graphics/vision pair calls Rt_to_matrix4x4,
+ # whose guard would raise too; matching the name pins each function's own guard.
+ ops = {
+ "Rt_to_matrix4x4": Rt_to_matrix4x4,
+ "camtoworld_graphics_to_vision_Rt": camtoworld_graphics_to_vision_Rt,
+ "camtoworld_vision_to_graphics_Rt": camtoworld_vision_to_graphics_Rt,
+ "camtoworld_to_worldtocam_Rt": camtoworld_to_worldtocam_Rt,
+ "worldtocam_to_camtoworld_Rt": worldtocam_to_camtoworld_Rt,
+ }
+ r_batch, t_batch = batch_pair
+ R = torch.eye(3, device=device, dtype=torch.float32).expand(r_batch, 3, 3)
+ t = torch.ones(t_batch, 3, 1, device=device, dtype=torch.float32)
+
+ with pytest.raises(ShapeError, match=f"^{op_name}: R and t must have the same batch size") as excinfo:
+ ops[op_name](R, t)
+ assert excinfo.value.actual_shape == [t_batch, 3, 1]
+ assert excinfo.value.expected_shape == [str(r_batch), "3", "1"]
+
+ def test_convention_batch_size_guard_follows_disable_checks_4774(self, device):
+ # Convention pin: the same-batch guard is a kornia check, so disable_checks() turns it off
+ # together with the KORNIA_CHECK_SHAPE calls before it, and the pair reaches torch.cat.
+ R = torch.eye(3, device=device, dtype=torch.float32).expand(2, 3, 3)
+ t = torch.ones(1, 3, 1, device=device, dtype=torch.float32)
+ checks_were_enabled = are_checks_enabled()
+ disable_checks()
+ try:
+ with pytest.raises(Exception) as excinfo:
+ Rt_to_matrix4x4(R, t)
+ finally:
+ if checks_were_enabled:
+ enable_checks()
+ assert not _raised_by_a_kornia_guard(excinfo.value)
class TestCamtoworldGraphicsToVision(BaseTester):
@@ -4850,8 +4874,8 @@ class TestCamtoworldRtToPoseRt(BaseTester):
)
def test_convention_shapes_are_strictly_batched(self, op_name, shapes, device):
# Convention pin: both functions accept exactly (B, 3, 3) + (B, 3, 1) -- no unbatched form,
- # no (B, 3) translation, no extra leading batch dimensions. A mismatched batch size is not
- # checked (kornia#4774, pinned in TestRt2Extrinsics).
+ # no (B, 3) translation, no extra leading batch dimensions. A mismatched batch size between
+ # R and t raises ShapeError (kornia#4774, pinned in TestRt2Extrinsics).
# Assertion policy and the float32 hardcoding are documented once on the shared
# _assert_strictly_batched helper.
_assert_strictly_batched(op_name, shapes, device)