Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

fix(geometry): reject non-finite coordinates in the 3D box paths (#4343)

abhijeet sharmaaf5bcbbc041a
diff --git a/CHANGELOG.md b/CHANGELOG.md
index d19bdb0dd..fbb45e1f4 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -369,6 +369,16 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
### Bug fixes
+* `Boxes3D.from_tensor(..., validate_boxes=True)` rejects non-finite coordinates, and `validate_bbox3d`
+ returns `False` for them instead of raising an `AssertionError` that names the wrong defect. This is the
+ 3D counterpart of #4243. An `inf` passed the positive-extent checks outright, and a `NaN` passed them
+ because every comparison against `NaN` is `False`, so the box was constructed with non-finite vertices;
+ in `validate_bbox3d` the `NaN` instead reached the `allclose` extent comparisons and raised
+ "Boxes must have be cube, while get different widths". `validate_bbox3d`'s four internal callers use it
+ for its raise and discard the result, so they now convert the `False` themselves and keep raising the same
+ `AssertionError` they did before, with a message that now names the non-finite coordinates instead of
+ reporting mismatched cube extents. The `validate_boxes=False` opt-out and the export gate are unchanged
+ (closes #4258). (#4343)
* `axis_angle_to_rotation_matrix` accepts the `(*, 3)` shape its own guard message promises, instead of
only `(N, 3)`. The body did `wxyz.unbind(dim=1)` and `.view(-1, 3, 3)`, so an unbatched `(3,)` raised
`IndexError: Dimension out of range` and any extra batch dimension raised `ValueError` out of the unbind,
diff --git a/kornia/geometry/bbox.py b/kornia/geometry/bbox.py
index 9b74f24f4..a48f8d2d0 100644
--- a/kornia/geometry/bbox.py
+++ b/kornia/geometry/bbox.py
@@ -107,8 +107,9 @@ def validate_bbox3d(boxes: torch.Tensor) -> bool:
:math:`(B, N, 8, 3)` tensors and raises ``AssertionError`` for any other shape. It compares the inclusive
``+1`` extents of the four edges parallel to each axis and raises ``AssertionError`` when they differ, so a
sheared parallelepiped with equal edge lengths and a zero-extent box both pass; it does not check right
- angles or positive extent. Under graph capture the extent checks are skipped and the shape check alone
- returns ``True``. The ``+1`` terms cancel in exact arithmetic and are tracked in
+ angles or positive extent. A box with a non-finite coordinate returns ``False``. Under graph capture
+ the extent checks are skipped and the shape check alone returns ``True``. The ``+1`` terms cancel
+ in exact arithmetic and are tracked in
`#3934 <https://github.com/kornia/kornia/issues/3934>`_.
.. warning::
@@ -124,7 +125,8 @@ def validate_bbox3d(boxes: torch.Tensor) -> bool:
back-top-right, back-bottom-right, back-bottom-left. The coordinates must be in the x, y, z order.
Returns:
- ``True``. Invalid input raises instead of returning ``False``.
+ ``True``, or ``False`` when any coordinate is non-finite. Invalid input otherwise raises instead of
+ returning ``False``.
"""
if not (len(boxes.shape) in [3, 4] and boxes.shape[-2:] == torch.Size([8, 3])):
@@ -133,10 +135,16 @@ def validate_bbox3d(boxes: torch.Tensor) -> bool:
if len(boxes.shape) == 4:
boxes = boxes.reshape(-1, 8, 3)
- # The cube checks below read the data, which graph capture cannot do; skip them under export.
+ # The value checks below read the data, which graph capture cannot do; skip them under export.
if is_exporting():
return True
+ # Non-finite coordinates are rejected as a predicate result rather than through the ``allclose``
+ # comparisons below, which see ``nan != nan`` and raise a "different widths" AssertionError that
+ # names the wrong defect.
+ if not torch.isfinite(boxes).all():
+ return False
+
left = torch.index_select(boxes, 1, torch.tensor([1, 2, 5, 6], device=boxes.device, dtype=torch.long))[:, :, 0]
right = torch.index_select(boxes, 1, torch.tensor([0, 3, 4, 7], device=boxes.device, dtype=torch.long))[:, :, 0]
widths = left - right + 1
@@ -225,10 +233,13 @@ def infer_bbox_shape3d(boxes: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor,
The inclusive ``+1`` arithmetic differs from torchvision, COCO, and albumentations and is tracked in
`#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 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.
+ returning ``False`` for a shape or extent failure, see
+ `#4013 <https://github.com/kornia/kornia/issues/4013>`_; a non-finite coordinate is the one case
+ :func:`validate_bbox3d` reports as ``False``, and this function raises ``AssertionError`` for it too.
+ Batched :math:`(B, N, 8, 3)` 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
@@ -267,7 +278,10 @@ def infer_bbox_shape3d(boxes: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor,
# 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)
+ # ``validate_bbox3d`` raises for every failure it detects except a non-finite coordinate, which is a
+ # ``False`` predicate result; this call site relies on the raise, so it converts that ``False`` itself.
+ if not validate_bbox3d(boxes):
+ raise AssertionError("Boxes must have finite coordinates, got non-finite values.")
left = torch.index_select(boxes, 1, torch.tensor([1, 2, 5, 6], device=boxes.device, dtype=torch.long))[:, :, 0]
right = torch.index_select(boxes, 1, torch.tensor([0, 3, 4, 7], device=boxes.device, dtype=torch.long))[:, :, 0]
@@ -388,7 +402,9 @@ def bbox_to_mask3d(boxes: torch.Tensor, size: tuple[int, int, int]) -> torch.Ten
:meth:`~kornia.geometry.boxes.Boxes3D.to_mask` for fractional coordinates and is tracked in
`#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
+ ``False`` for a shape or extent failure, `#4013 <https://github.com/kornia/kornia/issues/4013>`_; a
+ non-finite coordinate is reported as ``False`` by :func:`validate_bbox3d` and raised here too.
+ Batched :math:`(B, N, 8, 3)` input passes
:func:`validate_bbox3d` but is rejected here with :class:`~kornia.core.exceptions.ShapeError`; flatten to
:math:`(B \cdot N, 8, 3)` first.
@@ -442,7 +458,8 @@ def bbox_to_mask3d(boxes: torch.Tensor, size: tuple[int, int, int]) -> torch.Ten
# 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)
+ if not validate_bbox3d(boxes):
+ raise AssertionError("Boxes must have finite coordinates, got non-finite values.")
D0, D1, D2 = size # get depth, height, width
z_min = boxes[:, 0, 2].long()
diff --git a/kornia/geometry/boxes.py b/kornia/geometry/boxes.py
index 461cd61bf..441884d5e 100644
--- a/kornia/geometry/boxes.py
+++ b/kornia/geometry/boxes.py
@@ -240,7 +240,8 @@ class Boxes:
:func:`~kornia.geometry.bbox.nms` computes exclusive areas, and
:func:`~kornia.geometry.bbox.transform_bbox` converts ``'xywh'`` with the exclusive
``xmax = xmin + width``.
- - With ``validate_boxes=True``, the ``'xy*'`` modes reject non-positive extents measured in that mode's
+ - With ``validate_boxes=True``, a non-finite coordinate is rejected in every mode, and the ``'xy*'``
+ modes reject non-positive extents measured in that mode's
convention.
- The constructor rejects an integer tensor unless ``raise_if_not_floating_point=False``. A list input is
padded into a tensor of its *first* element's dtype before that check, so a mixed-dtype list is accepted
@@ -665,8 +666,9 @@ class Boxes:
* 'vertices_plus': the inclusive stored vertex form. With shape :math:`(N, 4, 2)`,
:math:`(B, N, 4, 2)`.
- validate_boxes: Check extents for the ``'xy*'`` modes in each mode's convention. This flag has no
- validation effect for vertex modes; see the warning on :class:`~kornia.geometry.boxes.Boxes`.
+ validate_boxes: Reject a non-finite coordinate, and check extents for the ``'xy*'`` modes in each
+ mode's convention. The extent half has no validation effect for vertex modes; see the warning on
+ :class:`~kornia.geometry.boxes.Boxes`.
Returns:
:class:`Boxes` containing the converted inclusive vertex representation.
@@ -1174,8 +1176,9 @@ class Boxes3D:
pass them the ``'vertices_plus'`` export, never ``'vertices'``, which they read as one larger per axis.
The validator also accepts batched :math:`(B, N, 8, 3)` input, but the shape and mask helpers require
unbatched :math:`(N, 8, 3)` input; see their warnings.
- - With ``validate_boxes=True``, :meth:`from_tensor` rejects extents that are not positive in the given
- mode's convention, so ``xmax == xmin`` is rejected in ``'xyzxyz'`` and accepted in ``'xyzxyz_plus'``.
+ - With ``validate_boxes=True``, :meth:`from_tensor` rejects a non-finite coordinate, and extents that
+ are not positive in the given mode's convention, so ``xmax == xmin`` is rejected in ``'xyzxyz'`` and
+ accepted in ``'xyzxyz_plus'``.
- The constructor rejects an integer tensor unless ``raise_if_not_floating_point=False``;
:meth:`from_tensor` silently casts integer input to ``float32``.
- :meth:`transform_boxes` leaves the source unchanged and returns a new object labelled
@@ -1280,8 +1283,9 @@ class Boxes3D:
* 'xyzwhd': boxes are assumed to be in the format ``xmin, ymin, zmin, width, height, depth`` where
``width = xmax - xmin``, ``height = ymax - ymin`` and ``depth = zmax - zmin``.
- validate_boxes: reject boxes whose width, height or depth is not positive when measured in the given
- mode's convention, so ``xmax == xmin`` is rejected in ``'xyzxyz'`` and accepted in ``'xyzxyz_plus'``.
+ validate_boxes: reject boxes with a non-finite coordinate, and boxes whose width, height or depth
+ is not positive when measured in the given mode's convention, so ``xmax == xmin`` is rejected in
+ ``'xyzxyz'`` and accepted in ``'xyzxyz_plus'``.
Returns:
:class:`Boxes3D` containing the converted inclusive vertex representation, labelled with ``mode``.
@@ -1333,6 +1337,8 @@ class Boxes3D:
# Value validation reads the data, which graph capture cannot do; skip it under export.
if validate_boxes and not is_exporting():
+ if not torch.isfinite(boxes).all():
+ raise ValueError("Some boxes have non-finite coordinates.")
if (width <= 0).any():
raise ValueError("Some boxes have negative widths or 0.")
if (height <= 0).any():
diff --git a/kornia/geometry/transform/crop3d.py b/kornia/geometry/transform/crop3d.py
index 87eba8665..1252d0581 100644
--- a/kornia/geometry/transform/crop3d.py
+++ b/kornia/geometry/transform/crop3d.py
@@ -367,8 +367,10 @@ def _crop_by_boxes3d_to_size(
# ``crop_by_boxes3d`` with the output size already known as Python ints. ``crop_and_resize3d`` and
# ``center_crop3d`` build ``dst_box`` from ``size``, so they take this path and never read the box
# values back from the device -- which also keeps them capturable by ``torch.onnx.export``.
- validate_bbox3d(src_box)
- validate_bbox3d(dst_box)
+ # ``validate_bbox3d`` raises for every failure it detects except a non-finite coordinate, which is a
+ # ``False`` predicate result; these call sites rely on the raise, so they convert that ``False``.
+ if not (validate_bbox3d(src_box) and validate_bbox3d(dst_box)):
+ raise AssertionError("Boxes must have finite coordinates, got non-finite values.")
if len(tensor.shape) != 5:
raise AssertionError(f"Only tensor with shape (B, C, D, H, W) supported. Got {tensor.shape}.")
diff --git a/tests/geometry/test_bbox.py b/tests/geometry/test_bbox.py
index 0c2f0e99e..11e3f5659 100644
--- a/tests/geometry/test_bbox.py
+++ b/tests/geometry/test_bbox.py
@@ -34,6 +34,7 @@ from kornia.geometry.bbox import (
validate_bbox3d,
)
from kornia.geometry.boxes import Boxes3D
+from kornia.geometry.transform.crop3d import crop_and_resize3d, crop_by_boxes3d
from testing.base import BaseTester
@@ -450,6 +451,83 @@ class TestTransformBoxes2D(BaseTester):
class TestBbox3D(BaseTester):
+ def test_convention_validate_bbox3d_rejects_non_finite_coordinates_4258(self, device, dtype):
+ # Pin kornia#4258, the 3D counterpart of the #4238 pin on validate_bbox above: a non-finite
+ # coordinate makes this a False predicate result, not an AssertionError. Before the fix the
+ # nan reached the allclose extent comparisons, which see nan != nan and raise "Boxes must
+ # have be cube, while get different heights", naming the wrong defect; an inf reached them
+ # as inf - inf = nan with the same result.
+ boxes = torch.tensor(
+ [
+ [
+ [0.0, 0.0, 0.0],
+ [4.0, 0.0, 0.0],
+ [4.0, 4.0, 0.0],
+ [0.0, 4.0, 0.0],
+ [0.0, 0.0, 4.0],
+ [4.0, 0.0, 4.0],
+ [4.0, 4.0, 4.0],
+ [0.0, 4.0, 4.0],
+ ]
+ ],
+ device=device,
+ dtype=dtype,
+ )
+ assert validate_bbox3d(boxes) is True
+
+ for coordinate_index in range(24):
+ for non_finite in [float("nan"), float("inf"), float("-inf")]:
+ invalid_boxes = boxes.clone()
+ invalid_boxes[0].reshape(-1)[coordinate_index] = non_finite
+ assert validate_bbox3d(invalid_boxes) is False
+ # the same holds for the (B, N, 8, 3) rank-4 layout
+ assert validate_bbox3d(invalid_boxes[None]) is False
+
+ def test_convention_consumers_still_raise_on_non_finite_coordinates_4258(self, device, dtype):
+ # validate_bbox3d's four internal callers use it for its raise and discard the return value,
+ # so turning the non-finite case into a False predicate result must not quietly let NaN
+ # through them. All of them raised on main and all of them still do.
+ box = torch.tensor(
+ [
+ [
+ [0.0, 0.0, 0.0],
+ [4.0, 0.0, 0.0],
+ [4.0, 4.0, 0.0],
+ [0.0, 4.0, 0.0],
+ [0.0, 0.0, 4.0],
+ [4.0, 0.0, 4.0],
+ [4.0, 4.0, 4.0],
+ [0.0, 4.0, 4.0],
+ ]
+ ],
+ device=device,
+ dtype=dtype,
+ )
+ invalid = box.clone()
+ invalid[0, 7, 1] = float("nan")
+
+ with pytest.raises(AssertionError, match="finite"):
+ infer_bbox_shape3d(invalid)
+ with pytest.raises(AssertionError, match="finite"):
+ bbox_to_mask3d(invalid, (6, 6, 6))
+
+ # The other two callers are the src_box and dst_box of _crop_by_boxes3d_to_size, reached
+ # through crop_by_boxes3d and crop_and_resize3d. They need their own cells: the dst_box is
+ # caught earlier by infer_bbox_shape3d, but the src_box is not, because crop_by_boxes3d
+ # sizes its output from the *dst* box. With the crop3d guard reverted both calls below
+ # accept the non-finite src_box without raising, while the two cells above stay green.
+ volume = torch.arange(64, device=device, dtype=dtype).reshape(1, 1, 4, 4, 4)
+ with pytest.raises(AssertionError, match="finite"):
+ crop_by_boxes3d(volume, invalid, box)
+ with pytest.raises(AssertionError, match="finite"):
+ crop_and_resize3d(volume, invalid, (2, 2, 2))
+
+ # the valid box is untouched
+ assert len(infer_bbox_shape3d(box)) == 3
+ assert bbox_to_mask3d(box, (6, 6, 6)).shape == (1, 1, 6, 6, 6)
+ assert crop_by_boxes3d(volume, box, box).shape == (1, 1, 5, 5, 5)
+ assert crop_and_resize3d(volume, box, (2, 2, 2)).shape == (1, 1, 2, 2, 2)
+
def test_generator_scalar_inputs(self, device, dtype):
args = [torch.tensor(value, device=device, dtype=dtype) for value in (1, 2, 3, 4, 5, 6)]
boxes = bbox_generator3d(*args)
diff --git a/tests/geometry/test_boxes.py b/tests/geometry/test_boxes.py
index 0482a33b6..ba865aac1 100644
--- a/tests/geometry/test_boxes.py
+++ b/tests/geometry/test_boxes.py
@@ -1020,6 +1020,29 @@ class TestTransformBoxes2D(BaseTester):
class TestBbox3D(BaseTester):
+ @pytest.mark.parametrize("mode", ["xyzxyz", "xyzxyz_plus", "xyzwhd"])
+ def test_convention_from_tensor_rejects_non_finite_coordinates_4258(self, mode, device, dtype):
+ # Pin kornia#4258, the 3D counterpart of the #4238 pin on Boxes.from_tensor: eager
+ # validation rejects non-finite values in both the unbatched and batched layouts, even when
+ # a valid row is present too. Before the fix an inf passed the positive-extent checks
+ # outright (inf - 0 > 0) and a nan passed them because every comparison against nan is
+ # False, so the box was constructed with non-finite vertices.
+ source = torch.tensor(
+ [[0.0, 0.0, 0.0, 4.0, 4.0, 4.0], [1.0, 1.0, 1.0, 5.0, 5.0, 5.0]], device=device, dtype=dtype
+ )
+ for source_layout in [source, source.unsqueeze(0)]:
+ for coordinate_index in range(6):
+ for non_finite in [float("nan"), float("inf"), float("-inf")]:
+ invalid_source = source_layout.clone()
+ invalid_source.reshape(-1, 6)[1, coordinate_index] = non_finite
+ with pytest.raises(ValueError, match="non-finite coordinates"):
+ Boxes3D.from_tensor(invalid_source, mode=mode, validate_boxes=True)
+
+ def test_convention_from_tensor_opt_out_preserves_non_finite_input_4258(self, device, dtype):
+ source = torch.tensor([[0.0, 0.0, 0.0, float("nan"), 4.0, 4.0]], device=device, dtype=dtype)
+ boxes = Boxes3D.from_tensor(source, mode="xyzxyz", validate_boxes=False)
+ assert torch.isnan(boxes.data).any()
+
def test_smoke(self, device, dtype):
def _create_tensor_box():
# Sample two points of the 3d rect