Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

fix(augmentation): align mask lists with per-sample parameters (#5779)

peng xiang466c9d1a362e
diff --git a/changelog.d/5779.breaking.md b/changelog.d/5779.breaking.md
new file mode 100644
index 000000000..43de952f7
--- /dev/null
+++ b/changelog.d/5779.breaking.md
@@ -0,0 +1,3 @@
+`AugmentationSequential` mask lists now hold one tensor per image sample, each `(H, W)`, `(C, H, W)` or `(1, C, H, W)`, and every entry follows its own sample's gate, parameters and transformation matrix in forward, replay, nested sequences, auto-augment policies and inverse. Before, every entry received the whole batch's parameters with only sample `i`'s gate: per-sample entries failed in warps or were cropped with sample 0's window, full-batch entries were transformed whole but gated by one sample's draw, and a list longer than the batch raised `IndexError`.
+A list of full-batch tensors, a list whose length differs from the batch, or a non-tensor entry now raises `ValueError`, with or without an image; pass full-batch masks under separate `mask` data keys. Video, mix and 3D children and a geometric `PatchSequential` raise `NotImplementedError` for a mask list; before, mix children returned the list unchanged while the image was mixed. Mask-only replay and inverse retain every sample (before, they returned a single tensor or raised `IndexError`), and list calls preserve the child's full-batch parameters.
+A tensor mask next to a rank-2 `(H, W)` image is now checked as next to a `(C, H, W)` image: another height or width, a 4D batch above 1 or a 5D mask raises `ValueError`. Before, it was transformed as given, cropped with the image's window, or failed inside a child with `IndexError` or `RuntimeError`.
diff --git a/docs/source/get-started/conventions.rst b/docs/source/get-started/conventions.rst
index a9be1b7de..8927dc3c4 100644
--- a/docs/source/get-started/conventions.rst
+++ b/docs/source/get-started/conventions.rst
@@ -406,11 +406,14 @@ Augmentations
supported. On accelerators the asynchronous assertion may report at the next
synchronization; MPS before torch 2.13 checks on the host. A direct
geometric ``transform_masks`` call requires a floating tensor.
-- A list of masks is not a substitute for separate full-batch tensors: list
- index ``i`` selects sample ``i``'s gate, so full-batch entries desynchronize
- under mixed gates and per-sample entries can fail in warps or reuse the wrong
- crop window. Pass separate ``mask`` keys instead
- (`#4477 <https://github.com/kornia/kornia/issues/4477>`_).
+- A mask list has one tensor per image sample, in sample order. Entries may
+ have different channel counts and use their sample's gate, parameters and
+ matrix in forward, replay and inverse, including nested image sequences and
+ auto-augment policies. Video, mix and 3D children, and a geometric
+ ``PatchSequential``, do not support mask lists and raise ``NotImplementedError``.
+ Each entry is ``(H, W)``, ``(C, H, W)`` or ``(1, C, H, W)`` with the image's
+ spatial size. Invalid lengths or shapes raise ``ValueError``. Use separate
+ ``mask`` keys for multiple full-batch masks.
- Boxes use the inclusive ``xyxy_plus`` convention of
:class:`kornia.geometry.boxes.Boxes` (see *Bounding boxes* above). Flips use
integer pixel centres: ``x' = W - 1 - x``.
diff --git a/kornia/augmentation/base.py b/kornia/augmentation/base.py
index 64c50b56e..63faac748 100644
--- a/kornia/augmentation/base.py
+++ b/kornia/augmentation/base.py
@@ -480,7 +480,7 @@ class _AugmentationBase(_BasicAugmentationBase):
# A batched call has one gate per sample, so ``batch_prob`` gives the batch size as a Python int. The shape
# helpers read it from the ``forward_input_shape`` tensor, a data-dependent branch that breaks
- # ``torch.compile(fullgraph=True)`` for a ``(B, H, W)`` mask (#5598). A list entry (0-d gate) keeps them.
+ # ``torch.compile(fullgraph=True)`` for a ``(B, H, W)`` mask (#5598). Scalar gates keep the shape helpers.
channel_dim: Optional[int] = None
if input.dim() == 3 and batch_prob.dim() == 1:
channel_dim = 1 if input.shape[0] == batch_prob.shape[0] else 0
diff --git a/kornia/augmentation/container/augment.py b/kornia/augmentation/container/augment.py
index d81017c70..df789d882 100644
--- a/kornia/augmentation/container/augment.py
+++ b/kornia/augmentation/container/augment.py
@@ -153,15 +153,15 @@ class AugmentationSequential(TransformMatrixMinIn, ImageSequential):
masks use at least float32 (float64 with a float64 image). Integer labels not exactly representable
in that working dtype raise ``RuntimeError`` instead of being rounded. On accelerators an asynchronous
assertion may report at the next synchronization; MPS before torch 2.13 checks on the host.
- - a ``mask`` argument can be a list of tensors with different channel counts, but its batch handling
- has limitations. Each list entry uses only ``batch_prob[i]`` as its gate, including for intensity
- children. Per-sample list tensors are unsupported by warp operations, and full-batch tensors in that
- list can become desynchronized from the image when the gate differs across samples. A list longer
- than the batch raises ``IndexError``. Use separate ``mask`` data keys for separate full-batch masks.
- ``.inverse()`` takes the list the forward pass returned and inverts it element by element with the
- same per-entry gate. A flip round-trips each entry, subject to the working-dtype requirements above; other
- warps lose the pixels they move out of the frame and, when they resample, restore the rest only
- approximately. Tracked in `#4477 <https://github.com/kornia/kornia/issues/4477>`_.
+ - a ``mask`` list contains one tensor per image sample, in sample order. Each entry is
+ ``(H, W)``, ``(C, H, W)`` or ``(1, C, H, W)``, with matching spatial dimensions; channel counts
+ may differ. Each entry uses its sample's gate, transform parameters and matrix, including in
+ nested sequences, auto-augment policies, replay and inverse. Full-batch mask tensors must use
+ separate ``mask`` data keys; a list with incompatible length or entry shape raises ``ValueError``,
+ also in an inverse without an image. Video, mix and 3D children, and a geometric
+ :class:`~kornia.augmentation.PatchSequential`, do not support mask lists and raise
+ ``NotImplementedError``. Inverse warps can only approximately restore resampled pixels and
+ cannot recover pixels moved out of the frame.
- the ``mask``, box and ``keypoints`` handlers of a geometric child, or of a custom
:class:`~kornia.augmentation.RigidAffineAugmentationBase2D` subclass, receive the transform of the
call's ``params``: the one the child recorded when it last transformed an image with those params, or
@@ -463,17 +463,17 @@ class AugmentationSequential(TransformMatrixMinIn, ImageSequential):
self.transform_op.data_keys = self.transform_op.preproc_datakeys(data_keys)
try:
- self._validate_args_datakeys(*args, data_keys=self.transform_op.data_keys) # type: ignore
+ if params is None:
+ params = self._params
+ self._validate_args_datakeys(*args, data_keys=self.transform_op.data_keys, params=params) # type: ignore
in_args = self._arguments_preproc(*args, data_keys=self.transform_op.data_keys) # type: ignore
if params is None:
- if self._params is None:
- raise ValueError(
- "No parameters available for inversing, please run a forward pass first "
- "or passing valid params into this function."
- )
- params = self._params
+ raise ValueError(
+ "No parameters available for inversing, please run a forward pass first "
+ "or passing valid params into this function."
+ )
outputs: List[DataType] = in_args
for param in params[::-1]:
@@ -481,8 +481,8 @@ class AugmentationSequential(TransformMatrixMinIn, ImageSequential):
outputs = self.transform_op.inverse( # type: ignore
*outputs, module=module, param=param, extra_args=self.extra_args
)
- if not isinstance(outputs, (list, tuple)):
- # Make sure we are unpacking a list whilst post-proc
+ if len(self.transform_op.data_keys) == 1 or not isinstance(outputs, (list, tuple)):
+ # One data key can itself hold a mask list; keep it as one argument for the next child.
outputs = [outputs]
outputs = self._arguments_postproc(args, outputs, data_keys=self.transform_op.data_keys) # type: ignore
@@ -500,6 +500,22 @@ class AugmentationSequential(TransformMatrixMinIn, ImageSequential):
return outputs
+ @staticmethod
+ def _validate_mask_list(mask: List[torch.Tensor], batch: int, size: Optional[torch.Size]) -> None:
+ """Validate the per-sample mask-list layout before any child runs."""
+ if len(mask) != batch:
+ raise ValueError(f"Mask list must contain one entry per sample ({batch}); got {len(mask)}.")
+ for i, entry in enumerate(mask):
+ if not isinstance(entry, torch.Tensor):
+ raise ValueError(f"Mask list entry {i} must be a torch.Tensor; got {type(entry).__name__}.")
+ if entry.ndim not in (2, 3, 4) or (entry.ndim == 4 and entry.shape[0] != 1):
+ raise ValueError(
+ f"Mask list entry {i} must be (H, W), (C, H, W) or (1, C, H, W); "
+ f"got {tuple(entry.shape)}. Use separate mask data keys for full-batch tensors."
+ )
+ if size is not None and entry.shape[-2:] != size:
+ raise ValueError(f"Mask list entry {i} must have spatial size {tuple(size)}; got {tuple(entry.shape)}.")
+
def _validate_args_datakeys(
self, *args: DataType, data_keys: List[DataKey], params: Optional[List[ParamItem]] = None
) -> None:
@@ -517,7 +533,7 @@ class AugmentationSequential(TransformMatrixMinIn, ImageSequential):
# Set once at construction from this container's children; distinguishes a video from a 5D
# ``(B, C, D, H, W)`` 3D image, which this function leaves untouched, as before.
is_video = self.contains_video_sequential
- if isinstance(image, torch.Tensor) and (image.ndim in (3, 4) or (image.ndim == 5 and is_video)):
+ if isinstance(image, torch.Tensor) and (image.ndim in (2, 3, 4) or (image.ndim == 5 and is_video)):
image_batch: Optional[int] = image.shape[0] if image.ndim in (4, 5) else 1
image_size = image.shape[-2:]
elif image is None and params is not None and not self.contains_3d_augmentation:
@@ -534,6 +550,9 @@ class AugmentationSequential(TransformMatrixMinIn, ImageSequential):
for mask, key in zip(args, data_keys):
if key not in _MSK_OPTIONS:
continue
+ if isinstance(mask, list):
+ self._validate_mask_list(mask, image_batch, image_size)
+ continue
if not isinstance(mask, torch.Tensor):
continue
# A mask next to a video is 5D, or (B, T, H, W) next to a BTCHW video, which VideoSequential reads with
@@ -730,8 +749,8 @@ class AugmentationSequential(TransformMatrixMinIn, ImageSequential):
for param in params:
module = self.get_submodule(param.name)
outputs = self.transform_op.transform(*outputs, module=module, param=param, extra_args=self.extra_args)
- if not isinstance(outputs, (list, tuple)):
- # Make sure we are unpacking a list whilst post-proc
+ if len(self.transform_op.data_keys) == 1 or not isinstance(outputs, (list, tuple)):
+ # One data key can itself hold a mask list; keep it as one argument for the next child.
outputs = [outputs]
self._update_transform_matrix_by_module(module)
@@ -978,7 +997,7 @@ class AugmentationSequential(TransformMatrixMinIn, ImageSequential):
# 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.
+ # A list holds one mask per sample (see the class docstring); it is not broadcast.
return [self._cast_mask(a, working) for a in arg]
return self._broadcast_single_mask(self._cast_mask(arg, working), image_batch)
diff --git a/kornia/augmentation/container/ops.py b/kornia/augmentation/container/ops.py
index dd23f5502..287442cd9 100644
--- a/kornia/augmentation/container/ops.py
+++ b/kornia/augmentation/container/ops.py
@@ -15,7 +15,6 @@
# limitations under the License.
#
-import copy
from abc import ABCMeta, abstractmethod
from typing import Any, Callable, Dict, Generic, List, Optional, ParamSpec, Type, TypeVar, Union
@@ -226,6 +225,10 @@ class AugmentationSequentialOps:
_data_keys = self.preproc_datakeys(data_keys)
if isinstance(module, K.RandomTransplantation):
+ # This child reads the mask while drawing params, before the list-mask handler can reject it.
+ for inp, dcate in zip(arg, _data_keys):
+ if dcate == DataKey.MASK and isinstance(inp, list):
+ raise NotImplementedError(f"{type(module).__name__} does not support mask lists.")
# For transforms which require the full input to calculate the parameters (e.g. RandomTransplantation)
param = ParamItem(
name=param.name,
@@ -514,68 +517,72 @@ class MaskSequentialOps(SequentialOpsInterface[torch.Tensor]):
return input
+ @staticmethod
+ def _sample_params(params: Dict[str, torch.Tensor], index: int) -> Dict[str, torch.Tensor]:
+ """Select one sample's gate and tensor parameters without mutating the saved draw."""
+ batch = params["batch_prob"].numel()
+ selected = {}
+ for name, value in params.items():
+ if name == "forward_input_shape":
+ value = value.clone()
+ value[0] = 1
+ elif value.ndim > 0 and value.shape[0] == batch:
+ value = value[index : index + 1]
+ selected[name] = value
+ return selected
+
@classmethod
def transform_list(
cls, input: List[torch.Tensor], module: nn.Module, param: ParamItem, extra_args: Optional[Dict[str, Any]] = None
) -> List[torch.Tensor]:
- """Apply a transformation with respect to the parameters.
+ """Transform one mask per image sample, allowing different channel counts.
Args:
- input: list of input tensors.
- module: any torch nn.Module but only kornia augmentation modules will count
- to apply transformations.
- param: the corresponding parameters to the module.
- extra_args: Optional dictionary of extra arguments with specific options for different input types.
+ input: Per-sample mask tensors in image order.
+ module: Augmentation or nested image sequence to apply.
+ param: The full image batch's saved parameters.
+ extra_args: Mask interpolation and other runtime overrides.
+
+ Returns:
+ One transformed mask per sample, in the same order.
"""
if extra_args is None:
extra_args = {}
- if isinstance(module, K.RigidAffineAugmentationBase2D) and not isinstance(
- module, K.IntensityAugmentationBase2D
- ):
- extra_args = cls._mask_extra_args(module, extra_args)
- tfm_input = []
+ if isinstance(module, K.GeometricAugmentationBase3D):
+ raise NotImplementedError("3D mask lists are not supported.")
+ if isinstance(module, (K.VideoSequential, K.MixAugmentationBaseV2)):
+ raise NotImplementedError(f"{type(module).__name__} does not support mask lists.")
+ if isinstance(module, K.PatchSequential):
+ # Its own handler: masks pass through an intensity-only pipeline, a geometric one raises.
+ seq_params = cls.get_sequential_module_param(param)
+ return [module.transform_masks(inp, params=seq_params, extra_args=extra_args) for inp in input]
+ if isinstance(module, K.container.ImageSequentialBase):
+ for child_param in cls.get_sequential_module_param(param):
+ input = cls.transform_list(input, module.get_submodule(child_param.name), child_param, extra_args)
+ return input
+ if isinstance(module, K.auto.operations.OperationBase):
+ return cls.transform_list(input, module.op, param, extra_args)
+ if isinstance(module, _AugmentationBase):
params = cls.get_instance_module_param(param)
- params_i = copy.deepcopy(params)
- for i, inp in enumerate(input):
- params_i["batch_prob"] = params["batch_prob"][i]
- tfm_inp = module.transform_masks(
+ transform = None
+ if isinstance(module, K.RigidAffineAugmentationBase2D) and not isinstance(
+ module, K.IntensityAugmentationBase2D
+ ):
+ extra_args = cls._mask_extra_args(module, extra_args)
+ transform = cls.get_transform_matrix(module, param, input)
+ output = [
+ module.transform_masks(
inp,
- params=params_i,
+ params=cls._sample_params(params, i),
flags=module.flags,
- transform=cls.get_transform_matrix(module, param, inp),
+ transform=transform[i : i + 1] if transform is not None else None,
**extra_args,
)
- tfm_input.append(tfm_inp)
- input = tfm_input
-
- elif isinstance(module, (K.GeometricAugmentationBase3D,)):
- raise NotImplementedError(
- "The support for 3d mask operations are not yet supported. You are welcome to file a PR in our repo."
- )
-
- elif isinstance(module, (_AugmentationBase)):
- tfm_input = []
- params = cls.get_instance_module_param(param)
- params_i = copy.deepcopy(params)
- for i, inp in enumerate(input):
- params_i["batch_prob"] = params["batch_prob"][i]
- tfm_inp = module.transform_masks(inp, params=params_i, flags=module.flags, **extra_args)
- tfm_input.append(tfm_inp)
- input = tfm_input
-
- elif isinstance(module, K.container.ImageSequentialBase):
- tfm_input = []
- seq_params = cls.get_sequential_module_param(param)
- for inp in input:
- tfm_inp = module.transform_masks(inp, params=seq_params, extra_args=extra_args)
- tfm_input.append(tfm_inp)
- input = tfm_input
-
- elif isinstance(module, (K.auto.operations.OperationBase,)):
- raise NotImplementedError(
- "The support for list of masks under auto operations are not yet supported. You are welcome to file a"
- " PR in our repo."
- )
+ for i, inp in enumerate(input)
+ ]
+ # Each call recorded one sample's slice; keep the batch draw as the child's params, as a tensor mask does.
+ module._commit_state(params=params)
+ return output
return input
@classmethod
@@ -621,46 +628,47 @@ class MaskSequentialOps(SequentialOpsInterface[torch.Tensor]):
def inverse_list(
cls, input: List[torch.Tensor], module: nn.Module, param: ParamItem, extra_args: Optional[Dict[str, Any]] = None
) -> List[torch.Tensor]:
- """Inverse a transformation on a list of masks, undoing :meth:`transform_list` element by element.
+ """Invert each sample's mask with its own forward parameters and matrix.
Args:
- input: list of input tensors.
- module: any torch nn.Module but only kornia augmentation modules will count
- to apply transformations.
- param: the corresponding parameters to the module.
- extra_args: Optional dictionary of extra arguments with specific options for different input types.
+ input: Per-sample masks returned by the forward pass.
+ module: Augmentation or nested image sequence to invert.
+ param: The full image batch's saved forward parameters.
+ extra_args: Mask interpolation and other runtime overrides.
+
+ Returns:
+ One inverse-transformed mask per sample, in the same order.
"""
if extra_args is None:
extra_args = {}
-
- if isinstance(module, (K.GeometricAugmentationBase2D,)):
+ if isinstance(module, K.GeometricAugmentationBase2D):
transform = module.compute_inverse_transformation(cls.get_transform_matrix(module, param, input))
params = cls.get_instance_module_param(param)
- params_i = copy.deepcopy(params)
- inv_input = []
- for i, inp in enumerate(input):
- # The same per-element ``batch_prob`` that ``transform_list`` gave this element.
- params_i["batch_prob"] = params["batch_prob"][i]
- inv_input.append(
- module.inverse_masks(inp, params=params_i, flags=module.flags, transform=transform, **extra_args)
+ output = [
+ module.inverse_masks(
+ inp,
+ params=cls._sample_params(params, i),
+ flags=module.flags,
+ transform=transform[i : i + 1],
+ **extra_args,
)
- input = inv_input
-
- elif isinstance(module, (K.GeometricAugmentationBase3D,)):
- raise NotImplementedError(
- "The support for 3d mask operations are not yet supported. You are welcome to file a PR in our repo."
- )
-
- elif isinstance(module, K.container.ImageSequentialBase):
+ for i, inp in enumerate(input)
+ ]
+ module._commit_state(params=params)
+ return output
+ if isinstance(module, K.GeometricAugmentationBase3D):
+ raise NotImplementedError("3D mask lists are not supported.")
+ if isinstance(module, (K.VideoSequential, K.MixAugmentationBaseV2)):
+ raise NotImplementedError(f"{type(module).__name__} does not support mask lists.")
+ if isinstance(module, K.PatchSequential):
seq_params = cls.get_sequential_module_param(param)
- input = [module.inverse_masks(inp, params=seq_params, extra_args=extra_args) for inp in input]
-
- elif isinstance(module, (K.auto.operations.OperationBase,)):
- raise NotImplementedError(
- "The support for list of masks under auto operations are not yet supported. You are welcome to file a"
- " PR in our repo."
- )
-
+ return [module.inverse_masks(inp, params=seq_params, extra_args=extra_args) for inp in input]
+ if isinstance(module, K.container.ImageSequentialBase):
+ for child_param in reversed(cls.get_sequential_module_param(param)):
+ input = cls.inverse_list(input, module.get_submodule(child_param.name), child_param, extra_args)
+ return input
+ if isinstance(module, K.auto.operations.OperationBase):
+ return cls.inverse_list(input, module.op, param, extra_args)
return input
diff --git a/tests/augmentation/container/test_augmentation_sequential.py b/tests/augmentation/container/test_augmentation_sequential.py
index 5cb8661c2..704b4b564 100644
--- a/tests/augmentation/container/test_augmentation_sequential.py
+++ b/tests/augmentation/container/test_augmentation_sequential.py
@@ -181,6 +181,8 @@ class TestAugmentationSequential:
((3, 8, 9), (1, 1, 8, 10), 1),
((2, 3, 8, 9), (9, 9), 2),
((3, 8, 9), (8, 10), 1),
+ ((8, 9), (1, 1, 8, 10), 1),
+ ((8, 9), (2, 1, 8, 9), 1),
],
)
def test_mask_with_incompatible_shape_raises(self, image_shape, mask_shape, batch):
@@ -1430,10 +1432,9 @@ class TestConventionAugmentationSequential(BaseTester):
out = aug(img, torch.rand(1, 3, 4, device=device, dtype=dtype))
assert out[1].shape == (1, 1, 3, 4)
- def test_wart_mask_lists_desynchronize_mixed_probability_batches_4477(self, device, dtype):
- # A list entry selects one sample's gate, even when that entry contains the whole batch.
+ def test_per_sample_mask_lists_follow_mixed_gates_4477(self, device, dtype):
image = torch.arange(24, device=device, dtype=dtype).reshape(2, 1, 3, 4)
- masks = [image.clone(), image.expand(-1, 2, -1, -1).clone()]
+ masks = [image[:1].clone(), image[1:].expand(-1, 2, -1, -1).clone()]
seq = K.AugmentationSequential(K.RandomHorizontalFlip(p=0.5), data_keys=["input", "mask"])
params = [
ParamItem(
@@ -1442,32 +1443,21 @@ class TestConventionAugmentationSequential(BaseTester):
)
]
out_image, out_masks = seq(image, masks, params=params)
- self.assert_close(out_image, torch.stack((image[0].flip(-1), image[1])))
- self.assert_close(out_masks[0], masks[0].flip(-1))
- self.assert_close(out_masks[1], masks[1])
- assert not torch.equal(out_masks[0][1], out_image[1])
- assert not torch.equal(out_masks[1][0, :1], out_image[0])
-
- # Separate tensor mask keys preserve the per-sample gates for both channel counts.
- aligned = K.AugmentationSequential(K.RandomHorizontalFlip(p=0.5), data_keys=["input", "mask", "mask"])
- out_image, first, second = aligned(image, *masks, params=params)
- self.assert_close(first, out_image)
- self.assert_close(second, out_image.expand(-1, 2, -1, -1))
-
- # Keep a deliberate invalid-index probe on CPU to avoid accelerator context poisoning.
- cpu_image = image.cpu()
- with pytest.raises(IndexError):
- seq(cpu_image, [cpu_image.clone() for _ in range(3)], params=params)
-
- def test_wart_per_sample_mask_lists_fail_warps_and_reuse_crop_window_4477(self, device, dtype):
+ self.assert_close(out_masks[0], out_image[:1])
+ self.assert_close(out_masks[1], out_image[1:].expand(-1, 2, -1, -1))
+ _, restored = seq.inverse(out_image, out_masks, params=params)
+ for actual, expected in zip(restored, masks):
+ self.assert_close(actual, expected)
+
+ @pytest.mark.parametrize("cropping_mode", ["slice", "resample"])
+ def test_per_sample_mask_lists_use_own_crop_window_4477(self, cropping_mode, device, dtype):
+ if cropping_mode == "resample" and not supports_bilinear_2d_grid_sample(device, dtype):
+ pytest.skip("The image crop path requires grid_sample for the selected dtype.")
image = torch.arange(16, device=device, dtype=dtype).reshape(1, 1, 4, 4).repeat(2, 1, 1, 1)
- masks = [image[:1].clone(), image[1:].clone()]
- warp = K.AugmentationSequential(K.RandomAffine((30.0, 30.0), p=1.0), data_keys=["input", "mask"])
- with pytest.raises(RuntimeError):
- warp(image, masks)
- # Control: full-batch list entries warp, so the failure above is the per-sample entries.
- assert [mask.shape for mask in warp(image, [image.clone(), image.clone()])[1]] == [(2, 1, 4, 4)] * 2
- crop = K.AugmentationSequential(K.RandomCrop((2, 2), p=1.0), data_keys=["input", "mask"])
+ masks = [image[:1].clone(), image[1:].expand(-1, 2, -1, -1).clone()]
+ crop = K.AugmentationSequential(
+ K.RandomCrop((2, 2), p=1.0, cropping_mode=cropping_mode, resample="nearest"), data_keys=["input", "mask"]
+ )
params = crop.forward_parameters(image.shape)
params[0].data["src"] = torch.tensor(
[[[0.0, 0.0], [1.0, 0.0], [1.0, 1.0], [0.0, 1.0]], [[2.0, 2.0], [3.0, 2.0], [3.0, 3.0], [2.0, 3.0]]],
@@ -1478,8 +1468,331 @@ class TestConventionAugmentationSequential(BaseTester):
self.assert_close(output[0], image[0, :, :2, :2])
self.assert_close(output[1], image[1, :, 2:, 2:])
self.assert_close(out_masks[0], output[:1])
- self.assert_close(out_masks[1], output[:1])
- assert not torch.equal(out_masks[1], output[1:])
+ self.assert_close(out_masks[1], output[1:].expand(-1, 2, -1, -1))
+
+ @pytest.mark.parametrize("nested", [False, True])
+ def test_per_sample_mask_lists_warp_replay_and_inverse_4477(self, nested, device, dtype):
+ if not supports_bilinear_2d_grid_sample(device, dtype):
+ pytest.skip("The image warp path requires grid_sample for the selected dtype.")
+ image = torch.arange(3 * 8 * 8, device=device, dtype=dtype).reshape(3, 1, 8, 8)
+ masks = [image[i : i + 1].expand(-1, i + 1, -1, -1).clone() for i in range(3)]
+ rotation = K.RandomRotation((-90.0, 90.0), p=0.5, resample="nearest")
+ child = K.ImageSequential(rotation) if nested else rotation
+ seq = K.AugmentationSequential(child, data_keys=["input", "mask"])
+ params = seq.forward_parameters(image.shape)
+ draw = params[0].data[0].data if nested else params[0].data
+ draw["degrees"] = torch.tensor([-90.0, 90.0, 90.0], device=device, dtype=dtype)
+ draw["batch_prob"] = torch.tensor([1.0, 0.0, 1.0], device=device, dtype=dtype)
+ output, out_masks = seq(image, masks, params=params)
+ for i, mask in enumerate(out_masks):
+ self.assert_close(mask, output[i : i + 1].expand(-1, i + 1, -1, -1))
+ # A later image draw must not change replay or inverse of these saved params.
+ seq(image, data_keys=["input"])
+ replay_image, replay_masks = seq(image, masks, params=params)
+ self.assert_close(replay_image, output)
+ for actual, expected in zip(replay_masks, out_masks):
+ self.assert_close(actual, expected)
+ _, restored = seq.inverse(output, out_masks, params=params)
+ for actual, expected in zip(restored, masks):
+ self.assert_close(actual, expected)
+
+ @pytest.mark.parametrize("rank", [2, 3, 4])
+ @pytest.mark.parametrize("keepdim", [False, True])
+ def test_per_sample_mask_list_ranks_4477(self, rank, keepdim, device, dtype):
+ image = torch.arange(24, device=device, dtype=dtype).reshape(2, 1, 3, 4)
+ entries = [image[i : i + 1].clone() for i in range(2)]
+ if rank < 4:
+ entries = [m.squeeze(0) for m in entries]
+ if rank == 2:
+ entries = [m.squeeze(0) for m in entries]
+ seq = K.AugmentationSequential(K.RandomHorizontalFlip(p=1.0), data_keys=["input", "mask"], keepdim=keepdim)
+ output, masks = seq(image, entries)
+ for i, mask in enumerate(masks):
+ assert mask.ndim == (rank if keepdim else 4)
+ self.assert_close(mask.reshape(1, 1, 3, 4), output[i : i + 1])
+
+ @pytest.mark.parametrize("padding", [0, 1])
+ def test_mask_list_crop_inverse_matches_tensor_masks_4477(self, padding, device, dtype):
+ if not supports_bilinear_2d_grid_sample(device, dtype):
+ pytest.skip("The image crop path requires grid_sample for the selected dtype.")
+ image = torch.arange(2 * 6 * 8, device=device, dtype=dtype).reshape(2, 1, 6, 8)
+ entries = [image[:1].clone(), image[1:].expand(-1, 2, -1, -1).clone()]
+ seq = K.AugmentationSequential(
+ K.RandomCrop((4, 4), padding=padding, p=1.0, cropping_mode="resample", resample="nearest"),
+ data_keys=["input", "mask"],
+ )
+ output, masks = seq(image, entries)
+ params = seq._params
+ _, tensor_mask = seq(image, image.clone(), params=params)
+ for i, mask in enumerate(masks):
+ self.assert_close(mask, tensor_mask[i : i + 1].expand(-1, i + 1, -1, -1))
+ _, inverse_list = seq.inverse(output, masks, params=params)
+ _, inverse_tensor = seq.inverse(output, tensor_mask, params=params)
+ for i, mask in enumerate(inverse_list):
+ self.assert_close(mask, inverse_tensor[i : i + 1].expand(-1, i + 1, -1, -1))
+
+ def test_empty_mask_list_4477(self, device, dtype):
+ image = torch.rand(0, 1, 4, 6, device=device, dtype=dtype)
+ seq = K.AugmentationSequential(K.RandomHorizontalFlip(p=1.0), data_keys=["input", "mask"])
+ output, masks = seq(image, [])
+ assert output.shape == image.shape
+ assert masks == []
+ restored, masks = seq.inverse(output, masks)
+ assert restored.shape == image.shape
+ assert masks == []
+
+ @pytest.mark.parametrize("layout", ["short", "long", "full_batch", "spatial", "rank1", "rank5"])
+ def test_invalid_mask_list_layout_4477(self, layout, device, dtype):
+ image = torch.rand(2, 1, 4, 6, device=device, dtype=dtype)
+ entries = [image[:1].clone(), image[1:].clone()]
+ if layout == "short":
+ entries = entries[:1]
+ elif layout == "long":
+ entries.append(image[:1].clone())
+ elif layout == "full_batch":
+ entries = [image.clone(), image.clone()]
+ elif layout == "rank1":
+ entries[1] = entries[1].flatten()
+ elif layout == "rank5":
+ entries[1] = entries[1][None]
+ else:
+ entries[1] = entries[1][..., :2, :]
+ seq = K.AugmentationSequential(K.RandomHorizontalFlip(p=1.0), data_keys=["input", "mask"])
+ with pytest.raises(ValueError, match="Mask list"):
+ seq(image, entries)
+
+ @pytest.mark.parametrize("entry", [None, 1, "mask", [1]])
+ def test_invalid_mask_list_entry_type_4477(self, entry, device, dtype):
+ image = torch.rand(2, 1, 4, 6, device=device, dtype=dtype)
+ seq = K.AugmentationSequential(K.RandomHorizontalFlip(p=1.0), data_keys=["input", "mask"])
+ with pytest.raises(ValueError, match=r"Mask list entry 1 must be a torch\.Tensor"):
+ seq(image, [image[:1].clone(), entry])
+
+ @pytest.mark.parametrize("use_cached_params", [False, True])
+ @pytest.mark.parametrize("nested", [False, True])
+ @pytest.mark.parametrize("layout", ["short", "long", "full_batch", "non_tensor"])
+ def test_invalid_mask_list_image_less_inverse_4477(self, layout, nested, use_cached_params, device, dtype):
+ image = torch.arange(48, device=device, dtype=dtype).reshape(2, 1, 4, 6)
+ flip = K.RandomHorizontalFlip(p=1.0)
+ seq = K.AugmentationSequential(K.ImageSequential(flip) if nested else flip, data_keys=["input", "mask"])
+ _, masks = seq(image, [image[:1].clone(), image[1:].clone()])
+ params = seq._params
+ if layout == "short":
+ masks = masks[:1]
+ elif layout == "long":
+ masks.append(masks[0].clone())
+ elif layout == "full_batch":
+ masks = [image.clone(), image.clone()]
+ else:
+ masks[1] = None
+ with pytest.raises(ValueError, match="Mask list"):
+ seq.inverse(masks, params=None if use_cached_params else params, data_keys=["mask"])
+ assert seq.transform_op.data_keys == seq.data_keys
+
+ @pytest.mark.parametrize("use_cached_params", [False, True])
+ @pytest.mark.parametrize("nested", [False, True])
+ @pytest.mark.parametrize("batch_size", [0, 2])
+ def test_mask_list_image_less_inverse_4477(self, batch_size, nested, use_cached_params, device, dtype):
+ image = torch.arange(batch_size * 24, device=device, dtype=dtype).reshape(batch_size, 1, 4, 6)
+ entries = [image[i : i + 1].expand(-1, i + 1, -1, -1).clone() for i in range(batch_size)]
+ flip = K.RandomHorizontalFlip(p=1.0)
+ seq = K.AugmentationSequential(
+ K.ImageSequential(flip) if nested else flip, K.RandomVerticalFlip(p=1.0), data_keys=["input", "mask"]
+ )
+ _, masks = seq(image, entries)
+ params = seq._params
+ if not use_cached_params:
+ # Explicit parameters must win over the metadata of a later call with another batch size.
+ seq(torch.zeros(3, 1, 4, 6, device=device, dtype=dtype), data_keys=["input"])
+ restored = seq.inverse(masks, params=None if use_cached_params else params, data_keys=["mask"])
+ assert len(restored) == batch_size
+ for actual, expected in zip(restored, entries):
+ self.assert_close(actual, expected, rtol=0, atol=0)
+
+ @pytest.mark.parametrize("layout", ["short", "long", "full_batch", "non_tensor", "spatial", "rank1", "rank5"])
+ def test_mask_list_beside_rank2_image_validates_before_children_4477(self, layout, device, dtype):
+ image = torch.zeros(4, 6, device=device, dtype=dtype)
+ masks = [image.clone()]
+ if layout == "short":
+ masks = []
+ elif layout == "long":
+ masks.append(image.clone())
+ elif layout == "full_batch":
+ masks = [image.expand(2, 1, 4, 6).clone()]
+ elif layout == "non_tensor":
+ masks = [None]
+ elif layout == "spatial":
+ masks = [image[:2].clone()]
+ elif layout == "rank1":
+ masks = [image.flatten()]
+ else:
+ masks = [image.reshape(1, 1, 1, 4, 6)]
+ child = K.RandomHorizontalFlip(p=1.0)
+ seq = K.AugmentationSequential(child, data_keys=["input", "mask"])
+ with (
+ patch.object(child, "forward", side_effect=AssertionError("Child must not run before validation")),
+ pytest.raises(ValueError, match="Mask list"),
+ ):
+ seq(image, masks)
+
+ def test_mask_list_beside_rank2_image_matches_tensor_mask_4477(self, device, dtype):
+ image = torch.arange(24, device=device, dtype=dtype).reshape(4, 6)
+ seq = K.AugmentationSequential(K.RandomHorizontalFlip(p=1.0), data_keys=["input", "mask"])
+ output, tensor_mask = seq(image, image.clone())
+ list_output, masks = seq(image, [image.clone()], params=seq._params)
+ self.assert_close(list_output, output)
+ assert len(masks) == 1
+ self.assert_close(masks[0], tensor_mask)
+
+ def test_mask_list_nested_inverse_runs_children_in_reverse_4477(self, device, dtype):
+ # A quarter turn and a flip do not commute, so the inverse order is visible.
+ image = torch.arange(2 * 36, device=device, dtype=dtype).reshape(2, 1, 6, 6)
+ entries = [image[:1].clone(), image[1:].expand(-1, 2, -1, -1).clone()]
+ seq = K.AugmentationSequential(
+ K.ImageSequential(K.RandomRotation90((1, 1), p=1.0), K.RandomHorizontalFlip(p=1.0)),
+ data_keys=["input", "mask"],
+ )
+ output, masks = seq(image, entries)
+ _, restored = seq.inverse(output, masks)
+ for actual, expected in zip(restored, entries):
+ self.assert_close(actual, expected)
+
+ def test_mask_list_uses_mask_fill_for_per_channel_image_fill_4477(self, device, dtype):
+ image = torch.arange(2 * 3 * 4 * 6, device=device, dtype=dtype).reshape(2, 3, 4, 6)
+ mask = torch.arange(2 * 4 * 6, device=device, dtype=dtype).reshape(2, 1, 4, 6) + 1
+ seq = K.AugmentationSequential(
+ K.RandomCrop((4, 6), padding=2, fill=(7.0, 8.0, 9.0), p=1.0), data_keys=["input", "mask"]
+ )
+ _, tensor_mask = seq(image, mask)
+ _, masks = seq(image, [mask[:1].clone(), mask[1:].clone()], params=seq._params)
+ for i, entry in enumerate(masks):
+ self.assert_close(entry, tensor_mask[i : i + 1])
+
+ def test_mask_list_replay_keeps_the_saved_draw_4477(self, device, dtype):
+ if not supports_bilinear_2d_grid_sample(device, dtype):
+ pytest.skip("The image warp path requires grid_sample for the selected dtype.")
+ image = torch.arange(2 * 64, device=device, dtype=dtype).reshape(2, 1, 8, 8)
+ entries = [image[:1].clone(), image[1:].clone()]
+ seq = K.AugmentationSequential(K.RandomRotation((90.0, 90.0), p=1.0), data_keys=["input", "mask"])
+ output, masks = seq(image, entries)
+ params = seq._params
+ assert params[0].data["forward_input_shape"].tolist() == list(image.shape)
+ assert seq[0]._params["batch_prob"].shape == (2,)
+ _, expected = seq.inverse(output, masks, params=params)
+ assert seq[0]._params["batch_prob"].shape == (2,)
+ seq(image, data_keys=["input"]) # a newer draw: the inverse below recomputes the saved matrix
+ keypoints = torch.zeros(2, 1, 2, device=device, dtype=dtype)
+ restored, _ = seq.inverse(masks, keypoints, params=params, data_keys=["mask", "keypoints"])
+ for actual, wanted in zip(restored, expected):
+ self.assert_close(actual, wanted)
+
+ @pytest.mark.parametrize("children", [1, 2])
+ def test_mask_list_as_the_only_data_key_4477(self, children, device, dtype):
+ image = torch.arange(2 * 24, device=device, dtype=dtype).reshape(2, 1, 4, 6)
+ entries = [image[:1].clone(), image[1:].expand(-1, 2, -1, -1).clone()]
+ modules = [K.RandomHorizontalFlip(p=1.0), K.RandomVerticalFlip(p=1.0)][:children]
+ seq = K.AugmentationSequential(*modules, data_keys=["input", "mask"])
+ _, masks = seq(image, entries)
+ replayed = seq(entries, data_keys=["mask"], params=seq._params)
+ assert isinstance(replayed, list)
+ assert len(replayed) == 2
+ for actual, expected in zip(replayed, masks):
+ self.assert_close(actual, expected)
+ restored = seq.inverse(masks, data_keys=["mask"])
+ assert isinstance(restored, list)
+ assert len(restored) == 2
+ for actual, expected in zip(restored, entries):
+ self.assert_close(actual, expected)
+
+ def test_mask_list_inverse_without_image_validates_layout_4477(self, device, dtype):
+ image = torch.rand(2, 1, 4, 6, device=device, dtype=dtype)
+ seq = K.AugmentationSequential(K.RandomHorizontalFlip(p=1.0), data_keys=["input", "mask"])
+ _, masks = seq(image, [image[:1].clone(), image[1:].clone()])
+ keypoints = torch.zeros(2, 1, 2, device=device, dtype=dtype)
+ with pytest.raises(ValueError, match="Mask list"):
+ seq.inverse([*masks, masks[0]], keypoints, data_keys=["mask", "keypoints"])
+
+ @pytest.mark.parametrize("policy_name", ["trivial", "rand", "auto"])
+ def test_mask_list_under_auto_operations_matches_tensor_masks_4477(self, policy_name, device, dtype):
+ if not supports_bilinear_2d_grid_sample(device, dtype):
+ pytest.skip("The image warp path requires grid_sample for the selected dtype.")
+ torch.manual_seed(0)
+ image = torch.rand(2, 3, 8, 8).to(device, dtype) # CPU draw: the policy angle below is device-independent
+ mask = torch.arange(2 * 64, device=device, dtype=dtype).reshape(2, 1, 8, 8)
+ if policy_name == "trivial":
+ policy = K.auto.TrivialAugment(policy=[[("rotate", -30.0, 30.0)]])
+ elif policy_name == "rand":
+ policy = K.auto.RandAugment(1, 15, policy=[[("rotate", -30.0, 30.0)]])
+ else:
+ policy = K.auto.AutoAugment(policy=[[("rotate", 1.0, 9)]])
+ seq = K.AugmentationSequential(policy, data_keys=["input", "mask"])
+ output, tensor_mask = seq(image, mask)
+ params = seq._params
+ _, masks = seq(image, [mask[:1].clone(), mask[1:].clone()], params=params)
+ _, restored_tensor = seq.inverse(output, tensor_mask, params=params)
+ _, restored = seq.inverse(output, masks, params=params)
+ assert not torch.equal(tensor_mask, mask)
+ for i in range(2):
+ self.assert_close(masks[i], tensor_mask[i : i + 1])
+ self.assert_close(restored[i], restored_tensor[i : i + 1])
+
+ @pytest.mark.parametrize("child", ["video", "mix", "cutmix", "mosaic", "jigsaw", "patch", "3d"])
+ def test_mask_list_unsupported_children_raise_4477(self, child, device, dtype):
+ image = torch.rand(2, 3, 4, 4, device=device, dtype=dtype)
+ entries = [torch.zeros(1, 1, 4, 4, device=device, dtype=dtype) for _ in range(2)]
+ if child == "video":
+ image = torch.rand(2, 2, 3, 4, 4, device=device, dtype=dtype)
+ module = K.VideoSequential(K.RandomHorizontalFlip(p=1.0), data_format="BTCHW")
+ elif child == "mix":
+ module = K.RandomMixUpV2(p=1.0)
+ elif child == "cutmix":
+ module = K.RandomCutMixV2(p=1.0)
+ elif child == "mosaic":
+ module = K.RandomMosaic(p=1.0)
+ elif child == "jigsaw":
+ module = K.RandomJigsaw((2, 2), p=1.0)
+ elif child == "patch":
+ module = K.PatchSequential(K.RandomHorizontalFlip(p=1.0), grid_size=(2, 2), random_apply=True)
+ else:
+ image = torch.rand(2, 1, 2, 4, 4, device=device, dtype=dtype)
+ entries = [torch.zeros(1, 1, 2, 4, 4, device=device, dtype=dtype) for _ in range(2)]
+ module = K.RandomHorizontalFlip3D(p=1.0)
+ seq = K.AugmentationSequential(module, data_keys=["input", "mask"])
+ with pytest.raises(NotImplementedError):
+ seq(image, entries)
+ output = seq(image, data_keys=["input"])
+ if child not in ("mix", "cutmix", "mosaic", "jigsaw"):
+ with pytest.raises(NotImplementedError):
+ seq.inverse(output, entries, data_keys=["input", "mask"])
+ with pytest.raises(NotImplementedError):
+ seq.inverse(entries, data_keys=["mask"])
+
+ @pytest.mark.parametrize("mask_only", [False, True])
+ def test_mask_list_transplantation_rejected_before_parameter_calculation_4477(self, mask_only, device, dtype):
+ image = torch.arange(2 * 16, device=device, dtype=dtype).reshape(2, 1, 4, 4)
+ mask = torch.zeros(2, 1, 4, 4, device=device, dtype=torch.long)
+ mask[:, :, :2, :2] = 1
+ seq = K.AugmentationSequential(K.RandomTransplantation(p=1.0), data_keys=["input", "mask"])
+ # Tensor masks remain supported, and provide a saved draw for mask-only replay.
+ output, tensor_mask = seq(image.clone(), mask.clone())
+ assert output.shape == image.shape
+ assert tensor_mask.shape == mask.shape
+ entries = [mask[:1].clone(), mask[1:].clone()]
+ args = (entries,) if mask_only else (image, entries)
+ kwargs = {"params": seq._params, "data_keys": ["mask"]} if mask_only else {}
+ with pytest.raises(NotImplementedError, match="RandomTransplantation does not support mask lists"):
+ seq(*args, **kwargs)
+
+ def test_mask_list_passes_through_intensity_patch_sequential_4477(self, device, dtype):
+ image = torch.rand(2, 3, 4, 4, device=device, dtype=dtype)
+ entries = [torch.rand(1, 1, 4, 4, device=device, dtype=dtype) for _ in range(2)]
+ patch = K.PatchSequential(K.RandomGaussianBlur((3, 3), (0.5, 0.5), p=1.0), grid_size=(2, 2), random_apply=True)
+ seq = K.AugmentationSequential(patch, data_keys=["input", "mask"])
+ output, masks = seq(image, entries)
+ _, restored = seq.inverse(output, masks)
+ for actual, restored_entry, expected in zip(masks, restored, entries):
+ self.assert_close(actual, expected)
+ self.assert_close(restored_entry, expected)
def test_mix_augmentation_inverse_raises_4693(self, device, dtype):
image = torch.stack([torch.full((2, 4, 6), float(i + 1), device=device, dtype=dtype) for i in range(3)])
@@ -1613,7 +1926,7 @@ class TestConventionAugmentationSequential(BaseTester):
# entry comes back in its own dtype, as in the forward pass (#4478).
image = torch.arange(48, device=device, dtype=dtype).reshape(2, 1, 4, 6)
labels = torch.arange(24, device=device).reshape(1, 1, 4, 6).expand(2, 1, -1, -1) % 5
- masks = [labels.clone(), (labels > 2)]
+ masks = [labels[:1].clone(), (labels[1:] > 2)]
seq = K.AugmentationSequential(K.RandomHorizontalFlip(p=1.0), data_keys=["input", "mask"])
out_image, out_masks = seq(image, masks)
restored_image, restored = seq.inverse(out_image, out_masks)
@@ -1625,10 +1938,10 @@ class TestConventionAugmentationSequential(BaseTester):
assert torch.equal(entry, original)
def test_list_mask_inverse_uses_each_entrys_forward_gate_4716(self, device, dtype):
- # The forward pass gives list entry i the gate of sample i (the #4477 wart). The inverse has to
+ # The forward pass gives list entry i the gate of sample i. The inverse has to
# reuse that same gate, or a mixed-probability batch would come back half re-flipped.
image = torch.arange(24, device=device, dtype=dtype).reshape(2, 1, 3, 4)
- masks = [image.clone(), image.expand(-1, 2, -1, -1).clone()]
+ masks = [image[:1].clone(), image[1:].expand(-1, 2, -1, -1).clone()]
seq = K.AugmentationSequential(K.RandomHorizontalFlip(p=0.5), data_keys=["input", "mask"])
params = [
ParamItem(
@@ -1642,14 +1955,14 @@ class TestConventionAugmentationSequential(BaseTester):
self.assert_close(restored[1], masks[1])
def test_list_mask_inverse_through_a_nested_sequential_4716(self, device, dtype):
- image = torch.arange(24, device=device, dtype=dtype).reshape(1, 1, 4, 6)
- masks = [image.clone(), image.clone() * 2]
+ image = torch.arange(24, device=device, dtype=dtype).reshape(1, 1, 4, 6).repeat(2, 1, 1, 1)
+ masks = [image[:1].clone(), image[1:].clone() * 2]
seq = K.AugmentationSequential(
K.ImageSequential(K.RandomHorizontalFlip(p=1.0), K.RandomVerticalFlip(p=1.0)),
data_keys=["input", "mask"],
)
out_image, out_masks = seq(image, masks)
- self.assert_close(out_masks[0], image.flip(-1).flip(-2))
+ self.assert_close(out_masks[0], image[:1].flip(-1).flip(-2))
_, restored = seq.inverse(out_image, out_masks)
for entry, original in zip(restored, masks):
self.assert_close(entry, original)
@@ -1659,7 +1972,7 @@ class TestConventionAugmentationSequential(BaseTester):
# A quarter turn can: applying the forward matrix again gives a half turn instead of the identity.
image = torch.rand(2, 1, 8, 8, device=device, dtype=dtype)
labels = torch.arange(64, device=device).reshape(1, 1, 8, 8).expand(2, 1, -1, -1) % 7
- masks = [labels.clone(), labels > 3]
+ masks = [labels[:1].clone(), labels[1:] > 3]
seq = K.AugmentationSequential(K.RandomRotation(degrees=(90.0, 90.0), p=1.0), data_keys=["input", "mask"])
out_image, out_masks = seq(image, masks)
assert not torch.equal(out_masks[0], labels)
diff --git a/tests/augmentation/test_base.py b/tests/augmentation/test_base.py
index fd5525b68..d3f75af2b 100644
--- a/tests/augmentation/test_base.py
+++ b/tests/augmentation/test_base.py
@@ -757,15 +757,16 @@ class TestConventionAugmentationBase2D(BaseTester):
with pytest.raises(NotImplementedError):
K.AugmentationSequential(aug, data_keys=["input", key])(image, data)
- def test_convention_bhw_mask_list_entry_follows_the_image_5598(self, device, dtype):
- # A batched (B, H, W) mask takes its batch size from ``batch_prob`` (#5598). A list entry has a 0-d gate and
- # still reads a first dimension equal to the image batch as that batch, so each row gets its own crop window.
- # The meaning of a mask list is tracked in #4477.
+ def test_convention_bhw_mask_uses_tensor_not_list_5598(self, device, dtype):
+ # A batched (B, H, W) mask takes its batch size from ``batch_prob`` (#5598). A mask list instead holds
+ # one tensor per image sample (#4477); wrapping the full batch in a one-element list is invalid.
image = torch.arange(2 * 64, device=device).to(dtype).reshape(2, 1, 8, 8)
sequence = K.AugmentationSequential(K.RandomCrop((4, 4), p=1.0), data_keys=["input", "mask"])
- output_image, output_masks = sequence(image, [image[:, 0]])
- assert output_masks[0].shape == (2, 1, 4, 4)
- self.assert_close(output_masks[0], output_image, rtol=0, atol=0)
+ output_image, output_mask = sequence(image, image[:, 0])
+ assert output_mask.shape == (2, 1, 4, 4)
+ self.assert_close(output_mask, output_image, rtol=0, atol=0)
+ with pytest.raises(ValueError, match="one entry per sample"):
+ sequence(image, [image[:, 0]])
@pytest.mark.parametrize("first_dim", [2, 3])
def test_convention_3d_mask_keepdim_returns_its_rank_5598(self, device, dtype, first_dim):