Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

feat(geometry): warn where validate_bbox and validate_bbox3d return False (#4013) (#6324)

Mohansree Vijayakumar0708d1c8d47c
diff --git a/changelog.d/6324.added.md b/changelog.d/6324.added.md
new file mode 100644
index 000000000..adb49a702
--- /dev/null
+++ b/changelog.d/6324.added.md
@@ -0,0 +1 @@
+`validate_bbox`, and `validate_bbox3d` for a non-finite coordinate, emit a `FutureWarning` when they return `False`: a future release raises `AssertionError` instead, as `validate_bbox3d` already does for other invalid boxes. Both validators now synchronize with the device once per call, which roughly halves their cost on MPS and speeds up `infer_bbox_shape3d` and `bbox_to_mask3d`.
diff --git a/kornia/geometry/bbox.py b/kornia/geometry/bbox.py
index 16d761293..0ea9cdd7a 100644
--- a/kornia/geometry/bbox.py
+++ b/kornia/geometry/bbox.py
@@ -18,6 +18,7 @@
from __future__ import annotations
import math
+import warnings
from typing import Optional
import torch
@@ -40,6 +41,17 @@ __all__ = [
"validate_bbox3d",
]
+_VALIDATE_BBOX_FALSE_MESSAGE = (
+ "`validate_bbox` returned False for an invalid box. Returning False is deprecated since kornia 0.9.1: a "
+ "future release raises AssertionError instead, as `validate_bbox3d` does. To work with both, treat an "
+ "AssertionError like a False result (kornia#4013)."
+)
+_VALIDATE_BBOX3D_FALSE_MESSAGE = (
+ "`validate_bbox3d` returned False for a non-finite coordinate. Returning False is deprecated since kornia "
+ "0.9.1: a future release raises AssertionError, as it already does for every other invalid box. To work with "
+ "both, treat an AssertionError like a False result (kornia#4013)."
+)
+
def validate_bbox(boxes: torch.Tensor) -> bool:
"""Validate whether a 2D box has matching top and bottom edge vectors.
@@ -51,8 +63,8 @@ def validate_bbox(boxes: torch.Tensor) -> bool:
angles, positive area and direction are not checked, so any parallelogram in cyclic vertex order passes.
.. warning::
- :func:`validate_bbox3d` raises ``AssertionError`` where this function returns ``False``:
- `#4013 <https://github.com/kornia/kornia/issues/4013>`_.
+ Returning ``False`` is deprecated; a future release raises ``AssertionError``
+ (`#4013 <https://github.com/kornia/kornia/issues/4013>`_).
Args:
boxes: a tensor containing the coordinates of the bounding boxes to be extracted. The tensor must have the shape
@@ -62,9 +74,8 @@ def validate_bbox(boxes: torch.Tensor) -> bool:
"""
if not (len(boxes.shape) in [3, 4] and boxes.shape[-2:] == torch.Size([4, 2])):
- return False
-
- if not torch.isfinite(boxes).all():
+ if not torch.jit.is_scripting() and not torch.jit.is_tracing() and not is_compiling():
+ warnings.warn(_VALIDATE_BBOX_FALSE_MESSAGE, FutureWarning, stacklevel=2)
return False
if len(boxes.shape) == 4:
@@ -78,15 +89,21 @@ def validate_bbox(boxes: torch.Tensor) -> bool:
width_t, width_b = x_tr - x_tl + 1, x_br - x_bl + 1
height_t, height_b = y_tr - y_tl + 1, y_br - y_bl + 1
- # Replace torch.allclose with exportable operations
- width_diff = torch.abs(width_t - width_b)
- height_diff = torch.abs(height_t - height_b)
-
- # Check if differences are within tolerance (1e-4)
- if torch.any(width_diff > 1e-4):
+ # Non-finite, width mismatch, height mismatch, read back in one host sync. Every failure returns False, so
+ # the order in which the flags are read does not change the result.
+ flags = torch.stack(
+ [
+ ~torch.isfinite(boxes).all(),
+ (torch.abs(width_t - width_b) > 1e-4).any(),
+ (torch.abs(height_t - height_b) > 1e-4).any(),
+ ]
+ ).cpu()
+ if bool(flags.any()):
+ if not torch.jit.is_scripting() and not torch.jit.is_tracing() and not is_compiling():
+ warnings.warn(_VALIDATE_BBOX_FALSE_MESSAGE, FutureWarning, stacklevel=2)
return False
- return not torch.any(height_diff > 1e-4)
+ return True
def validate_bbox3d(boxes: torch.Tensor) -> bool:
@@ -100,8 +117,8 @@ def validate_bbox3d(boxes: torch.Tensor) -> bool:
checked.
.. warning::
- :func:`validate_bbox` returns ``False`` where this function raises:
- `#4013 <https://github.com/kornia/kornia/issues/4013>`_.
+ Returning ``False`` is deprecated; a future release raises ``AssertionError``
+ (`#4013 <https://github.com/kornia/kornia/issues/4013>`_).
Args:
boxes: a tensor containing the coordinates of the bounding boxes to be extracted. The tensor must have the shape
@@ -114,6 +131,16 @@ def validate_bbox3d(boxes: torch.Tensor) -> bool:
returning ``False``.
"""
+ if _validate_bbox3d(boxes):
+ return True
+ if not torch.jit.is_scripting() and not torch.jit.is_tracing() and not is_compiling():
+ warnings.warn(_VALIDATE_BBOX3D_FALSE_MESSAGE, FutureWarning, stacklevel=2)
+ return False
+
+
+def _validate_bbox3d(boxes: torch.Tensor) -> bool:
+ # ``validate_bbox3d`` without its deprecation warning, for kornia's own callers, which turn a ``False``
+ # result into an ``AssertionError`` themselves.
if not (len(boxes.shape) in [3, 4] and boxes.shape[-2:] == torch.Size([8, 3])):
raise AssertionError(f"Box shape must be (B, 8, 3) or (B, N, 8, 3). Got {boxes.shape}.")
@@ -125,26 +152,31 @@ def validate_bbox3d(boxes: torch.Tensor) -> bool:
if not torch.jit.is_scripting() and is_compiling():
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
+ # Vertices (1, 2, 5, 6) - (0, 3, 4, 7) along x and (2, 3, 6, 7) - (0, 1, 4, 5) along y, by slicing, so a
+ # call does not copy an index tensor from the host.
+ x, y = boxes[..., 0], boxes[..., 1]
+ widths = torch.cat([x[:, 1:3] - x[:, 0:4:3], x[:, 5:7] - x[:, 4:8:3]], 1) + 1
+ heights = torch.cat([y[:, 2:4] - y[:, 0:2], y[:, 6:8] - y[:, 4:6]], 1) + 1
+ depths = boxes[:, 4:, 2] - boxes[:, :4, 2] + 1
- 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
- if not torch.allclose(widths.permute(1, 0), widths[:, 0]):
+ # Non-finite coordinates are rejected as a predicate result rather than through the extent comparisons,
+ # which see ``nan != nan`` and would raise a "different widths" AssertionError that names the wrong defect.
+ # All four flags reach the host in one sync; ``isclose`` keeps the ``allclose`` default tolerances.
+ flags = torch.stack(
+ [
+ ~torch.isfinite(boxes).all(),
+ ~torch.isclose(widths.permute(1, 0), widths[:, 0]).all(),
+ ~torch.isclose(heights.permute(1, 0), heights[:, 0]).all(),
+ ~torch.isclose(depths.permute(1, 0), depths[:, 0]).all(),
+ ]
+ ).cpu()
+ if bool(flags[0]):
+ return False
+ if bool(flags[1]):
raise AssertionError(f"Boxes must have be cube, while get different widths {widths}.")
-
- bot = torch.index_select(boxes, 1, torch.tensor([2, 3, 6, 7], device=boxes.device, dtype=torch.long))[:, :, 1]
- upper = torch.index_select(boxes, 1, torch.tensor([0, 1, 4, 5], device=boxes.device, dtype=torch.long))[:, :, 1]
- heights = bot - upper + 1
- if not torch.allclose(heights.permute(1, 0), heights[:, 0]):
+ if bool(flags[2]):
raise AssertionError(f"Boxes must have be cube, while get different heights {heights}.")
-
- depths = boxes[:, 4:, 2] - boxes[:, :4, 2] + 1
- if not torch.allclose(depths.permute(1, 0), depths[:, 0]):
+ if bool(flags[3]):
raise AssertionError(f"Boxes must have be cube, while get different depths {depths}.")
return True
@@ -258,7 +290,7 @@ def infer_bbox_shape3d(boxes: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor,
KORNIA_CHECK_SHAPE(boxes, ["N", "8", "3"])
# ``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):
+ 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]
@@ -423,7 +455,7 @@ 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"])
- if not 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
diff --git a/kornia/geometry/transform/crop3d.py b/kornia/geometry/transform/crop3d.py
index 6b71d4e2d..5283c85b5 100644
--- a/kornia/geometry/transform/crop3d.py
+++ b/kornia/geometry/transform/crop3d.py
@@ -19,7 +19,7 @@ from typing import Tuple
import torch
-from kornia.geometry.bbox import infer_bbox_shape3d, validate_bbox3d
+from kornia.geometry.bbox import _validate_bbox3d, infer_bbox_shape3d
from .imgwarp import get_perspective_transform3d, warp_affine3d
@@ -375,7 +375,7 @@ def _crop_by_boxes3d_to_size(
# values back from the device -- which also keeps them capturable by ``torch.onnx.export``.
# ``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)):
+ 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:
diff --git a/tests/geometry/test_bbox.py b/tests/geometry/test_bbox.py
index 08db94043..5d5deca17 100644
--- a/tests/geometry/test_bbox.py
+++ b/tests/geometry/test_bbox.py
@@ -107,14 +107,17 @@ class TestBbox2D(BaseTester):
relabeled_rectangle = torch.tensor(
[[[[0.0, 0.0], [3.0, 0.0], [0.0, 2.0], [3.0, 2.0]]]], device=device, dtype=dtype
)
- assert validate_bbox(relabeled_rectangle) is False
+ with pytest.warns(FutureWarning, match="validate_bbox"):
+ assert validate_bbox(relabeled_rectangle) is False
trapezoid = torch.tensor([[[[0.0, 0.0], [10.0, 0.0], [10.0, 5.0], [3.0, 5.0]]]], device=device, dtype=dtype)
- assert validate_bbox(trapezoid) is False
+ with pytest.warns(FutureWarning, match="validate_bbox"):
+ assert validate_bbox(trapezoid) is False
# The edge vectors share their x component and differ only in y, so only the second comparison rejects it.
tilted_bottom = torch.tensor([[[[0.0, 0.0], [2.0, 0.0], [2.0, 2.0], [0.0, 1.0]]]], device=device, dtype=dtype)
- assert validate_bbox(tilted_bottom) is False
+ with pytest.warns(FutureWarning, match="validate_bbox"):
+ assert validate_bbox(tilted_bottom) is False
def test_convention_validate_bbox_accepts_noncontiguous_rank4_layout_4174(self, device, dtype):
# kornia#4174: a rank-4 input whose leading dimensions cannot be merged by view returns a boolean.
@@ -145,13 +148,16 @@ class TestBbox2D(BaseTester):
for non_finite in [float("nan"), float("inf"), float("-inf")]:
invalid_boxes = boxes.clone()
invalid_boxes[1].reshape(-1)[coordinate_index] = non_finite
- assert validate_bbox(invalid_boxes) is False
+ with pytest.warns(FutureWarning, match="validate_bbox"):
+ assert validate_bbox(invalid_boxes) is False
def test_wart_validate_bbox_returns_false_where_validate_bbox3d_raises_4013(self, device, dtype):
# Wart pin for kornia#4013: for the same invalid shape, the 2D validator
- # returns False while the 3D validator raises.
+ # returns False while the 3D validator raises. The False result is deprecated and
+ # warns until a later release turns it into the AssertionError the 3D validator raises.
invalid_shape = torch.rand(1, 3, 3, device=device, dtype=dtype)
- assert validate_bbox(invalid_shape) is False
+ with pytest.warns(FutureWarning, match="validate_bbox"):
+ assert validate_bbox(invalid_shape) is False
with pytest.raises(AssertionError):
validate_bbox3d(invalid_shape)
@@ -174,6 +180,25 @@ class TestBbox2D(BaseTester):
with pytest.raises(AssertionError):
validate_bbox3d(non_cube)
+ def test_validate_bbox_warns_where_it_returns_false_4013(self, device, dtype):
+ # kornia#4013: every input for which validate_bbox returns False warns, pointing at the caller, and still
+ # returns False; a valid box warns nothing.
+ valid = torch.tensor([[[0.0, 0.0], [3.0, 0.0], [3.0, 2.0], [0.0, 2.0]]], device=device, dtype=dtype)
+ non_rectangle = valid.clone()
+ non_rectangle[0, 3, 1] = 3.0
+ nan_box = valid.clone()
+ nan_box[0, 2, 0] = float("nan")
+ wrong_shape = torch.rand(1, 3, 2, device=device, dtype=dtype)
+ for boxes in (non_rectangle, nan_box, wrong_shape):
+ with pytest.warns(FutureWarning, match="validate_bbox") as record:
+ assert validate_bbox(boxes) is False
+ assert [w.filename for w in record] == [__file__]
+
+ with warnings.catch_warnings():
+ warnings.simplefilter("error")
+ assert validate_bbox(valid) is True
+ assert validate_bbox(valid[None]) is True
+
def test_smoke(self, device, dtype):
# Sample two points of the rectangle
points = torch.rand(1, 4, device=device, dtype=dtype)
@@ -234,9 +259,17 @@ class TestBbox2D(BaseTester):
boxes_sheared = torch.tensor([[[0.0, 0.0], [2.0, 0.0], [3.0, 1.0], [1.0, 1.0]]], device=device, dtype=dtype)
self.assert_close(scripted_fn(boxes_sheared), validate_bbox(boxes_sheared))
- # Test with invalid shape
+ # Test with invalid shape: the scripted function returns False without the eager deprecation warning
boxes_wrong_shape = torch.rand(1, 3, 2, device=device, dtype=dtype)
- self.assert_close(scripted_fn(boxes_wrong_shape), validate_bbox(boxes_wrong_shape))
+ with warnings.catch_warnings():
+ warnings.simplefilter("error")
+ assert scripted_fn(boxes_wrong_shape) is False
+ boxes_non_rectangle = torch.tensor(
+ [[[0.0, 0.0], [1.0, 0.0], [1.0, 1.0], [0.0, 2.0]]], device=device, dtype=dtype
+ )
+ with warnings.catch_warnings():
+ warnings.simplefilter("error")
+ assert scripted_fn(boxes_non_rectangle) is False
def test_convention_bbox_to_mask_takes_width_then_height_and_reads_two_vertices_4014(self, device, dtype):
# Convention pin (kornia#4014 records the argument-order split with Boxes.to_mask):
@@ -539,9 +572,11 @@ class TestBbox3D(BaseTester):
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
+ with pytest.warns(FutureWarning, match="validate_bbox3d"):
+ 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
+ with pytest.warns(FutureWarning, match="validate_bbox3d"):
+ 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 each
@@ -565,6 +600,9 @@ class TestBbox3D(BaseTester):
invalid = box.clone()
invalid[0, 7, 1] = float("nan")
+ # The callers raise themselves, so validate_bbox3d's deprecation warning (kornia#4013) is not theirs to
+ # emit: a FutureWarning here would surface as an error instead of the AssertionError.
+ warnings.simplefilter("error", FutureWarning)
with pytest.raises(AssertionError, match="finite"):
infer_bbox_shape3d(invalid)
with pytest.raises(AssertionError, match="finite"):
@@ -697,10 +735,11 @@ class TestBbox3D(BaseTester):
)
def test_wart_validate_bbox3d_checks_equal_edge_extents_not_cuboids_4013(self, device, dtype, monkeypatch):
- # Wart pin for kornia#4013 (the 3D validator raises where the 2D one returns False): the
- # check compares the inclusive extents of the four edges parallel to each axis, so a
- # sheared parallelepiped and a zero-extent box pass, and only unequal edges raise. Under
- # graph capture the extent check is skipped and the shape check alone returns True.
+ # Wart pin for kornia#4013 (the 3D validator raises where the 2D one returns False, and its one
+ # False result, a non-finite coordinate, warns that it will raise too): the check compares
+ # the inclusive extents of the four edges parallel to each axis, so a sheared parallelepiped
+ # and a zero-extent box pass, and only unequal edges raise. Under graph capture the extent
+ # check is skipped and the shape check alone returns True.
cuboid = self._unit_cuboid(device, dtype)
assert validate_bbox3d(cuboid) is True
assert validate_bbox3d(cuboid[None]) is True
@@ -714,10 +753,17 @@ class TestBbox3D(BaseTester):
unequal = cuboid.clone()
unequal[0, 1, 0] = 5.0
- with pytest.raises(AssertionError, match="widths"):
- validate_bbox3d(unequal)
- with pytest.raises(AssertionError, match="shape"):
- validate_bbox3d(cuboid[0])
+ with warnings.catch_warnings():
+ warnings.simplefilter("error")
+ with pytest.raises(AssertionError, match="widths"):
+ validate_bbox3d(unequal)
+ with pytest.raises(AssertionError, match="shape"):
+ validate_bbox3d(cuboid[0])
+ nan_box = cuboid.clone()
+ nan_box[0, 5, 2] = float("nan")
+ with pytest.warns(FutureWarning, match="validate_bbox3d") as record:
+ assert validate_bbox3d(nan_box) is False
+ assert [w.filename for w in record] == [__file__]
monkeypatch.setattr(bbox_module, "is_compiling", lambda: True)
assert validate_bbox3d(unequal) is True
with pytest.raises(AssertionError, match="shape"):