Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

fix(bbox): reject rank-4 input in infer_bbox_shape3d and bbox_to_mask3d (closes #4248) (#4351)

Dipak Chaudhari3c2047856ff9
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 11d596fa8..a51c8f2fb 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -393,6 +393,12 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
`ValueError`; it previously raised a `topk` `RuntimeError`, and under the per-image ranking it
would otherwise have silently disabled refinement instead. (#4256, #4350)
+* `infer_bbox_shape3d` and `bbox_to_mask3d` reject rank-4 `(B, N, 8, 3)` input with a `ShapeError`,
+ the way `infer_bbox_shape` and `bbox_to_mask` have since #4218. `validate_bbox3d` accepts the rank-4
+ form and reshapes internally, but both callers index dim 1 as the vertex axis, so the box axis was
+ read as the vertices: an out-of-bounds error with one box, and three `(1, 3)` tensors -- one value
+ per coordinate rather than per box -- with eight. (#4248, #4351)
+
* `RenderingDeFMO` (used by `DeFMO`) no longer crashes on a half-precision forward pass. Its rendering
time-steps (`times`) were a plain Python attribute, not a registered buffer, so `nn.Module.to()` never
moved it; `forward` re-derived `times`'s device from the input on every call but never its dtype, so
diff --git a/kornia/geometry/bbox.py b/kornia/geometry/bbox.py
index d0c00f0c8..9b74f24f4 100644
--- a/kornia/geometry/bbox.py
+++ b/kornia/geometry/bbox.py
@@ -99,7 +99,7 @@ def validate_bbox(boxes: torch.Tensor) -> bool:
def validate_bbox3d(boxes: torch.Tensor) -> bool:
- """Validate that a 3D box has equal inclusive edge extents along each axis, raising when it does not.
+ r"""Validate that a 3D box has equal inclusive edge extents along each axis, raising when it does not.
Convention:
Vertices use inclusive coordinates in the order front-top-left, front-top-right, front-bottom-right,
@@ -113,9 +113,9 @@ def validate_bbox3d(boxes: torch.Tensor) -> bool:
.. warning::
:func:`validate_bbox` returns ``False`` where this function raises; that inconsistency is tracked in
- `#4013 <https://github.com/kornia/kornia/issues/4013>`_. Rank-4 input passes this check but breaks
- :func:`infer_bbox_shape3d` and :func:`bbox_to_mask3d`, tracked in
- `#4248 <https://github.com/kornia/kornia/issues/4248>`_.
+ `#4013 <https://github.com/kornia/kornia/issues/4013>`_. Rank-4 input passes this check, but
+ :func:`infer_bbox_shape3d` and :func:`bbox_to_mask3d` reject it with
+ :class:`~kornia.core.exceptions.ShapeError`: flatten to :math:`(B \cdot N, 8, 3)` before calling them.
Args:
boxes: a tensor containing the coordinates of the bounding boxes to be extracted. The tensor must have the shape
@@ -226,9 +226,9 @@ def infer_bbox_shape3d(boxes: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor,
`#3934 <https://github.com/kornia/kornia/issues/3934>`_; the exclusive-export trap is
`#4009 <https://github.com/kornia/kornia/issues/4009>`_. Validation raises ``AssertionError`` rather than
returning ``False``, see `#4013 <https://github.com/kornia/kornia/issues/4013>`_. Batched :math:`(B, N, 8, 3)`
- input passes validation but is then indexed as if the box axis were the vertex axis, which raises an
- indexing error or returns wrong-shaped values depending on ``N``; flatten to :math:`(B \cdot N, 8, 3)`
- first. Tracked in `#4248 <https://github.com/kornia/kornia/issues/4248>`_.
+ input is rejected with :class:`~kornia.core.exceptions.ShapeError`, as the 2D helpers reject
+ :math:`(B, N, 4, 2)`; flatten to :math:`(B \cdot N, 8, 3)` first. :func:`validate_bbox3d` still accepts
+ the rank-4 form and reshapes internally, which is why the rejection lives here rather than there.
Args:
boxes: a tensor containing the coordinates of the bounding boxes to be extracted. The tensor must have the shape
@@ -262,6 +262,11 @@ def infer_bbox_shape3d(boxes: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor,
(tensor([31, 61]), tensor([21, 51]), tensor([11, 41]))
"""
+ # validate_bbox3d also accepts (B, N, 8, 3) and reshapes internally, but the
+ # indexing below reads dim 1 as the vertex axis, so a rank-4 input would be
+ # read as if the box axis were the vertices. Reject it here, the way #4218
+ # did for the 2D twin.
+ KORNIA_CHECK_SHAPE(boxes, ["N", "8", "3"])
validate_bbox3d(boxes)
left = torch.index_select(boxes, 1, torch.tensor([1, 2, 5, 6], device=boxes.device, dtype=torch.long))[:, :, 0]
@@ -365,7 +370,7 @@ def bbox_to_mask(boxes: torch.Tensor, width: int, height: int) -> torch.Tensor:
def bbox_to_mask3d(boxes: torch.Tensor, size: tuple[int, int, int]) -> torch.Tensor:
- """Convert 3D bounding boxes to masks. Covered area is 1. and the remaining is 0.
+ r"""Convert 3D bounding boxes to masks. Covered area is 1. and the remaining is 0.
Convention:
``size`` is ``(depth, height, width)`` and the mask comes back as :math:`(B, 1, depth, height, width)` in
@@ -384,8 +389,8 @@ def bbox_to_mask3d(boxes: torch.Tensor, size: tuple[int, int, int]) -> torch.Ten
`#4015 <https://github.com/kornia/kornia/issues/4015>`_. The ``float32`` output with a channel axis is
tracked in `#4250 <https://github.com/kornia/kornia/issues/4250>`_. Validation raises rather than returning
``False``, `#4013 <https://github.com/kornia/kornia/issues/4013>`_. Batched :math:`(B, N, 8, 3)` input passes
- validation and then raises an indexing or broadcasting error; flatten it first. Tracked in
- `#4248 <https://github.com/kornia/kornia/issues/4248>`_.
+ :func:`validate_bbox3d` but is rejected here with :class:`~kornia.core.exceptions.ShapeError`; flatten to
+ :math:`(B \cdot N, 8, 3)` first.
Args:
boxes: a tensor containing the coordinates of the bounding boxes to be extracted. The tensor must have the shape
@@ -434,6 +439,9 @@ def bbox_to_mask3d(boxes: torch.Tensor, size: tuple[int, int, int]) -> torch.Ten
[0., 0., 0., 0., 0.]]]]])
"""
+ # Same as infer_bbox_shape3d: boxes[:, 4, 2] below reads dim 1 as the vertex
+ # axis, which a rank-4 (B, N, 8, 3) input silently is not.
+ KORNIA_CHECK_SHAPE(boxes, ["B", "8", "3"])
validate_bbox3d(boxes)
D0, D1, D2 = size # get depth, height, width
diff --git a/kornia/geometry/boxes.py b/kornia/geometry/boxes.py
index d03532b1e..461cd61bf 100644
--- a/kornia/geometry/boxes.py
+++ b/kornia/geometry/boxes.py
@@ -1189,8 +1189,10 @@ class Boxes3D:
:func:`~kornia.geometry.bbox.validate_bbox` is `#4013 <https://github.com/kornia/kornia/issues/4013>`_, and
boxes built by :func:`~kornia.geometry.bbox.bbox_generator3d` measure one larger than requested,
`#4018 <https://github.com/kornia/kornia/issues/4018>`_. The :meth:`to_tensor` default-mode split with
- :class:`Boxes` is tracked in `#4251 <https://github.com/kornia/kornia/issues/4251>`_, and the rank-4 breakage
- of the free functions in `#4248 <https://github.com/kornia/kornia/issues/4248>`_. :meth:`to_mask` rejects
+ :class:`Boxes` is tracked in `#4251 <https://github.com/kornia/kornia/issues/4251>`_. The free functions
+ reject rank-4 input rather than misreading it, so flatten to :math:`(B \cdot N, 8, 3)` before calling
+ :func:`~kornia.geometry.bbox.infer_bbox_shape3d` or :func:`~kornia.geometry.bbox.bbox_to_mask3d`.
+ :meth:`to_mask` rejects
boxes that require grad even though :meth:`to_tensor` is differentiable; see the note on
:meth:`to_tensor`.
diff --git a/tests/geometry/test_bbox.py b/tests/geometry/test_bbox.py
index 25f740127..0c2f0e99e 100644
--- a/tests/geometry/test_bbox.py
+++ b/tests/geometry/test_bbox.py
@@ -616,40 +616,18 @@ class TestBbox3D(BaseTester):
self.assert_close(widths, torch.tensor([4.0], device=device, dtype=dtype), atol=0.0, rtol=0.0)
@pytest.mark.parametrize("num_boxes", [1, 8])
- def test_wart_rank4_input_passes_validate_bbox3d_then_breaks_the_3d_helpers_4248(self, device, dtype, num_boxes):
- # Wart pin for kornia#4248: validate_bbox3d accepts (B, N, 8, 3), but infer_bbox_shape3d and bbox_to_mask3d
- # then index the box axis as the vertex axis. With one box that raises out-of-bounds errors;
- # with eight boxes infer_bbox_shape3d instead returns three (1, 3) tensors, one value per
- # coordinate rather than per box. The 2D helpers had the same defect until kornia#4180.
- boxes = self._unit_cuboid(device, dtype).expand(num_boxes, 8, 3)[None].contiguous()
- assert validate_bbox3d(boxes) is True
- if num_boxes == 8:
- depths, heights, widths = infer_bbox_shape3d(boxes)
- assert depths.shape == heights.shape == widths.shape == (1, 3)
- with pytest.raises(RuntimeError):
- bbox_to_mask3d(boxes, (4, 5, 5))
- else:
- with pytest.raises((RuntimeError, IndexError)):
- infer_bbox_shape3d(boxes)
- with pytest.raises((RuntimeError, IndexError)):
- bbox_to_mask3d(boxes, (4, 5, 5))
-
- @pytest.mark.parametrize("num_boxes", [1, 8])
- @pytest.mark.xfail(
- strict=True,
- raises=AssertionError,
- reason="kornia#4248: rank-4 3D input is not rejected with ShapeError as the 2D helpers do since kornia#4218",
- )
def test_convention_rank4_input_is_rejected_by_the_3d_helpers_4248(self, device, dtype, num_boxes):
+ # kornia#4248, the 3D twin of kornia#4180. validate_bbox3d still accepts (B, N, 8, 3) and
+ # reshapes internally, but infer_bbox_shape3d and bbox_to_mask3d read dim 1 as the vertex
+ # axis, so rank-4 input was read as if the box axis were the vertices: out-of-bounds with
+ # one box, and three (1, 3) tensors -- one value per coordinate rather than per box -- with
+ # eight. Both now reject it up front, the way the 2D helpers have since kornia#4218.
boxes = self._unit_cuboid(device, dtype).expand(num_boxes, 8, 3)[None].contiguous()
+ # The accepting half of the mismatch is unchanged and still worth pinning.
+ assert validate_bbox3d(boxes) is True
for call in (lambda: infer_bbox_shape3d(boxes), lambda: bbox_to_mask3d(boxes, (4, 5, 5))):
- try:
+ with pytest.raises(ShapeError):
call()
- except ShapeError:
- continue
- except Exception as error:
- raise AssertionError(f"expected ShapeError, got {type(error).__name__}") from error
- raise AssertionError("expected ShapeError, the call returned")
def test_wart_bbox_generator3d_extent_is_one_larger_than_requested_4018(self, device, dtype):
# Wart pin for kornia#4018: the 3D generator places the far corner at start + size, so