π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
fix(geometry): validate vertex boxes (#5337)
Pushkar Ahuja3700a3c391f5
diff --git a/changelog.d/5337.breaking.md b/changelog.d/5337.breaking.mdnew file mode 100644index 000000000..c1ec0c4ec--- /dev/null+++ b/changelog.d/5337.breaking.md@@ -0,0 +1,7 @@+`Boxes.from_tensor` with `mode="vertices"` or `mode="vertices_plus"`, and `VideoBoxes.from_tensor`, now reject a+non-finite vertex coordinate when `validate_boxes=True` (the default). Before, the vertex modes ignored+`validate_boxes` and stored `NaN` and `inf` vertices; pass `validate_boxes=False` to keep them. The check is+`torch._assert_async`, so it raises `RuntimeError` (the `'xy*'` modes keep raising `ValueError`), runs on CPU and+CUDA, is skipped on MPS, and keeps the vertex import, and with it `AugmentationSequential` with `"bbox"` data,+compilable with `fullgraph=True`. The vertex modes still take no extent or shape check, so the rotated, sheared and+projective quadrilaterals of `transform_boxes` import unchanged.diff --git a/kornia/geometry/boxes.py b/kornia/geometry/boxes.pyindex a47f7db3c..42c8690d2 100644--- a/kornia/geometry/boxes.py+++ b/kornia/geometry/boxes.py@@ -95,6 +95,25 @@ def _boxes_to_polygons(return polygons+def _validate_box_coordinates(boxes: torch.Tensor) -> None:+ """Validate that box coordinates are finite."""+ if not torch.isfinite(boxes).all():+ raise ValueError("Some boxes have non-finite coordinates.")+++def _assert_finite_vertices(boxes: torch.Tensor) -> None:+ """Reject a non-finite vertex coordinate without reading the data on the host.++ ``AugmentationSequential`` imports ``'bbox'`` data through ``'vertices_plus'`` inside a ``fullgraph=True``+ compile, where a Python ``if`` on the data would break the graph. ``torch._assert_async`` raises+ ``RuntimeError`` instead. As in :mod:`kornia.enhance`, the check is skipped on MPS, where materializing the+ condition would drain the queued stream on every call.+ """+ if boxes.device.type == "mps":+ return+ torch._assert_async(torch.isfinite(boxes).all(), "Some boxes have non-finite coordinates.")++def _boxes_to_quadrilaterals(boxes: torch.Tensor, mode: str = "xyxy", validate_boxes: bool = True) -> torch.Tensor:"""Convert from boxes to quadrilaterals."""mode = mode.lower()@@ -113,6 +132,14 @@ def _boxes_to_quadrilaterals(boxes: torch.Tensor, mode: str = "xyxy", validate_bboxes = boxes if boxes.is_floating_point() else boxes.to(torch.get_default_dtype())boxes = boxes if batched else boxes.unsqueeze(0)+ # Value validation reads the data, which graph capture cannot do; skip it under export. The vertex modes check+ # finiteness asynchronously so that they stay fullgraph-compilable.+ if validate_boxes and not is_exporting() and boxes.numel() > 0:+ if mode.startswith("vertices"):+ _assert_finite_vertices(boxes)+ else:+ _validate_box_coordinates(boxes)+if mode.startswith("vertices"):if mode == "vertices":quadrilaterals = boxes.clone()@@ -126,6 +153,7 @@ def _boxes_to_quadrilaterals(boxes: torch.Tensor, mode: str = "xyxy", validate_bquadrilaterals = boxes.clone()else:raise ValueError(f"Unknown mode {mode}")+elif mode.startswith("xy"):if mode == "xyxy":height, width = boxes[..., 3] - boxes[..., 1], boxes[..., 2] - boxes[..., 0]@@ -138,8 +166,6 @@ def _boxes_to_quadrilaterals(boxes: torch.Tensor, mode: str = "xyxy", validate_b# 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():@@ -209,8 +235,10 @@ class Boxes:- :func:`~kornia.geometry.bbox.infer_bbox_shape` and :func:`~kornia.geometry.bbox.bbox_to_mask` readtheir input as inclusive: pass them the ``'vertices_plus'`` export, unbatched.:func:`~kornia.geometry.bbox.nms` takes exclusive ``xyxy``.- - With ``validate_boxes=True``, the ``'xy*'`` modes reject a non-finite coordinate and non-positive- extents.+ - With ``validate_boxes=True``, every mode rejects a non-finite coordinate. The ``'xy*'`` modes raise+ ``ValueError`` and also reject non-positive extents. The vertex modes raise ``RuntimeError`` through+ ``torch._assert_async`` (on CPU and CUDA, skipped on MPS), so they stay ``fullgraph``-compilable, and take+ no extent or shape check, so the arbitrary quadrilaterals of :meth:`transform_boxes` import unchanged.- The constructor rejects an integer tensor unless ``raise_if_not_floating_point=False`` (a list ischecked by its first element's dtype); :meth:`from_tensor` casts integer input to the default dtype.- :meth:`merge` and :meth:`index_put` are non-mutating by default.@@ -226,9 +254,10 @@ class Boxes:`#4008 <https://github.com/kornia/kornia/issues/4008>`_. :meth:`to_mask` and:func:`~kornia.geometry.bbox.bbox_to_mask` take opposite size orders:`#4014 <https://github.com/kornia/kornia/issues/4014>`_. The integer-input split is- `#4012 <https://github.com/kornia/kornia/issues/4012>`_. Vertex modes are not validated and- ``'vertices'`` can deform the input: `#4177 <https://github.com/kornia/kornia/issues/4177>`_. ``trim``,- ``translate(method='fast')`` and tuple-bound ``clamp`` are unimplemented:+ `#4012 <https://github.com/kornia/kornia/issues/4012>`_. ``'vertices'`` subtracts the inclusive offset at+ fixed vertex slots, so it deforms a quadrilateral that is not an axis-aligned rectangle in clockwise order:+ `#3934 <https://github.com/kornia/kornia/issues/3934>`_. ``trim``, ``translate(method='fast')`` and+ tuple-bound ``clamp`` are unimplemented:`#4017 <https://github.com/kornia/kornia/issues/4017>`_."""@@ -650,9 +679,9 @@ class Boxes:* 'vertices_plus': the inclusive stored vertex form. With shape :math:`(N, 4, 2)`,:math:`(B, N, 4, 2)`.- validate_boxes: For the ``'xy*'`` modes, reject a non-finite coordinate and non-positive extents in- each mode's convention. The vertex modes are not validated; see the warning on- :class:`~kornia.geometry.boxes.Boxes`.+ validate_boxes: Reject a non-finite coordinate in every mode: ``ValueError`` for the ``'xy*'`` modes,+ which also reject non-positive extents in each mode's convention, and ``RuntimeError`` from+ ``torch._assert_async`` for the vertex modes (skipped on MPS), which take no extent or shape check.Returns::class:`Boxes` containing the converted inclusive vertex representation.@@ -1030,8 +1059,9 @@ class VideoBoxes(Boxes):Convention:- :meth:`from_tensor` stores :math:`(B, T, N, 4, 2)` input unchanged as :math:`(B \cdot T, N, 4, 2)`- ``'vertices_plus'`` data, with no mode, conversion or validation; integer input is cast to the default- dtype, and another shape or a list raises ``ValueError``.+ ``'vertices_plus'`` data, with no mode or conversion; integer input is cast to the default dtype, and+ another shape or a list raises ``ValueError``. ``validate_boxes=True`` rejects a non-finite coordinate as+ :meth:`Boxes.from_tensor` does for ``'vertices_plus'``.- :meth:`to_tensor` accepts every :class:`Boxes` mode and restores the temporal axis(``to_tensor('xyxy')`` is :math:`(B, T, N, 4)`).- A transformation matrix is :math:`(B \cdot T, 3, 3)`; a :math:`(3, 3)` matrix raises ``ValueError``@@ -1042,8 +1072,7 @@ class VideoBoxes(Boxes):.. warning::Indexing returns a wrapper without :attr:`temporal_channel_size`, so its :meth:`to_tensor` raises- ``AttributeError``: `#4249 <https://github.com/kornia/kornia/issues/4249>`_. ``validate_boxes`` is inert:- `#4177 <https://github.com/kornia/kornia/issues/4177>`_.+ ``AttributeError``: `#4249 <https://github.com/kornia/kornia/issues/4249>`_.Attributes:temporal_channel_size: Number of frames :math:`T` stored with the boxes.@@ -1063,9 +1092,10 @@ class VideoBoxes(Boxes):``vertices_plus`` order (top-left, top-right, bottom-right,bottom-left), stored unchanged; integer input is cast to``torch.get_default_dtype()``. Lists of tensors are not supported yet.- validate_boxes: Forwarded to ``_boxes_to_quadrilaterals``. The- ``vertices_plus`` path used here builds corners directly and- performs no size check, so this flag currently has no effect.+ validate_boxes: Reject a non-finite coordinate with ``RuntimeError``+ (``torch._assert_async``, skipped on MPS). There is no extent or shape+ check, as for ``'vertices_plus'`` in+ :meth:`~kornia.geometry.boxes.Boxes.from_tensor`.Returns::class:`VideoBoxes` with :attr:`temporal_channel_size` set todiff --git a/tests/augmentation/test_augmentation_compile.py b/tests/augmentation/test_augmentation_compile.pyindex d6060f97a..6b279dce3 100644--- a/tests/augmentation/test_augmentation_compile.py+++ b/tests/augmentation/test_augmentation_compile.py@@ -72,6 +72,18 @@ class TestAugmentationCompile(BaseTester):self.assert_close(out_input, input.flip(-1))self.assert_close(out_mask, mask.flip(-1))+ def test_dynamo_sequential_bbox(self, device, dtype, torch_optimizer):+ # The 'bbox' key imports through Boxes.from_tensor('vertices_plus'), whose finiteness check is+ # asynchronous, so the box path compiles with fullgraph=True (#4177).+ input = torch.rand(2, 3, 8, 8, device=device, dtype=dtype)+ bbox = torch.tensor([[[1.0, 1.0], [4.0, 1.0], [4.0, 5.0], [1.0, 5.0]]], device=device, dtype=dtype)+ bbox = bbox.expand(2, 1, 4, 2).contiguous()+ aug = K.AugmentationSequential(K.RandomHorizontalFlip(p=1.0), data_keys=["input", "bbox"])+ expected = aug(input, bbox)+ actual = torch_optimizer(aug, fullgraph=True)(input, bbox)+ self.assert_close(actual[0], expected[0])+ self.assert_close(actual[1], expected[1])+def test_compile_distinct_classes(self, device, dtype, torch_optimizer):# More classes than Dynamo's default per-code-object cache limit (#4658).augmentations = [diff --git a/tests/geometry/test_boxes.py b/tests/geometry/test_boxes.pyindex 88ca27b0c..6c0546b3b 100644--- a/tests/geometry/test_boxes.py+++ b/tests/geometry/test_boxes.py@@ -61,6 +61,34 @@ class TestBoxes2D(BaseTester):with pytest.raises(ValueError, match="non-finite coordinates"):Boxes.from_tensor(invalid_source, mode=mode, validate_boxes=True)+ @pytest.mark.parametrize("mode", ["vertices", "vertices_plus"])+ @pytest.mark.parametrize("value", [float("nan"), float("inf"), float("-inf")])+ def test_convention_vertex_modes_reject_non_finite_coordinates_4177(self, mode, value, device, dtype):+ # Kornia#4177: vertex modes accept arbitrary finite quadrilaterals, but+ # validate_boxes=True rejects non-finite coordinates.+ if device.type != "cpu":+ # The check is torch._assert_async: skipped on MPS by design, a device-side assert on CUDA.+ pytest.skip("the vertex check raises synchronously only on CPU")+ vertices = torch.tensor(+ [[[0.0, 0.0], [4.0, 0.0], [4.0, 4.0], [0.0, 4.0]]],+ device=device,+ dtype=dtype,+ )+ vertices[0, 1, 0] = value++ with pytest.raises(RuntimeError, match="non-finite coordinates"):+ Boxes.from_tensor(vertices, mode=mode, validate_boxes=True)++ @pytest.mark.parametrize("mode", ["vertices", "vertices_plus"])+ def test_dynamo_vertex_import_is_fullgraph_4177(self, mode, device, dtype, torch_optimizer):+ # The vertex check is asynchronous, so a validated vertex import adds no graph break.+ vertices = torch.tensor([[[1.0, 2.0], [4.0, 1.0], [5.0, 4.0], [2.0, 5.0]]], device=device, dtype=dtype)++ def import_boxes(data: torch.Tensor) -> torch.Tensor:+ return Boxes.from_tensor(data, mode=mode, validate_boxes=True).data++ self.assert_close(torch_optimizer(import_boxes, fullgraph=True)(vertices), import_boxes(vertices))+@pytest.mark.parametrize("container", ["Boxes", "Boxes3D"])def test_convention_from_tensor_opt_out_preserves_non_finite_input_4238(self, container, device, dtype):# kornia#4238 (2D) and kornia#4258 (3D): validate_boxes=False keeps a non-finite coordinate.@@ -156,18 +184,47 @@ class TestBoxes2D(BaseTester):self.assert_close(widths, torch.tensor([5.0], device=device, dtype=dtype), atol=0.0, rtol=0.0)@pytest.mark.parametrize("mode", ["vertices", "vertices_plus"])- def test_wart_vertices_import_is_not_validated_4177(self, mode, device, dtype):- # Wart pin for kornia#4177: neither vertex mode is validated. The exclusive- # 'vertices' import also subtracts one from fixed positions, so a non-rectangular- # quadrilateral is silently reshaped instead of rejected with validate_boxes=True.- # The -1 deformation is the inclusive offset tracked in kornia#3934.- quadrilateral = torch.tensor([[[0.0, 0.0], [9.0, 0.0], [3.0, 7.0], [0.0, 1.0]]], device=device, dtype=dtype)+ @pytest.mark.parametrize(+ "quadrilateral",+ [+ # Rotated quadrilateral.+ [[[1.0, 2.0], [4.0, 1.0], [5.0, 4.0], [2.0, 5.0]]],+ # Sheared quadrilateral.+ [[[3.0, 2.0], [6.0, 2.0], [7.0, 3.0], [4.0, 3.0]]],+ # Projective quadrilateral.+ [[[0.0, 0.0], [8.0, 1.0], [7.0, 6.0], [1.0, 5.0]]],+ # Reordered vertices.+ [[[0.0, 0.0], [0.0, 5.0], [6.0, 5.0], [6.0, 0.0]]],+ ],+ )+ def test_convention_vertex_modes_accept_arbitrary_quadrilaterals_4177(self, mode, quadrilateral, device, dtype):+ # kornia#4177: the vertex modes validate finiteness only, so validate_boxes=True accepts rotated, sheared,+ # projective and reordered quadrilaterals. 'vertices_plus' stores them unchanged; 'vertices' subtracts the+ # inclusive offset at fixed vertex slots, which deforms them (kornia#3934).+ quadrilateral = torch.tensor(quadrilateral, device=device, dtype=dtype)+boxes = Boxes.from_tensor(quadrilateral, mode=mode, validate_boxes=True)+expected = quadrilateral.clone()if mode == "vertices":- expected = torch.tensor([[[0.0, 0.0], [8.0, 0.0], [2.0, 6.0], [0.0, 0.0]]], device=device, dtype=dtype)+ expected[..., 1:3, 0] -= 1+ expected[..., 2:, 1] -= 1+self.assert_close(boxes.data, expected, atol=0.0, rtol=0.0)+ def test_vertices_plus_import_accepts_one_pixel_box_4177(self, device, dtype):+ # Kornia#4177: vertices_plus may represent a one-pixel box with four+ # identical vertices, and validate_boxes=True must accept it.+ vertices = torch.tensor(+ [[[5.0, 5.0], [5.0, 5.0], [5.0, 5.0], [5.0, 5.0]]],+ device=device,+ dtype=dtype,+ )++ boxes = Boxes.from_tensor(vertices, mode="vertices_plus", validate_boxes=True)++ self.assert_close(boxes.data, vertices, atol=0.0, rtol=0.0)+def test_convention_constructor_mode_is_only_an_export_label(self, device, dtype):vertices = torch.tensor([[[1.0, 2.0], [5.0, 2.0], [5.0, 4.0], [1.0, 4.0]]], device=device, dtype=dtype)constructed = Boxes(vertices, mode="vertices").to_tensor()@@ -187,6 +244,8 @@ class TestBoxes2D(BaseTester):sheared = boxes.transform_boxes(shear)expected_data = torch.tensor([[[3.0, 2.0], [6.0, 2.0], [7.0, 3.0], [4.0, 3.0]]], device=device, dtype=dtype)self.assert_close(sheared.data, expected_data, atol=0.0, rtol=0.0)+ imported = Boxes.from_tensor(sheared.data, mode="vertices_plus", validate_boxes=True)+ self.assert_close(imported.data, sheared.data, atol=0.0, rtol=0.0)expected_export = torch.tensor([[[3.0, 2.0], [7.0, 2.0], [7.0, 3.0], [3.0, 3.0]]], device=device, dtype=dtype)self.assert_close(sheared.to_tensor("vertices_plus"), expected_export, atol=0.0, rtol=0.0)@@ -1929,6 +1988,28 @@ class TestVideoBoxes(BaseTester):assert isinstance(video_boxes, VideoBoxes)assert video_boxes.temporal_channel_size == boxes.size(1)+ def test_validate_boxes_preserves_arbitrary_quadrilaterals_4177(self, device, dtype):+ boxes = self._sample_video_boxes(device, dtype)+ boxes[0, 0, 0] = torch.tensor(+ [[0.0, 0.0], [9.0, 0.0], [3.0, 7.0], [0.0, 1.0]],+ device=device,+ dtype=dtype,+ )++ video_boxes = VideoBoxes.from_tensor(boxes, validate_boxes=True)++ self.assert_close(video_boxes.data, boxes.reshape(-1, 1, 4, 2), atol=0.0, rtol=0.0)++ @pytest.mark.parametrize("value", [float("nan"), float("inf"), float("-inf")])+ def test_validate_boxes_rejects_non_finite_vertices_4177(self, value, device, dtype):+ if device.type != "cpu":+ pytest.skip("the vertex check is torch._assert_async: synchronous only on CPU")+ boxes = self._sample_video_boxes(device, dtype)+ boxes[0, 0, 0, 0, 0] = value++ with pytest.raises(RuntimeError, match="non-finite coordinates"):+ VideoBoxes.from_tensor(boxes, validate_boxes=True)+def test_exception(self, device, dtype):frame = self._sample_video_boxes(device, dtype, batch=1, time=1)[0] # (T, N, 4, 2)with pytest.raises(ValueError):