π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
fix(augmentation): fix RandomMosaic boxes and output size (#4679)
NiteeshGowda72b5fab34984cb
diff --git a/changelog.d/4679.fixed.md b/changelog.d/4679.fixed.mdnew file mode 100644index 000000000..2254da1cd--- /dev/null+++ b/changelog.d/4679.fixed.md@@ -0,0 +1,10 @@+`RandomMosaic` now respects `output_size` when transforming bounding boxes and no longer crashes with+`cropping_mode="resample"` when `output_size=None`. With an explicit `output_size`, both cropping modes now take an+unscaled `output_size` window of the composed canvas, so the boxes stay on their tiles; before, `"slice"` rescaled an+input-sized crop whenever every sample drew the same corner and zero-padded it otherwise. When the gate selects only+part of the batch, an unselected sample's boxes are now returned unchanged; before, they were clipped to the input+extent and a box below `min_bbox_size` was replaced by `[0, 0, 1, 1]`. For a tensor box input the unselected row is+still padded to the mosaic box count, now with all-zero (zero-area) rows instead of the `[0, 0, 1, 1]` placeholder+that looked like a real box (inside `AugmentationSequential`, `"bbox_xyxy"` padding was already all-zero). A list box+input still comes back as a list with one tensor per sample, and an unselected sample's tensor now holds only its own+boxes instead of being padded with placeholder rows. Fixes #4652.diff --git a/kornia/augmentation/_2d/mix/base.py b/kornia/augmentation/_2d/mix/base.pyindex ed1da7112..0236d7164 100644--- a/kornia/augmentation/_2d/mix/base.py+++ b/kornia/augmentation/_2d/mix/base.py@@ -26,11 +26,19 @@ from kornia.augmentation.utils import (_transform_output_shape,_validate_input_dtype,)+from kornia.augmentation.utils.helpers import _boxes_to_padded_tensorfrom kornia.constants import DataKey, DTypefrom kornia.core.check import KORNIA_UNWRAPfrom kornia.geometry.boxes import Boxes+def _export_boxes(box: Boxes, mode: str, box_input: Any) -> torch.Tensor:+ # A list box input comes back as a list of per-sample tensors; a tensor input as one dense tensor.+ if isinstance(box_input, list):+ return KORNIA_UNWRAP(box.to_tensor(mode), torch.Tensor)+ return _boxes_to_padded_tensor(box, mode)++class MixAugmentationBaseV2(_BasicAugmentationBase):r"""MixAugmentationBase base class for customized mix augmentation implementations.@@ -296,15 +304,15 @@ class MixAugmentationBaseV2(_BasicAugmentationBase):elif dcate == DataKey.BBOX:box = Boxes.from_tensor(_input, mode="vertices", validate_boxes=False)box = self.transform_boxes(box, self._params, self.flags)- output = KORNIA_UNWRAP(box.to_tensor("vertices"), torch.Tensor)+ output = _export_boxes(box, "vertices", _input)elif dcate == DataKey.BBOX_XYXY:box = Boxes.from_tensor(_input, mode="xyxy", validate_boxes=False)box = self.transform_boxes(box, self._params, self.flags)- output = KORNIA_UNWRAP(box.to_tensor("xyxy"), torch.Tensor)+ output = _export_boxes(box, "xyxy", _input)elif dcate == DataKey.BBOX_XYWH:box = Boxes.from_tensor(_input, mode="xywh", validate_boxes=False)box = self.transform_boxes(box, self._params, self.flags)- output = KORNIA_UNWRAP(box.to_tensor("xywh"), torch.Tensor)+ output = _export_boxes(box, "xywh", _input)elif dcate == DataKey.KEYPOINTS:output = self.transform_keypoint(_input, self._params, self.flags)elif dcate == DataKey.CLASS:diff --git a/kornia/augmentation/_2d/mix/mosaic.py b/kornia/augmentation/_2d/mix/mosaic.pyindex 29ddf2f85..5796a9a7e 100644--- a/kornia/augmentation/_2d/mix/mosaic.py+++ b/kornia/augmentation/_2d/mix/mosaic.py@@ -25,6 +25,7 @@ from kornia.augmentation._2d.mix.base import MixAugmentationBaseV2from kornia.constants import DataKey, Resamplefrom kornia.core.check import KORNIA_UNWRAPfrom kornia.core.ops import eye_like+from kornia.core.utils import is_exportingfrom kornia.geometry.boxes import Boxesfrom kornia.geometry.transform import crop_by_indices, crop_by_transform_mat, get_perspective_transform@@ -63,7 +64,7 @@ class RandomMosaic(MixAugmentationBaseV2):align_corners: interpolation flag.cropping_mode: The used algorithm to crop. ``slice`` will use advanced slicing to extract the torch.Tensor basedon the sampled indices. ``resample`` will use `warp_affine` using the affine transformation- to extract and resize at once. Use `slice` for efficiency, or `resample` for proper+ to extract the window. Use `slice` for efficiency, or `resample` for properdifferentiability.Examples:@@ -79,22 +80,35 @@ class RandomMosaic(MixAugmentationBaseV2):Convention:- ``output_size`` and the default output shape are ordered ``(height, width)``. With ``output_size=None``- and the default ``cropping_mode="slice"`` the output preserves the input's ``(H, W)`` even when they- differ; ``cropping_mode="resample"`` needs an explicit ``output_size``; without one it raises ``TypeError``- once the gate selects a sample, and a call that selects none returns the input- (`#4652 <https://github.com/kornia/kornia/issues/4652>`_). ``start_ratio_range`` draws a pair- used as ``(x / W, y / H)`` for the crop's top-left corner. These are the repaired axis conventions from+ the output preserves the input's ``(H, W)`` even when they differ, in both ``cropping_mode="slice"`` and+ ``cropping_mode="resample"``. ``start_ratio_range`` draws a pair used as ``(x / W, y / H)`` for the crop's+ top-left corner. These are the repaired axis conventions from`#4438 <https://github.com/kornia/kornia/issues/4438>`_.- ``p`` is per sample and this class fixes ``same_on_batch=False``. It composes ``mosaic_grid[0]`` tilesalong width and ``mosaic_grid[1]`` tiles along height, then crops each result. It supports``"bbox"``, ``"bbox_xyxy"``, and ``"bbox_xywh"`` in addition to image inputs; it does not supportmasks, keypoints, or class labels.- - With an explicit ``output_size`` an unselected sample is zero-padded or cropped to that size rather than- returned unchanged. Boxes are not rescaled or clipped to ``output_size``, and whenever any sample is- selected an unselected sample's own boxes are clipped to the input extent, replaced by a- ``[0, 0, 1, 1]`` placeholder when smaller than ``min_bbox_size``, and padded with that placeholder to- the grid's box count, although that sample is not mixed- (`#4652 <https://github.com/kornia/kornia/issues/4652>`_).+ - Both ``cropping_mode`` values take an ``output_size`` window of the composed canvas at the drawn corner,+ without rescaling; where the window passes the canvas edge it is zero. With an explicit ``output_size`` an+ unselected sample is zero-padded or cropped to that size rather than returned unchanged. The boxes of a+ selected sample are translated with its tiles, not rescaled, and clipped to the output window+ ``[0, W_out] x [0, H_out]``.+ - A tensor box input comes back as one dense tensor. When the gate selects any sample, every row holds+ ``N * mosaic_grid[0] * mosaic_grid[1]`` boxes for ``N`` input boxes per sample: a selected row holds its+ mosaic boxes, and an unselected row holds its own ``N`` boxes unchanged followed by all-zero padding rows+ (``[0, 0, 0, 0]`` in ``"bbox_xyxy"`` and ``"bbox_xywh"``, four ``(0, 0)`` vertices in ``"bbox"``), which+ have zero area. When the gate selects no sample the boxes are returned unchanged with their ``N`` rows.+ - A list box input comes back as a list with one tensor per sample, from a direct call and from+ :class:`~kornia.augmentation.container.AugmentationSequential` alike, whatever the gate selects. An+ unselected sample's tensor is its own boxes unchanged, with no padding rows. A selected sample's tensor+ takes its box count from the wrong source images, so it can drop real boxes or keep padding rows+ (`#4715 <https://github.com/kornia/kornia/issues/4715>`_).+ - In either form, a selected sample's box that falls below ``min_bbox_size`` is zeroed by+ :meth:`~kornia.geometry.boxes.Boxes.filter_boxes_by_area`. A direct call exports it as ``[0, 0, 1, 1]``+ in ``"bbox_xyxy"`` and ``"bbox_xywh"``, not as zero-area padding+ (`#4714 <https://github.com/kornia/kornia/issues/4714>`_); inside+ :class:`~kornia.augmentation.container.AugmentationSequential` it is ``[0, 0, 1, 1]`` in ``"bbox_xywh"``+ and ``[0, 0, 0, 0]`` in ``"bbox_xyxy"``."""@@ -143,6 +157,7 @@ class RandomMosaic(MixAugmentationBaseV2):offset_end = dst_box[0, 2].repeat(input.data.shape[0], 1)idx = torch.arange(0, input.data.shape[0], device=input.device, dtype=torch.long)[to_apply]+ num_boxes = input.data.shape[1]maybe_out_boxes: Optional[Boxes] = None# ``batch_shapes`` and ``src_box`` are full-batch sized.# Subset them to match ``idx`` (the to_apply indices).@@ -159,16 +174,27 @@ class RandomMosaic(MixAugmentationBaseV2):_idx = i * flags["mosaic_grid"][1] + j_box._data[params["permutation"][:, 0]] = _box._data[params["permutation"][:, _idx]]_box.translate(_offset, inplace=True)- # zero-out unrelated batch elements.- _box._data[~to_apply] = 0if maybe_out_boxes is None:- _box._data[~to_apply] = input._data[~to_apply]maybe_out_boxes = _boxelse:KORNIA_UNWRAP(maybe_out_boxes, Boxes).merge(_box, inplace=True)out_boxes: Boxes = KORNIA_UNWRAP(maybe_out_boxes, Boxes)out_boxes.clamp(offset, offset_end, inplace=True)out_boxes.filter_boxes_by_area(flags["min_bbox_size"], inplace=True)++ if not bool(to_apply.all()):+ # An unselected sample keeps its own boxes unchanged, followed by padding up to the mosaic box count.+ # The padding is recorded in ``_N`` and exported as all-zero (zero-area) rows.+ out_boxes._data[~to_apply, :num_boxes] = input._data[~to_apply]+ out_boxes._data[~to_apply, num_boxes:] = 0.0+ padding = out_boxes._data.shape[1] - num_boxes+ merged_padding = out_boxes._N if out_boxes._N is not None else [0] * len(to_apply)+ input_padding = input._N if input._N is not None else [0] * len(to_apply)+ out_boxes._N = [+ merged if bool(selected) else own + padding+ for selected, merged, own in zip(to_apply, merged_padding, input_padding)+ ]+return out_boxesdef apply_transform_class(@@ -222,15 +248,26 @@ class RandomMosaic(MixAugmentationBaseV2):else:padding_mode = flags["padding_mode"]+ output_size = (+ tuple(params["batch_shapes"][0, -2:].tolist()) if flags["output_size"] is None else flags["output_size"]+ )return crop_by_transform_mat(input,transform[:, :2, :],- flags["output_size"],+ output_size,mode=flags["resample"].name.lower(),padding_mode=padding_mode,align_corners=flags["align_corners"],)if flags["cropping_mode"] == "slice": # uses advanced slicing to crop+ if flags["output_size"] is not None and input.shape[0] > 0 and not is_exporting():+ # The window is ``output_size`` and may pass the canvas edge. Zero-pad the canvas so every slice is+ # exactly ``output_size``: ``crop_by_indices`` resizes rather than pads when all boxes coincide.+ src = params["src"].long()+ pad_w = int(src[:, 1, 0].max()) + 1 - input.shape[-1]+ pad_h = int(src[:, 3, 1].max()) + 1 - input.shape[-2]+ if pad_w > 0 or pad_h > 0:+ input = F.pad(input, [0, max(pad_w, 0), 0, max(pad_h, 0)])return crop_by_indices(input, params["src"], flags["output_size"], shape_compensation="F.pad")raise NotImplementedError(f"Not supported type: {flags['cropping_mode']}.")diff --git a/kornia/augmentation/container/augment.py b/kornia/augmentation/container/augment.pyindex f22296ca5..0421f9de8 100644--- a/kornia/augmentation/container/augment.py+++ b/kornia/augmentation/container/augment.py@@ -24,6 +24,7 @@ from torch import nnfrom kornia.augmentation._2d.base import RigidAffineAugmentationBase2Dfrom kornia.augmentation._3d.base import AugmentationBase3D, RigidAffineAugmentationBase3Dfrom kornia.augmentation.base import _AugmentationBase+from kornia.augmentation.utils.helpers import _boxes_to_padded_tensorfrom kornia.constants import DataKey, Resamplefrom kornia.core.ops import eye_likefrom kornia.core.utils import is_autocast_enabled, is_exporting@@ -735,6 +736,9 @@ class AugmentationSequential(TransformMatrixMinIn, ImageSequential):# TODO: handle 3d scenariosif isinstance(in_arg, Boxes):return out_arg+ if isinstance(in_arg, torch.Tensor) and not isinstance(out_arg, VideoBoxes):+ # A dense input stays dense; padding added by an augmentation (e.g. RandomMosaic) is exported as zeros.+ return _boxes_to_padded_tensor(out_arg, mode)return out_arg.to_tensor(mode=mode)diff --git a/kornia/augmentation/random_generator/_2d/mosaic.py b/kornia/augmentation/random_generator/_2d/mosaic.pyindex 0d8f1ed37..2d28ce333 100644--- a/kornia/augmentation/random_generator/_2d/mosaic.py+++ b/kornia/augmentation/random_generator/_2d/mosaic.py@@ -83,7 +83,7 @@ class MosaicGenerator(RandomGeneratorBase):def forward(self, batch_shape: Tuple[int, ...], same_on_batch: bool = False) -> Dict[str, torch.Tensor]:batch_size = batch_shape[0]input_sizes = (batch_shape[-2], batch_shape[-1])- # output_size = input_sizes if self.output_size is None else self.output_size+ output_size = input_sizes if self.output_size is None else self.output_size_common_param_check(batch_size, same_on_batch)_device, _dtype = _extract_device_dtype([self.mosaic_grid])@@ -105,11 +105,18 @@ class MosaicGenerator(RandomGeneratorBase):crop_src = bbox_generator(start_corner_x,start_corner_y,- start_corner_x.clone().fill_(input_sizes[1]),- start_corner_y.clone().fill_(input_sizes[0]),+ start_corner_x.clone().fill_(output_size[1]),+ start_corner_y.clone().fill_(output_size[0]),)crop_dst = _constant_tensor(- [[[0, 0], [input_sizes[1] - 1, 0], [input_sizes[1] - 1, input_sizes[0] - 1], [0, input_sizes[0] - 1]]],+ [+ [+ [0, 0],+ [output_size[1] - 1, 0],+ [output_size[1] - 1, output_size[0] - 1],+ [0, output_size[0] - 1],+ ]+ ],device=_device,dtype=_dtype,).repeat(batch_size, 1, 1)diff --git a/kornia/augmentation/utils/helpers.py b/kornia/augmentation/utils/helpers.pyindex 3e38cbed0..99145a242 100644--- a/kornia/augmentation/utils/helpers.py+++ b/kornia/augmentation/utils/helpers.py@@ -24,6 +24,7 @@ import torch.nn.functional as Ffrom torch.distributions import Beta, Uniformfrom kornia.core.utils import _extract_device_dtype+from kornia.geometry.boxes import Boxesfrom kornia.geometry.keypoints import Keypoints@@ -67,6 +68,26 @@ def _flatten_constant(data: Any, shape: List[int], leaves: List[Any], depth: intleaves.append(data)+def _boxes_to_padded_tensor(boxes: Boxes, mode: str) -> torch.Tensor:+ """Export ``boxes`` as one dense tensor whose trailing padding rows are exactly zero.++ :class:`~kornia.geometry.boxes.Boxes` records per-sample trailing padding in ``_N`` and its default export+ returns a ragged list for such an object. The padding rows are zeroed after the export rather than stored as+ zeros, because a zero stored box exports as ``[0, 0, 1, 1]`` in the exclusive ``'xyxy'``, ``'xywh'`` and+ ``'vertices'`` modes, which reads as a real one-pixel box.+ """+ out = boxes.to_tensor(mode, as_padded_sequence=True)+ if not isinstance(out, torch.Tensor):+ raise TypeError(f"Expected a padded tensor export. Got {type(out)}.")+ if boxes._N is None:+ return out+ num_boxes = out.shape[1]+ real = torch.tensor([num_boxes - n for n in boxes._N], device=out.device)+ valid = torch.arange(num_boxes, device=out.device)[None] < real[:, None]+ valid = valid.reshape(valid.shape + (1,) * (out.dim() - 2))+ return torch.where(valid, out, torch.zeros((), device=out.device, dtype=out.dtype))++def _constant_tensor(data: Union[float, List[Any], Tuple[Any, ...]],*,diff --git a/tests/augmentation/test_augmentation_mix.py b/tests/augmentation/test_augmentation_mix.pyindex 1da56c01b..55e93f687 100644--- a/tests/augmentation/test_augmentation_mix.py+++ b/tests/augmentation/test_augmentation_mix.py@@ -31,6 +31,7 @@ from kornia.augmentation import (RandomTransplantation3D,)from kornia.geometry.bbox import infer_bbox_shape+from kornia.geometry.boxes import Boxesfrom testing.base import BaseTester@@ -568,6 +569,128 @@ class TestRandomMosaic(BaseTester):torch.testing.assert_close(top_left, expected)+ def test_boxes_follow_output_size_4652(self, device, dtype):+ torch.manual_seed(2)++ input = torch.rand(4, 1, 6, 8, device=device, dtype=dtype)+ boxes = torch.tensor([[[1.0, 1.0, 4.0, 4.0]]] * 4, device=device, dtype=dtype)++ aug = RandomMosaic(+ output_size=(4, 10),+ p=1.0,+ data_keys=["input", "bbox_xyxy"],+ )++ output, output_boxes = aug(input, boxes)++ assert output.shape == (4, 1, 4, 10)+ assert bool((output_boxes[..., 1] <= 4).all())+ assert bool((output_boxes[..., 3] <= 4).all())++ def test_resample_output_size_none_matches_slice_4652(self, device, dtype):+ torch.manual_seed(2)++ input = torch.rand(4, 1, 6, 8, device=device, dtype=dtype)++ slice_output = RandomMosaic(+ cropping_mode="slice",+ output_size=None,+ p=1.0,+ data_keys=["input"],+ )(input)++ resample_output = RandomMosaic(+ cropping_mode="resample",+ output_size=None,+ p=1.0,+ data_keys=["input"],+ )(input)++ assert resample_output.shape == slice_output.shape == input.shape++ def test_partial_batch_does_not_add_phantom_boxes_4652(self, device, dtype):+ torch.manual_seed(2)++ input = torch.rand(4, 1, 6, 8, device=device, dtype=dtype)+ boxes = torch.tensor([[[1.0, 1.0, 4.0, 4.0]]] * 4, device=device, dtype=dtype)++ aug = RandomMosaic(+ p=0.0,+ data_keys=["input", "bbox_xyxy"],+ )++ params = aug._param_generator(torch.Size(input.shape))+ params["batch_prob"] = torch.tensor([0.0, 1.0, 0.0, 1.0], device=device)++ box_object = Boxes.from_tensor(boxes, mode="xyxy")+ output = aug.apply_transform_boxes(box_object, params, aug.flags)++ output_boxes = output.to_tensor("xyxy")++ assert len(output_boxes) == 4+ assert output_boxes[0].shape == (1, 4)+ assert output_boxes[1].shape == (4, 4)+ assert output_boxes[2].shape == (1, 4)+ assert output_boxes[3].shape == (4, 4)++ torch.testing.assert_close(output_boxes[0], boxes[0])+ torch.testing.assert_close(output_boxes[2], boxes[2])++ def test_partial_batch_preserves_unselected_out_of_bounds_boxes_4679(self, device, dtype):+ input = torch.rand(4, 1, 6, 8, device=device, dtype=dtype)+ boxes = torch.tensor(+ [+ [[2.0, 1.0, 30.0, 20.0]],+ [[1.0, 1.0, 4.0, 4.0]],+ [[3.0, 2.0, 25.0, 18.0]],+ [[1.0, 1.0, 4.0, 4.0]],+ ],+ device=device,+ dtype=dtype,+ )++ aug = RandomMosaic(+ p=0.0,+ data_keys=["input", "bbox_xyxy"],+ )++ params = aug._param_generator(torch.Size(input.shape))+ params["batch_prob"] = torch.tensor([0.0, 1.0, 0.0, 1.0], device=device)++ box_object = Boxes.from_tensor(boxes, mode="xyxy")+ output = aug.apply_transform_boxes(box_object, params, aug.flags).to_tensor("xyxy")++ torch.testing.assert_close(output[0], boxes[0])+ torch.testing.assert_close(output[2], boxes[2])++ def test_partial_batch_preserves_unselected_filtered_boxes_4679(self, device, dtype):+ input = torch.rand(4, 1, 6, 8, device=device, dtype=dtype)+ boxes = torch.tensor(+ [+ [[1.0, 1.0, 4.0, 4.0]],+ [[1.0, 1.0, 4.0, 4.0]],+ [[1.0, 1.0, 2.0, 2.0]],+ [[1.0, 1.0, 4.0, 4.0]],+ ],+ device=device,+ dtype=dtype,+ )++ aug = RandomMosaic(+ p=0.0,+ min_bbox_size=19.0,+ data_keys=["input", "bbox_xyxy"],+ )++ params = aug._param_generator(torch.Size(input.shape))+ params["batch_prob"] = torch.tensor([0.0, 1.0, 0.0, 1.0], device=device)++ box_object = Boxes.from_tensor(boxes, mode="xyxy")+ output = aug.apply_transform_boxes(box_object, params, aug.flags).to_tensor("xyxy")++ torch.testing.assert_close(output[0], boxes[0])+ torch.testing.assert_close(output[2], boxes[2])+@pytest.mark.parametrize(("keepdim", "expected_shape"), [(False, (1, 1, 6, 8)), (True, (1, 6, 8))])def test_non_square_unbatched_keepdim_4438(self, keepdim, expected_shape):torch.manual_seed(0)diff --git a/tests/augmentation/test_conventions_mix.py b/tests/augmentation/test_conventions_mix.pyindex 3a754f305..ddd61fe83 100644--- a/tests/augmentation/test_conventions_mix.py+++ b/tests/augmentation/test_conventions_mix.py@@ -17,6 +17,7 @@from __future__ import annotations+import mathimport warningsimport pytest@@ -525,38 +526,192 @@ class TestMixConventions(BaseTester):assert independent._params["patch_coords"].unique(dim=0).shape[0] > 1@pytest.mark.device_agnostic- def test_wart_mosaic_output_size_boxes_and_resample_default_4652(self):- image = torch.rand(4, 1, 6, 8)- boxes = torch.tensor([[[1.0, 1.0, 4.0, 4.0]]] * 4)- assert K.RandomMosaic(output_size=(4, 10), p=0.0)(image).shape == (4, 1, 4, 10)- # Replay one recorded draw under both settings, with a hand-set gate that selects rows 1 and 3 only.- reference = K.RandomMosaic(p=1.0, data_keys=["input", "bbox_xyxy"])+ def test_convention_mosaic_boxes_follow_output_size_and_resample_defaults_to_input_size(self):+ # Fixed by #4679 (#4652): boxes used to be clipped to the input extent rather than to ``output_size``, and+ # ``cropping_mode="resample"`` without an ``output_size`` raised ``TypeError`` once a sample was selected.+ image = torch.rand(3, 1, 6, 8)+ assert K.RandomMosaic(output_size=(4, 10), p=0.0)(image).shape == (3, 1, 4, 10)+ # Full-tile boxes on a (6, 8) input; the crop starts at (x, y) = (4, 3) of the (12, 16) canvas and is+ # (4, 10) high and wide, so each tile's box is clipped to the output window [0, 10] x [0, 4].+ boxes = torch.tensor([[[0.0, 0.0, 8.0, 6.0]]] * 3)+ aug = K.RandomMosaic(output_size=(4, 10), start_ratio_range=(0.5, 0.5), p=1.0, data_keys=["input", "bbox_xyxy"])+ output, output_boxes = aug(image, boxes)+ assert output.shape == (3, 1, 4, 10)+ # The input extent would give [0, 3, 4, 6], [4, 0, 8, 3] and [4, 3, 8, 6] instead.+ expected = torch.tensor(+ [[0.0, 0.0, 4.0, 3.0], [0.0, 3.0, 4.0, 4.0], [4.0, 0.0, 10.0, 3.0], [4.0, 3.0, 10.0, 4.0]]+ )+ self.assert_close(output_boxes, expected.expand(3, -1, -1))+ # Without output_size, resample crops to the input size and agrees with slice on the same draw.+ sliced = K.RandomMosaic(start_ratio_range=(0.5, 0.5), p=1.0)+ expected_image = sliced(image)+ resampled = K.RandomMosaic(start_ratio_range=(0.5, 0.5), p=1.0, cropping_mode="resample")(+ image, params=sliced._params+ )+ assert resampled.shape == image.shape+ self.assert_close(resampled, expected_image)+ self.assert_close(K.RandomMosaic(p=0.0, cropping_mode="resample")(image), image)++ @pytest.mark.parametrize("cropping_mode", ["slice", "resample"])+ @pytest.mark.parametrize("output_size", [(4, 10), (9, 5), (14, 18), (4, 14), (13, 6)])+ @pytest.mark.parametrize("batch_size", [1, 3])+ def test_convention_mosaic_output_size_crops_an_unscaled_window_of_the_canvas(+ self, cropping_mode, output_size, batch_size, device, dtype+ ):+ # Both cropping modes take an ``output_size`` window of the composed canvas at the drawn corner, without+ # rescaling; past the canvas edge the window is zero. That is what keeps the boxes, which are translated and+ # not rescaled, on their tiles. Before, resample squeezed an input-sized window into ``output_size`` (#4679+ # review), and slice did so whenever every sample drew the same corner (``crop_by_indices`` ignored+ # ``shape_compensation="F.pad"`` on its uniform path).+ image = torch.rand(batch_size, 1, 6, 8, device=device, dtype=dtype)+ aug = K.RandomMosaic(+ output_size=output_size,+ start_ratio_range=(0.5, 0.5),+ p=1.0,+ cropping_mode=cropping_mode,+ resample="nearest",+ )+ output = aug(image)+ canvas = aug._compose_images(image, aug._params, aug.flags) # (12, 16); the corner is (x, y) = (4, 3)+ window = canvas[..., 3 : 3 + output_size[0], 4 : 4 + output_size[1]]+ expected = torch.nn.functional.pad(+ window, [0, output_size[1] - window.shape[-1], 0, output_size[0] - window.shape[-2]]+ )+ assert output.shape == (batch_size, 1, *output_size)+ self.assert_close(output, expected)++ @pytest.mark.parametrize("cropping_mode", ["slice", "resample"])+ def test_convention_mosaic_boxes_stay_on_their_tiles_for_a_random_corner(self, cropping_mode, device, dtype):+ # Each source image is one constant and its box covers the whole image, so the pixels inside every output+ # box must all come from the one tile the box claims. The box is shrunk by one pixel per side: a half-precision+ # corner rounds by up to a pixel, while the defect this pins moved a tile boundary by a whole tile fraction.+ image = torch.arange(1.0, 5.0, device=device, dtype=dtype).view(4, 1, 1, 1).expand(4, 1, 6, 8).contiguous()+ boxes = torch.tensor([[[0.0, 0.0, 8.0, 6.0]]], device=device, dtype=dtype).expand(4, 1, 4)+ for output_size in ((4, 10), (9, 5), (8, 12)):+ for seed in range(5):+ torch.manual_seed(seed)+ aug = K.RandomMosaic(+ output_size=output_size,+ p=1.0,+ cropping_mode=cropping_mode,+ resample="nearest",+ data_keys=["input", "bbox_xyxy"],+ )+ output, out_boxes = aug(image, boxes)+ for b in range(4):+ for x1, y1, x2, y2 in out_boxes[b].tolist():+ x1, y1, x2, y2 = math.ceil(x1) + 1, math.ceil(y1) + 1, math.floor(x2) - 1, math.floor(y2) - 1+ if x2 <= x1 or y2 <= y1:+ continue+ values = output[b, 0, y1:y2, x1:x2].unique()+ assert values.numel() == 1 and values.item() != 0, (output_size, seed, b)++ def test_convention_mosaic_unselected_list_row_keeps_its_own_box_count(self, device, dtype):+ # A list input carries its own padding: a one-box sample in a list whose longest sample has two boxes. An+ # unselected row must come back with just its own box, not its own padding row as a phantom box.+ image = torch.rand(2, 1, 6, 8, device=device, dtype=dtype)+ boxes = [+ torch.tensor([[1.0, 1.0, 4.0, 4.0]], device=device, dtype=dtype),+ torch.tensor([[1.0, 1.0, 3.0, 3.0], [2.0, 1.0, 6.0, 5.0]], device=device, dtype=dtype),+ ]+ mosaic = K.RandomMosaic(p=1.0)+ pipeline = K.AugmentationSequential(mosaic, data_keys=["input", "bbox_xyxy"])+ pipeline(image, boxes)+ params = pipeline._params+ params[0].data["batch_prob"] = params[0].data["batch_prob"].new_tensor([0.0, 1.0])+ _, out_boxes = pipeline(image, boxes, params=params)+ assert isinstance(out_boxes, list)+ self.assert_close(out_boxes[0], boxes[0])++ @pytest.mark.parametrize("data_key", ["bbox_xyxy", "bbox_xywh", "bbox"])+ @pytest.mark.parametrize("gate", [(0.0, 0.0), (1.0, 1.0), (0.0, 1.0)])+ def test_convention_mosaic_list_boxes_come_back_as_a_list(self, gate, data_key, device, dtype):+ # Maintainer ruling on #4679: a list box input comes back as a list, from a direct call and from+ # AugmentationSequential, at every gate; an unselected sample's tensor is its own boxes, with no padding.+ image = torch.rand(2, 1, 6, 8, device=device, dtype=dtype)+ corners = self._mosaic_boxes(2, data_key, device, dtype)+ boxes = [corners[0, :1], corners[1]]+ pipeline = K.AugmentationSequential(K.RandomMosaic(p=1.0), data_keys=["input", data_key])+ pipeline(image, boxes)+ params = pipeline._params+ params[0].data["batch_prob"] = params[0].data["batch_prob"].new_tensor(gate)+ _, piped = pipeline(image, boxes, params=params)+ _, direct = K.RandomMosaic(data_keys=["input", data_key])(image, boxes, params=params[0].data)+ for out_boxes in (direct, piped):+ assert isinstance(out_boxes, list) and len(out_boxes) == 2+ for sample, selected in enumerate(gate):+ if not selected:+ self.assert_close(out_boxes[sample], boxes[sample])++ @staticmethod+ def _mosaic_boxes(num_boxes: int, data_key: str, device, dtype) -> torch.Tensor:+ corners = torch.tensor([[1.0, 1.0, 4.0, 4.0], [2.0, 1.0, 6.0, 5.0]], device=device, dtype=dtype)[:num_boxes]+ boxes = corners[None] + 0.25 * torch.arange(4, device=device, dtype=dtype).view(4, 1, 1) # distinct rows+ if data_key != "bbox":+ return boxes+ x1, y1, x2, y2 = boxes.unbind(-1)+ return torch.stack([torch.stack(v, -1) for v in ((x1, y1), (x2, y1), (x2, y2), (x1, y2))], -2)++ @pytest.mark.parametrize("num_boxes", [1, 2])+ @pytest.mark.parametrize("data_key", ["bbox_xyxy", "bbox_xywh", "bbox"])+ def test_convention_mosaic_partial_gate_pads_unselected_rows_with_zero_area_boxes(+ self, num_boxes, data_key, device, dtype+ ):+ # Maintainer ruling on #4679 (#4652): a tensor box input always comes back dense. An unselected row keeps+ # its own boxes, followed by all-zero padding rather than the [0, 0, 1, 1] placeholder that reads as a real+ # 1x1 box.+ image = torch.rand(4, 1, 6, 8, device=device, dtype=dtype)+ boxes = self._mosaic_boxes(num_boxes, data_key, device, dtype)+ reference = K.RandomMosaic(p=1.0, data_keys=["input", data_key])reference(image, boxes)params = dict(reference._params)- params["batch_prob"] = torch.tensor([0.0, 1.0, 0.0, 1.0])- selected = params["batch_prob"] > 0- results = [- K.RandomMosaic(output_size=output_size, p=1.0, data_keys=["input", "bbox_xyxy"])(- image, boxes, params=params- )- for output_size in (None, (4, 10))- ]- assert results[0][0].shape == (4, 1, 6, 8) and results[1][0].shape == (4, 1, 4, 10)- self.assert_close(results[0][1], results[1][1]) # the boxes ignore output_size- assert results[1][1][selected][..., 3].max() > 4 # a box bottom below the 4-pixel-high output- placeholder = torch.tensor([[1.0, 1.0, 4.0, 4.0]] + [[0.0, 0.0, 1.0, 1.0]] * 3)- self.assert_close(results[1][1][~selected], placeholder.expand(2, -1, -1))- # An unselected row keeps its image, yet its own boxes are clipped to the input extent and dropped to the- # placeholder below min_bbox_size.- loose = torch.tensor([[[2.0, 1.0, 30.0, 20.0], [1.0, 1.0, 5.0, 6.0]]] * 4)- strict = K.RandomMosaic(p=1.0, min_bbox_size=19.0, data_keys=["input", "bbox_xyxy"])- output, filtered = strict(image, loose, params=params)- self.assert_close(output[~selected], image[~selected])- own = torch.tensor([[2.0, 1.0, 8.0, 6.0], [0.0, 0.0, 1.0, 1.0]]) # clipped to W=8, H=6; the small one dropped- self.assert_close(filtered[~selected][:, :2], own.expand(2, -1, -1))- with pytest.raises(TypeError, match="NoneType"):- K.RandomMosaic(p=1.0, cropping_mode="resample")(image)- self.assert_close(K.RandomMosaic(p=0.0, cropping_mode="resample")(image), image) # no selection, no raise+ params["batch_prob"] = params["batch_prob"].new_tensor([0.0, 1.0, 0.0, 1.0])+ _, out_boxes = K.RandomMosaic(p=1.0, data_keys=["input", data_key])(image, boxes, params=params)+ assert isinstance(out_boxes, torch.Tensor)+ assert out_boxes.shape == (4, 4 * num_boxes, *boxes.shape[2:])+ self.assert_close(out_boxes[[0, 2], :num_boxes], boxes[[0, 2]])+ padding = out_boxes[[0, 2], num_boxes:]+ assert torch.equal(padding, torch.zeros_like(padding))++ def test_convention_mosaic_gate_leaves_selected_rows_and_p0_returns_the_input(self, device, dtype):+ # The partial gate changes only the unselected rows: a selected row matches the full-gate result of the+ # same draw, the full gate has no padding to add, and a gate that selects nothing returns the input.+ image = torch.rand(4, 1, 6, 8, device=device, dtype=dtype)+ boxes = self._mosaic_boxes(2, "bbox_xyxy", device, dtype)+ aug = K.RandomMosaic(p=1.0, data_keys=["input", "bbox_xyxy"])+ _, full = aug(image, boxes)+ params = dict(aug._params)+ params["batch_prob"] = params["batch_prob"].new_tensor([0.0, 1.0, 0.0, 1.0])+ _, partial = aug(image, boxes, params=params)+ assert isinstance(partial, torch.Tensor)+ assert partial.shape == full.shape == (4, 8, 4)+ self.assert_close(partial[[1, 3]], full[[1, 3]])+ _, untouched = K.RandomMosaic(p=0.0, data_keys=["input", "bbox_xyxy"])(image, boxes)+ assert untouched.shape == boxes.shape+ self.assert_close(untouched, boxes)++ @pytest.mark.parametrize("data_key", ["bbox_xyxy", "bbox_xywh", "bbox"])+ def test_convention_mosaic_partial_gate_pads_with_zeros_inside_augmentation_sequential(+ self, data_key, device, dtype+ ):+ # AugmentationSequential exports boxes through its own modes; the padding is zero there as well.+ image = torch.rand(4, 1, 6, 8, device=device, dtype=dtype)+ boxes = self._mosaic_boxes(2, data_key, device, dtype)+ mosaic = K.RandomMosaic(p=0.5)+ pipeline = K.AugmentationSequential(mosaic, data_keys=["input", data_key])+ for seed in range(20):+ torch.manual_seed(seed)+ _, out_boxes = pipeline(image, boxes)+ selected = mosaic._params["batch_prob"] > 0.5+ if 0 < int(selected.sum()) < 4:+ break+ else:+ pytest.fail("no partial gate in 20 draws")+ assert isinstance(out_boxes, torch.Tensor)+ assert out_boxes.shape == (4, 8, *boxes.shape[2:])+ self.assert_close(out_boxes[~selected, :2], boxes[~selected])+ padding = out_boxes[~selected, 2:]+ assert torch.equal(padding, torch.zeros_like(padding))@pytest.mark.device_agnostic@pytest.mark.parametrize("image_dtype", [torch.float16, torch.bfloat16])