Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

fix(augmentation): broadcast single mask over a batched image in AugmentationSequential (#5618)

Muhammad Talhaae2cb4a440fd
diff --git a/changelog.d/5618.breaking.md b/changelog.d/5618.breaking.md
new file mode 100644
index 000000000..3696b70b4
--- /dev/null
+++ b/changelog.d/5618.breaking.md
@@ -0,0 +1 @@
+`AugmentationSequential` now repeats a single tensor mask, `(H, W)`, `(1, H, W)`, `(1, C, H, W)` or one `(C, H, W)` mask, to the batch of a `(B, C, H, W)` image before the first child, so each sample's own parameters apply to its copy and the mask comes back with batch `B`. Previously the result depended on the child: per-sample warps such as `RandomAffine`, `RandomPerspective` and `RandomElasticTransform` raised `grid_sampler(): expected grid and input to have same batch size`, `RandomTransplantation` refused the mask, and flips, crops, resizes and color children such as `ColorJiggle` returned it at batch 1, with flips and crops applying sample 0's parameters only, so it did not match images 1 to `B - 1`. For example, with a batch-2 image a `(1, 1, H, W)` mask through `RandomHorizontalFlip` used to come back as `(1, 1, H, W)` and now comes back as `(2, 1, H, W)`; under `keepdim=True` a `(1, H, W)` mask used to come back as `(1, H, W)` and an `(H, W)` mask as `(H, W)`, and both now come back as `(2, H, W)`. Mask lists, unbatched images, batch-1 images and masks with one entry per image are unchanged. An `(H, W)` mask is now checked against the image's height and width like a 3-D or 4-D mask, and a mismatch raises the same `ValueError`; it used to go through unchecked (a `(9, 8)` mask with `(8, 8)` images came back with height 9).
diff --git a/kornia/augmentation/container/augment.py b/kornia/augmentation/container/augment.py
index a989a34c6..720c4db9b 100644
--- a/kornia/augmentation/container/augment.py
+++ b/kornia/augmentation/container/augment.py
@@ -133,7 +133,10 @@ class AugmentationSequential(TransformMatrixMinIn, ImageSequential):
``(B, N, 4)`` for ``bbox_xyxy`` and ``bbox_xywh``, and ``(B, N, 2)`` in ``(x, y)`` for ``keypoints``;
``N = 0`` is accepted. 3D inputs are ``(D, H, W)`` or ``(B, C, D, H, W)``; rank 4 is rejected as
ambiguous. A ``(B, H, W)`` mask is returned as ``(B, 1, H, W)``, or as ``(B, H, W)`` under
- ``keepdim=True``. A wrong input rank raises ``RuntimeError`` here rather than the ``ValueError`` of a
+ ``keepdim=True``. A single tensor mask, ``(H, W)``, ``(1, H, W)``, ``(1, C, H, W)`` or one ``(C, H, W)``,
+ next to a ``(B, C, H, W)`` image is repeated to batch ``B`` before the first child, so each sample's own
+ parameters apply to its copy; a 3D mask whose leading size is ``B`` is read as ``(B, H, W)``. A list of
+ masks is not repeated. A wrong input rank raises ``RuntimeError`` here rather than the ``ValueError`` of a
bare augmentation (`#4424 <https://github.com/kornia/kornia/issues/4424>`_).
- boxes use the inclusive ``xyxy_plus`` convention of :class:`~kornia.geometry.boxes.Boxes`. Flips map
``x' = W - 1 - x`` and ``y' = H - 1 - y`` for every key, as :func:`~kornia.geometry.transform.hflip`
@@ -504,7 +507,7 @@ class AugmentationSequential(TransformMatrixMinIn, ImageSequential):
image_batch = image.shape[0] if image.ndim == 4 else 1
image_size = image.shape[-2:]
for mask, key in zip(args, data_keys):
- if key not in _MSK_OPTIONS or not isinstance(mask, torch.Tensor) or mask.ndim not in (3, 4):
+ if key not in _MSK_OPTIONS or not isinstance(mask, torch.Tensor) or mask.ndim not in (2, 3, 4):
continue
mask_batch = mask.shape[0] if mask.ndim == 4 else 1
if mask_batch not in (1, image_batch) or mask.shape[-2:] != image_size:
@@ -520,9 +523,13 @@ class AugmentationSequential(TransformMatrixMinIn, ImageSequential):
# conversion happens under ``torch.export``, where that attribute is deliberately left untouched. Masks
# after an image use the most recent image, as before; a call with no image falls back to the attribute.
working_dtype = self.input_dtype
+ image_batch: Optional[int] = None
for arg, dcate in zip(args, data_keys):
if DataKey.get(dcate) in _IMG_OPTIONS:
working_dtype = cast(torch.Tensor, arg).dtype
+ # Only a batched ``(B, C, H, W)`` image has a batch to broadcast a single mask over.
+ if isinstance(arg, torch.Tensor) and arg.ndim == 4:
+ image_batch = arg.shape[0]
break
inp: List[DataType] = []
for arg, dcate in zip(args, data_keys):
@@ -544,7 +551,7 @@ class AugmentationSequential(TransformMatrixMinIn, ImageSequential):
self.mask_dtype = arg[0].dtype
else:
self.mask_dtype = cast(torch.Tensor, arg).dtype
- inp.append(self._preproc_mask(arg, working_dtype))
+ inp.append(self._preproc_mask(arg, working_dtype, image_batch))
elif DataKey.get(dcate) in _KEYPOINTS_OPTIONS:
inp.append(self._preproc_keypoints(arg, dcate))
elif DataKey.get(dcate) in _BOXES_OPTIONS:
@@ -700,8 +707,11 @@ class AugmentationSequential(TransformMatrixMinIn, ImageSequential):
Arguments convert by data key, and only an image takes the image conversion. A mask given as a NumPy array,
a PIL image or an image file path keeps its dtype and label values, palette indices included. Every mask
- must match the image's height and width, with a batch size of 1 or the image's. Arguments converted from NumPy
- go to the container's device when it has parameters or buffers, as the image does.
+ must match the image's height and width, with a batch size of 1 or the image's. A single tensor mask
+ (``(H, W)``, batch 1, or one ``(C, H, W)`` mask) is repeated to the image's batch, so every sample's own
+ parameters apply to its copy and the output mask has the image's batch size; a 3D mask whose leading size
+ equals the image batch is read as ``(B, H, W)``. Arguments converted from NumPy go to the container's device
+ when it has parameters or buffers, as the image does.
Args:
inputs: Inputs to operate on.
@@ -833,13 +843,42 @@ class AugmentationSequential(TransformMatrixMinIn, ImageSequential):
return valid_data_keys, invalid_keys
- def _preproc_mask(self, arg: MaskDataType, dtype: Optional[torch.dtype]) -> MaskDataType:
+ def _preproc_mask(
+ self, arg: MaskDataType, dtype: Optional[torch.dtype], image_batch: Optional[int] = None
+ ) -> MaskDataType:
# ``dtype`` is the calling image's working dtype, resolved by ``_arguments_preproc``; ``float32`` when the
- # call has no image and no earlier call recorded one.
+ # call has no image and no earlier call recorded one. ``image_batch`` is the batch size of a ``(B, C, H, W)``
+ # image in the call, ``None`` when there is none.
working = dtype if dtype is not None else torch.float
if isinstance(arg, list):
+ # A list keeps its per-entry gate semantics (see the class docstring); it is not broadcast.
return [a.to(working) for a in arg]
- return arg.to(working)
+ return self._broadcast_single_mask(arg.to(working), image_batch)
+
+ @staticmethod
+ def _broadcast_single_mask(mask: torch.Tensor, image_batch: Optional[int]) -> torch.Tensor:
+ """Repeat a single mask along the batch so that each image sample transforms its own copy.
+
+ A mask that stands for "this mask for every image" is accepted by ``_validate_args_datakeys`` next to an
+ image of batch ``B > 1``. Unrepeated, a child would transform it with the parameters of sample 0 only
+ (flip, crop) or fail inside a per-sample warp (affine, perspective, ...), so it would not line up with
+ images ``1..B-1``.
+
+ The single-mask layouts are ``(H, W)``, ``(1, C, H, W)``, ``(1, H, W)`` and ``(C, H, W)``; an ``(H, W)``
+ mask is read as ``(1, H, W)``, as a NumPy ``(H, W)`` mask is. A 3D mask is read like ``transform_tensor``
+ reads it: as ``(B, H, W)`` when its leading size is the image batch (so it is left alone), otherwise as
+ one ``(C, H, W)`` mask.
+ """
+ if image_batch is None or image_batch == 1 or mask.ndim not in (2, 3, 4):
+ return mask
+ if mask.ndim == 2:
+ mask = mask[None] # one (H, W) mask
+ if mask.ndim == 3 and mask.shape[0] not in (1, image_batch):
+ mask = mask[None] # one multi-channel (C, H, W) mask
+ elif mask.shape[0] != 1:
+ return mask # already one mask per image
+ # ``contiguous`` materialises the copy: a stride-0 view would break in-place edits made by a child.
+ return mask.expand(image_batch, *mask.shape[1:]).contiguous()
def _postproc_mask(self, arg: MaskDataType, like: MaskDataType) -> MaskDataType:
# Each mask output goes back to the dtype of its own argument, per element for a list. A single shared
diff --git a/tests/augmentation/container/test_augmentation_sequential.py b/tests/augmentation/container/test_augmentation_sequential.py
index b3277071e..4f99c3d0f 100644
--- a/tests/augmentation/container/test_augmentation_sequential.py
+++ b/tests/augmentation/container/test_augmentation_sequential.py
@@ -167,7 +167,13 @@ class TestAugmentationSequential:
@pytest.mark.parametrize(
("image_shape", "mask_shape", "batch"),
- [((2, 3, 8, 9), (3, 1, 8, 9), 2), ((3, 8, 9), (3, 1, 8, 9), 1), ((3, 8, 9), (1, 1, 8, 10), 1)],
+ [
+ ((2, 3, 8, 9), (3, 1, 8, 9), 2),
+ ((3, 8, 9), (3, 1, 8, 9), 1),
+ ((3, 8, 9), (1, 1, 8, 10), 1),
+ ((2, 3, 8, 9), (9, 9), 2),
+ ((3, 8, 9), (8, 10), 1),
+ ],
)
def test_mask_with_incompatible_shape_raises(self, image_shape, mask_shape, batch):
image, mask = torch.zeros(image_shape), torch.zeros(mask_shape)
@@ -186,13 +192,116 @@ class TestAugmentationSequential:
assert torch.equal(out_mask, torch.from_numpy(labels).permute(2, 0, 1)[None])
- def test_single_mask_with_a_batch_is_not_rejected(self):
+ def test_single_mask_with_a_batch_is_broadcast_not_rejected(self):
image, mask = torch.zeros(2, 3, 8, 9), torch.rand(1, 1, 8, 9)
aug = K.AugmentationSequential(K.RandomHorizontalFlip(p=1.0), data_keys=["input", "mask"])
_, out_mask = aug(image, mask)
- assert torch.equal(out_mask, mask.flip(-1))
+ assert torch.equal(out_mask, mask.flip(-1).expand(2, -1, -1, -1))
+
+ @pytest.mark.parametrize("mask_shape", [(1, 1, 8, 8), (1, 8, 8), (3, 8, 8)])
+ @pytest.mark.parametrize(
+ "make_child",
+ [
+ lambda: K.RandomHorizontalFlip(p=1.0),
+ lambda: K.RandomHorizontalFlip(p=0.5),
+ lambda: K.RandomCrop((4, 4), p=1.0),
+ lambda: K.RandomAffine(30.0, p=1.0, resample="nearest"),
+ ],
+ ids=["flip", "flip_half", "crop", "affine"],
+ )
+ def test_single_mask_follows_each_samples_own_transform(self, make_child, mask_shape):
+ # Every image is a copy of the mask, so each output mask must equal its own augmented image. A mask that was
+ # transformed with sample 0's draw only (flip, crop) or that made the warp fail (affine) breaks this.
+ mask = torch.rand(*mask_shape)
+ image = mask.reshape(1, mask.shape[-3], 8, 8).expand(4, -1, -1, -1).clone()
+ for seed in range(5):
+ torch.manual_seed(seed)
+ aug = K.AugmentationSequential(make_child(), data_keys=["input", "mask"])
+
+ out_image, out_mask = aug(image, mask)
+
+ assert out_mask.shape == out_image.shape
+ assert_close(out_mask, out_image)
+
+ @pytest.mark.parametrize("mask_shape", [(1, 1, 8, 8), (1, 8, 8)])
+ def test_single_mask_equals_an_explicit_full_batch_mask(self, mask_shape):
+ image = torch.rand(3, 3, 8, 8)
+ mask = (torch.rand(*mask_shape) > 0.5).float()
+ outputs = []
+ for candidate in (mask, mask.expand(3, *mask.shape[1:]).clone()):
+ torch.manual_seed(7)
+ aug = K.AugmentationSequential(
+ K.RandomAffine(30.0, p=1.0), K.RandomHorizontalFlip(p=0.5), data_keys=["input", "mask"]
+ )
+ outputs.append(aug(image, candidate)[1])
+
+ assert outputs[0].shape == (3, 1, 8, 8)
+ assert_close(outputs[0], outputs[1])
+
+ @pytest.mark.parametrize("mask_shape", [(2, 1, 8, 8), (2, 8, 8)])
+ def test_full_batch_mask_is_not_repeated(self, mask_shape):
+ # A leading size equal to the image batch is one mask per image, in both the 3D and the 4D layout.
+ mask = torch.rand(*mask_shape)
+ image = mask.reshape(2, 1, 8, 8).expand(-1, 3, -1, -1).clone()
+ torch.manual_seed(0)
+ aug = K.AugmentationSequential(K.RandomCrop((4, 4), p=1.0), data_keys=["input", "mask"])
+
+ out_image, out_mask = aug(image, mask)
+
+ assert out_mask.shape == (2, 1, 4, 4)
+ assert_close(out_mask, out_image[:, :1])
+
+ def test_single_mask_broadcast_keeps_the_callers_mask_and_inverts(self):
+ image, mask = torch.rand(2, 3, 8, 8), torch.rand(1, 1, 8, 8)
+ original = mask.clone()
+ aug = K.AugmentationSequential(K.RandomHorizontalFlip(p=1.0), data_keys=["input", "mask"])
+
+ out_image, out_mask = aug(image, mask)
+ _, inv_mask = aug.inverse(out_image, out_mask)
+
+ assert torch.equal(mask, original)
+ assert_close(inv_mask, original.expand(2, -1, -1, -1))
+
+ def test_single_mask_broadcast_through_a_dict_and_keepdim(self):
+ image, mask = torch.rand(2, 3, 8, 8), torch.rand(1, 8, 8)
+ aug = K.AugmentationSequential(K.RandomHorizontalFlip(p=1.0), data_keys=None, keepdim=True)
+
+ out = aug({"image": image, "mask": mask})
+
+ assert out["mask"].shape == (2, 8, 8)
+
+ def test_single_mask_with_an_unbatched_image_stays_single(self):
+ aug = K.AugmentationSequential(K.RandomHorizontalFlip(p=1.0), data_keys=["input", "mask"])
+
+ _, out_mask = aug(torch.rand(3, 8, 8), torch.rand(1, 1, 8, 8))
+
+ assert out_mask.shape == (1, 1, 8, 8)
+
+ @pytest.mark.parametrize("keepdim", [None, True])
+ def test_single_hw_mask_is_broadcast_5611(self, keepdim, device, dtype):
+ # An (H, W) tensor mask is one mask for every image, like the NumPy (H, W) mask it may come from.
+ mask = torch.rand(8, 8, device=device, dtype=dtype)
+ image = mask.expand(4, 3, 8, 8).clone()
+ aug = K.AugmentationSequential(
+ K.RandomAffine(30.0, p=1.0, resample="nearest"), data_keys=["input", "mask"], keepdim=keepdim
+ )
+
+ out_image, out_mask = aug(image, mask)
+
+ assert out_mask.shape == ((4, 8, 8) if keepdim else (4, 1, 8, 8))
+ assert_close(out_mask.reshape(4, 1, 8, 8), out_image[:, :1])
+
+ def test_multi_channel_mask_with_a_batch_one_image_is_not_repeated(self, device, dtype):
+ # With B == 1 there is nothing to repeat: a (C, H, W) mask keeps its shape under keepdim=True.
+ image = torch.rand(1, 3, 8, 8, device=device, dtype=dtype)
+ mask = torch.rand(2, 8, 8, device=device, dtype=dtype)
+ aug = K.AugmentationSequential(K.RandomHorizontalFlip(p=1.0), data_keys=["input", "mask"], keepdim=True)
+
+ _, out_mask = aug(image, mask)
+
+ assert_close(out_mask, mask.flip(-1))
def test_call_time_data_keys_are_restored_after_forward_exception(self, device, dtype):
image = torch.rand(1, 3, 16, 20, device=device, dtype=dtype)