π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
fix(augmentation): repeat a single mask for video inputs and mask-only replays (#5636)
Arij Belmabroukd7ce2a43ea04
diff --git a/changelog.d/5636.breaking.md b/changelog.d/5636.breaking.mdnew file mode 100644index 000000000..2dc71f6b5--- /dev/null+++ b/changelog.d/5636.breaking.md@@ -0,0 +1 @@+`AugmentationSequential` now repeats a single mask to the batch in two more cases, so each sample's own parameters apply to its copy and the mask comes back with batch `B`: a `(1, T, C, H, W)` mask next to a `(B, T, C, H, W)` video (a `VideoSequential` child; next to a BTCHW video a `(1, T, H, W)` mask too), and a mask replayed alone with `params=` and no image, which is repeated to the batch recorded in those params (`forward_input_shape[0]`; for a video, a new `video_batch_size` entry that `VideoSequential` now adds to each child's parameters). Previously both came back at batch 1: flips and crops applied sample 0's parameters only, and `RandomAffine` raised `grid_sampler(): expected grid and input to have same batch size`. For example, with a batch-2 video a `(1, T, 1, H, W)` mask through `RandomHorizontalFlip` used to come back as `(1, T, 1, H, W)` and now comes back as `(2, T, 1, H, W)`. Some inputs that used to run, or to fail late, now raise `ValueError`: a mask next to a video that is neither 5D nor a 4D mask next to a BTCHW video (it failed later inside the `VideoSequential` reshape or came back with a wrong shape; with `same_on_frame=False` a `(1, 4, 8, 8)` mask next to a 4-frame BCTHW video came back as `(1, 1, 8, 4, 8)`), a 1D mask (it used to raise `RuntimeError`), a 5D mask next to a non-video image, a mask whose frame count differs from the video's, and a replayed mask whose batch is neither 1 nor the recorded batch (`RandomHorizontalFlip` and `RandomCrop` used to run silently with a wrong result). Full-batch masks and 3D-augmentation containers are unchanged. A `VideoSequential` nested inside another container keeps the old behavior.diff --git a/kornia/augmentation/container/augment.py b/kornia/augmentation/container/augment.pyindex 720c4db9b..d91dc5f99 100644--- a/kornia/augmentation/container/augment.py+++ b/kornia/augmentation/container/augment.py@@ -136,8 +136,13 @@ class AugmentationSequential(TransformMatrixMinIn, ImageSequential):``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 ownparameters 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>`_).+ masks is not repeated. A single ``(1, T, C, H, W)`` mask is repeated the same way next to a+ ``(B, T, C, H, W)`` video. Next to a BTCHW video a ``(B, T, H, W)`` mask is read with one channel and+ returned as ``(B, T, 1, H, W)``, and a single ``(1, T, H, W)`` mask is repeated too. Any other mask rank+ next to a video, or a 5D mask next to a non-video image, raises ``ValueError`` instead of guessing. A+ replay with no image (``params=`` given, no ``INPUT`` key) reads the batch to repeat to from the recorded+ params instead. 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`does. Labels pass through geometric steps untouched.@@ -491,7 +496,9 @@ class AugmentationSequential(TransformMatrixMinIn, ImageSequential):return outputs- def _validate_args_datakeys(self, *args: DataType, data_keys: List[DataKey]) -> None:+ def _validate_args_datakeys(+ self, *args: DataType, data_keys: List[DataKey], params: Optional[List[ParamItem]] = None+ ) -> None:if len(args) != len(data_keys):raise AssertionError(f"The number of inputs must align with the number of data_keys. Got {len(args)} and {len(data_keys)}."@@ -502,21 +509,63 @@ class AugmentationSequential(TransformMatrixMinIn, ImageSequential):if key in _IMG_OPTIONS:image = argbreak- if not isinstance(image, torch.Tensor) or image.ndim not in (3, 4):+ image_size: Optional[torch.Size] = None+ # 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)):+ 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:+ # A replay has no image; only the mask batch is checked, against the recorded params.+ image_batch = self._batch_size_from_params(params)+ else:+ return+ if image_batch is None:return- image_batch = image.shape[0] if image.ndim == 4 else 1- image_size = image.shape[-2:]+ # The frame axis of a video, 1 for BTCHW and 2 for BCTHW. A list, not next(generator, None), which Dynamo on+ # torch 2.5/2.6 cannot trace (see above).+ videos = [c for c in self.children() if isinstance(c, VideoSequential)] if is_video else []+ temporal_dim = videos[0]._temporal_channel if videos else 1for mask, key in zip(args, data_keys):- if key not in _MSK_OPTIONS or not isinstance(mask, torch.Tensor) or mask.ndim not in (2, 3, 4):+ if key not in _MSK_OPTIONS:+ 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+ # one channel as it reads a (B, H, W) mask next to an image. A 5D mask is never valid next to an image.+ # Any other combination raises here instead of guessing and failing later with a confusing reshape error.+ if mask.ndim == 5 and not is_video:+ raise ValueError(f"A 5D mask is only valid next to a video; got mask {tuple(mask.shape)}.")+ if is_video and not (mask.ndim == 5 or (mask.ndim == 4 and temporal_dim == 1)):+ raise ValueError(+ "A mask next to a video must be 5D, (1, T, C, H, W) or (B, T, C, H, W), or (1, T, H, W) or "+ f"(B, T, H, W) next to a BTCHW video; got mask {tuple(mask.shape)}."+ )+ if (+ is_video+ and isinstance(image, torch.Tensor)+ and image.ndim == 5+ and mask.shape[temporal_dim] != image.shape[temporal_dim]+ ):+ raise ValueError(+ "Video and mask must have the same number of frames; "+ f"got video {tuple(image.shape)} and mask {tuple(mask.shape)}."+ )+ mask_batch = mask.shape[0] if mask.ndim in (4, 5) else 1+ if image_size is None:+ if mask_batch not in (1, image_batch):+ raise ValueError(f"Mask batch size must be 1 or {image_batch}; got mask {tuple(mask.shape)}.")continue- mask_batch = mask.shape[0] if mask.ndim == 4 else 1if mask_batch not in (1, image_batch) or mask.shape[-2:] != image_size:raise ValueError("Image and mask must have matching spatial dimensions and compatible batch sizes "f"(1 or {image_batch}); got image {tuple(image.shape)} and mask {tuple(mask.shape)}.")- def _arguments_preproc(self, *args: DataType, data_keys: List[DataKey]) -> List[DataType]:+ def _arguments_preproc(+ self, *args: DataType, data_keys: List[DataKey], params: Optional[List[ParamItem]] = None+ ) -> List[DataType]:# Resolve this call's image dtype before any mask is converted, so a mask that precedes the image in# dictionary insertion order uses it too, rather than the previous call's image dtype (or ``float32`` on# a fresh container). It is kept in a local rather than read back from ``self.input_dtype``, so the same@@ -524,13 +573,21 @@ class AugmentationSequential(TransformMatrixMinIn, ImageSequential):# after an image use the most recent image, as before; a call with no image falls back to the attribute.working_dtype = self.input_dtypeimage_batch: Optional[int] = None+ has_image = Falsefor arg, dcate in zip(args, data_keys):if DataKey.get(dcate) in _IMG_OPTIONS:+ has_image = Trueworking_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:+ # Only a batched ``(B, C, H, W)`` image, or a video's ``(B, T, C, H, W)``, has a batch to+ # broadcast a single mask over; a 5D 3D-augmentation volume is left alone, as before.+ if isinstance(arg, torch.Tensor) and (+ arg.ndim == 4 or (arg.ndim == 5 and self.contains_video_sequential)+ ):image_batch = arg.shape[0]break+ if not has_image and params is not None:+ # A replay has no image in this call; fall back to the batch its params were drawn for.+ image_batch = self._batch_size_from_params(params)inp: List[DataType] = []for arg, dcate in zip(args, data_keys):if DataKey.get(dcate) in _IMG_OPTIONS:@@ -629,9 +686,9 @@ class AugmentationSequential(TransformMatrixMinIn, ImageSequential):self.transform_op.data_keys = original_data_keystry:- self._validate_args_datakeys(*args, data_keys=original_data_keys)+ self._validate_args_datakeys(*args, data_keys=original_data_keys, params=params)- in_args = self._arguments_preproc(*args, data_keys=original_data_keys)+ in_args = self._arguments_preproc(*args, data_keys=original_data_keys, params=params)# Annotation handlers may read the matrix recorded by the image call. Process INPUT first for every child,# including nested containers and policies, then restore the caller's order below.@@ -867,9 +924,10 @@ class AugmentationSequential(TransformMatrixMinIn, ImageSequential):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.+ one ``(C, H, W)`` mask. A 5D ``(1, T, C, H, W)`` mask, or a 4D ``(1, T, H, W)`` one, next to a video, only+ expands dim 0; ``T`` is left alone."""- if image_batch is None or image_batch == 1 or mask.ndim not in (2, 3, 4):+ if image_batch is None or image_batch == 1 or mask.ndim not in (2, 3, 4, 5):return maskif mask.ndim == 2:mask = mask[None] # one (H, W) mask@@ -880,6 +938,49 @@ class AugmentationSequential(TransformMatrixMinIn, ImageSequential):# ``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()+ @staticmethod+ def _batch_size_from_params(params: List[ParamItem]) -> Optional[int]:+ """Extract the replay batch size when no image is available.++ Args:+ params: Recorded parameter tree for the replayed augmentation call.++ Returns:+ The original batch size, or None if no batch size could be recovered.+ """++ def _read_batch_size(value: Any) -> Optional[int]:+ """Recursively read the original batch size stored in nested parameter metadata.++ Args:+ value: A nested replay parameter value produced by a sequential augmentation.++ Returns:+ The recovered batch size, or None when no batch metadata is present.+ """+ if isinstance(value, ParamItem):+ return _read_batch_size(value.data)+ if isinstance(value, list):+ for item in value:+ batch = _read_batch_size(item)+ if batch is not None:+ return batch+ return None+ if isinstance(value, dict):+ video_batch = value.get("video_batch_size")+ if video_batch is not None:+ return int(torch.as_tensor(video_batch).reshape(-1)[0].item())+ forward_input_shape = value.get("forward_input_shape")+ if forward_input_shape is not None:+ return int(torch.as_tensor(forward_input_shape).reshape(-1)[0].item())+ return None++ for item in params:+ batch = _read_batch_size(item)+ if batch is not None:+ return batch+ return None+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# dtype would cast every mask to whichever mask came last: an integer semantic mask followed by a booleandiff --git a/kornia/augmentation/container/video.py b/kornia/augmentation/container/video.pyindex 2b9fefae0..ffd8fb283 100644--- a/kornia/augmentation/container/video.py+++ b/kornia/augmentation/container/video.py@@ -189,6 +189,27 @@ class VideoSequential(ImageSequential):return v.unsqueeze(1).repeat(1, batch_shape[0], *([1] * (v.ndim - 1))).reshape(-1, *v.shape[1:])return v+ @staticmethod+ def _record_video_batch_size(+ param: Union[Dict[str, torch.Tensor], List[ParamItem]], original_batch_size: int+ ) -> None:+ """Attach the original video batch size to nested replay metadata.++ Args:+ param: Parameter tree returned by a nested sequential container.+ original_batch_size: Batch size of the public video before frame flattening.+ """+ if isinstance(param, dict):+ if "forward_input_shape" in param:+ param["video_batch_size"] = torch.full(+ (), original_batch_size, device=param["forward_input_shape"].device, dtype=torch.long+ )+ return+ if isinstance(param, list):+ for item in param:+ if isinstance(item, ParamItem) and isinstance(item.data, (dict, list)):+ VideoSequential._record_video_batch_size(item.data, original_batch_size)+def _input_shape_convert_in(self, input: torch.Tensor, frame_num: int) -> torch.Tensor:# Convert any shape to (B, T, C, H, W)if self.data_format == "BCTHW":@@ -200,6 +221,15 @@ class VideoSequential(ImageSequential):return input.reshape(-1, *input.shape[2:])def _input_shape_convert_back(self, input: torch.Tensor, frame_num: int) -> torch.Tensor:+ """Reshape a flattened video tensor back to its original layout.++ Args:+ input: Flattened tensor with the frame dimension merged into the batch axis.+ frame_num: Number of frames in each video clip.++ Returns:+ The tensor reshaped back to the original video layout.+ """input = input.view(-1, frame_num, *input.shape[1:])if self.data_format == "BCTHW":input = input.transpose(1, 2)@@ -219,6 +249,7 @@ class VideoSequential(ImageSequential):across frames depending on ``same_on_frame`` and module settings."""frame_num = batch_shape[self._temporal_channel]+ original_batch_size = batch_shape[0]named_modules = self.get_forward_sequence()# Got param generation shape to (B, C, H, W). Ignoring T.batch_shape = self.__infer_channel_exclusive_batch_shape__(batch_shape, self._temporal_channel)@@ -240,16 +271,21 @@ class VideoSequential(ImageSequential):mod_param = module.forward_parameters(mod_shape)if isinstance(mod_param, dict):- for k, v in mod_param.items():+ self._record_video_batch_size(mod_param, original_batch_size)+ for k, v in list(mod_param.items()):# TODO: revise ColorJiggle and ColorJitter order param in the future to align the standard.if k == "order" and isinstance(module, (K.ColorJiggle, K.ColorJitter)):continue+ if k == "video_batch_size":+ continueif k == "forward_input_shape":mod_param.update({k: v})continuemod_param[k] = self.__broadcast_param__(v, batch_shape, frame_num, self.same_on_frame, is_same_on_batch)+ elif isinstance(mod_param, list):+ self._record_video_batch_size(mod_param, original_batch_size)param = ParamItem(name, mod_param)@@ -257,6 +293,7 @@ class VideoSequential(ImageSequential):# Frames are flattened to (B * T, ...) before the nested container runs, so it# needs one draw per frame, like the unnested branch above.seq_param = module.forward_parameters(torch.Size([batch_shape[0] * frame_num, *batch_shape[1:]]))+ self._record_video_batch_size(seq_param, original_batch_size)if self.same_on_frame:raise ValueError("nn.Sequential is currently unsupported for ``same_on_frame``.")param = ParamItem(name, seq_param)diff --git a/tests/augmentation/container/test_augmentation_sequential.py b/tests/augmentation/container/test_augmentation_sequential.pyindex ffb8545a6..5bbe52e06 100644--- a/tests/augmentation/container/test_augmentation_sequential.py+++ b/tests/augmentation/container/test_augmentation_sequential.py@@ -311,6 +311,177 @@ class TestAugmentationSequential:assert_close(out_mask, mask.flip(-1))+ def test_video_single_mask_follows_each_samples_own_flip_5624(self, device, dtype):+ # Entry point 1 of #5624: a (1, T, C, H, W) mask next to a (B, T, C, H, W) video; each output mask+ # must equal its own sample's augmented image, and the test uses a fixed per-sample batch_prob so the+ # fixture is deterministic and not dependent on the global RNG.+ mask = torch.rand(1, 4, 1, 8, 8, device=device, dtype=dtype)+ image = mask.expand(2, -1, 3, -1, -1).clone()+ aug = K.AugmentationSequential(+ K.VideoSequential(K.RandomHorizontalFlip(p=0.5), data_format="BTCHW"), data_keys=["input", "mask"]+ )+ out_image, out_mask = aug(image, mask)+ aug._params[0].data[0].data["batch_prob"] = torch.tensor(+ [True, False, True, False, False, True, False, True], device=device, dtype=torch.bool+ )+ out_image, out_mask = aug(image, mask, params=aug._params)++ assert out_mask.shape == (2, 4, 1, 8, 8)+ assert_close(out_mask, out_image[:, :, :1])++ @pytest.mark.parametrize("data_format", ["BTCHW", "BCTHW"])+ def test_video_single_mask_equals_an_explicit_full_batch_mask_5624(self, data_format, device, dtype):+ # Entry point 1 of #5624, RandomAffine: a single mask must match an already-expanded one, not just avoid+ # the grid_sampler batch-size error. BCTHW puts the frames on dim 2, so its frame check must not read the+ # channel axis (1 mask channel against 3 image channels).+ channels_first = data_format == "BCTHW"+ image = torch.rand(*((2, 3, 4) if channels_first else (2, 4, 3)), 8, 8, device=device, dtype=dtype)+ mask = torch.rand(*((1, 1, 4) if channels_first else (1, 4, 1)), 8, 8, device=device, dtype=dtype)+ outputs = []+ for candidate in (mask, mask.expand(2, -1, -1, -1, -1).clone()):+ torch.manual_seed(5)+ aug = K.AugmentationSequential(+ K.VideoSequential(K.RandomAffine(30.0, p=1.0), data_format=data_format), data_keys=["input", "mask"]+ )+ outputs.append(aug(image, candidate)[1])++ assert outputs[0].shape == (2, *mask.shape[1:])+ assert_close(outputs[0], outputs[1])++ @pytest.mark.parametrize("nested", [False, True])+ def test_video_replay_single_mask_uses_the_video_batch_5624(self, nested, device, dtype):+ # Entry point 2 of #5624 for a video: with same_on_frame=False each child records B * T rows in+ # forward_input_shape, so a mask-only replay must repeat a single mask to the video batch B that+ # VideoSequential records, also through a nested container.+ video = torch.rand(3, 4, 3, 8, 8, device=device, dtype=dtype)+ mask = torch.rand(1, 4, 1, 8, 8, device=device, dtype=dtype)+ child = K.RandomAffine(30.0, p=1.0)+ aug = K.AugmentationSequential(+ K.VideoSequential(K.ImageSequential(child) if nested else child, same_on_frame=False),+ data_keys=["input", "mask"],+ )+ aug(video, mask.expand(3, -1, -1, -1, -1).clone())++ out_single = aug(mask, params=aug._params, data_keys=["mask"])+ out_full = aug(mask.expand(3, -1, -1, -1, -1).clone(), params=aug._params, data_keys=["mask"])+ assert out_single.shape == (3, 4, 1, 8, 8)+ assert_close(out_single, out_full)++ def test_replay_single_mask_follows_each_samples_own_flip_5624(self, device, dtype):+ # Entry point 2 of #5624: a mask replayed alone (no image) with params recorded for batch > 1 must+ # match an already-expanded replay, and the fixture uses a fixed batch_prob pattern so the result is+ # deterministic and independent of global RNG state.+ image = torch.rand(3, 3, 8, 8, device=device, dtype=dtype)+ mask = torch.rand(1, 1, 8, 8, device=device, dtype=dtype)+ aug = K.AugmentationSequential(K.RandomHorizontalFlip(p=0.5), data_keys=["input", "mask"])+ aug(image, mask.expand(3, -1, -1, -1).clone())+ aug._params[0].data["batch_prob"] = torch.tensor([True, False, True], device=device, dtype=torch.bool)++ out_mask = aug(mask, params=aug._params, data_keys=["mask"])+ expected = aug(mask.expand(3, -1, -1, -1).clone(), params=aug._params, data_keys=["mask"])+ assert out_mask.shape == expected.shape+ assert_close(out_mask, expected)++ def test_replay_single_mask_equals_an_explicit_full_batch_mask_5624(self, device, dtype):+ # Entry point 2 of #5624, RandomAffine: a replayed single mask must match an already-expanded one, not+ # just avoid the grid_sampler batch-size error.+ image = torch.rand(3, 3, 8, 8, device=device, dtype=dtype)+ mask = torch.rand(1, 1, 8, 8, device=device, dtype=dtype)+ aug = K.AugmentationSequential(K.RandomAffine(30.0, p=1.0), data_keys=["input", "mask"])+ aug(image, mask.expand(3, -1, -1, -1).clone())++ out_single = aug(mask, params=aug._params, data_keys=["mask"])+ out_full = aug(mask.expand(3, -1, -1, -1).clone(), params=aug._params, data_keys=["mask"])+ assert out_single.shape == (3, 1, 8, 8)+ assert_close(out_single, out_full)++ def test_video_mask_batch_mismatch_raises_5624(self, device, dtype):+ # A mask batch that is neither 1 nor the video batch is rejected, as for a 4-D image (#5618).+ image = torch.rand(2, 4, 3, 8, 8, device=device, dtype=dtype)+ mask = torch.rand(3, 4, 1, 8, 8, device=device, dtype=dtype)+ aug = K.AugmentationSequential(+ K.VideoSequential(K.RandomHorizontalFlip(p=1.0), data_format="BTCHW"), data_keys=["input", "mask"]+ )++ with pytest.raises(ValueError, match="batch"):+ aug(image, mask)++ def test_video_mask_frame_count_mismatch_raises_5624(self, device, dtype):+ image = torch.rand(2, 4, 3, 8, 8, device=device, dtype=dtype)+ mask = torch.rand(2, 3, 1, 8, 8, device=device, dtype=dtype) # 3 frames, the video has 4+ aug = K.AugmentationSequential(+ K.VideoSequential(K.RandomHorizontalFlip(p=1.0), data_format="BTCHW"), data_keys=["input", "mask"]+ )+ with pytest.raises(ValueError, match="frames"):+ aug(image, mask)++ def test_replay_mask_batch_mismatch_raises_5624(self, device, dtype):+ # A replayed mask batch that is neither 1 nor the recorded batch is rejected the same way.+ image = torch.rand(3, 3, 8, 8, device=device, dtype=dtype)+ mask = torch.rand(1, 1, 8, 8, device=device, dtype=dtype)+ aug = K.AugmentationSequential(K.RandomHorizontalFlip(p=1.0), data_keys=["input", "mask"])+ aug(image, mask.expand(3, -1, -1, -1).clone())+ bad_mask = torch.rand(2, 1, 8, 8, device=device, dtype=dtype)++ with pytest.raises(ValueError, match="batch"):+ aug(bad_mask, params=aug._params, data_keys=["mask"])++ @pytest.mark.parametrize(+ "data_format,mask_shape",+ [("BTCHW", (8, 8)), ("BTCHW", (4, 8, 8)), ("BTCHW", (1, 2, 4, 1, 8, 8)), ("BCTHW", (2, 4, 8, 8))],+ )+ def test_video_ambiguous_mask_rank_raises_5624(self, data_format, mask_shape, device, dtype):+ # Next to a video a mask is 5D, or (B, T, H, W) for a BTCHW video; any other rank is ambiguous (missing+ # channel? missing batch? a plain 2D mask?), so it must raise here rather than fail later inside+ # VideoSequential's own reshape. A BCTHW video reads its frames from dim 2, which a 4D mask does not have.+ shape = (2, 4, 3, 8, 8) if data_format == "BTCHW" else (2, 3, 4, 8, 8)+ image = torch.rand(*shape, device=device, dtype=dtype)+ mask = torch.rand(*mask_shape, device=device, dtype=dtype)+ aug = K.AugmentationSequential(+ K.VideoSequential(K.RandomHorizontalFlip(p=1.0), data_format=data_format), data_keys=["input", "mask"]+ )++ with pytest.raises(ValueError, match="5D"):+ aug(image, mask)++ @pytest.mark.parametrize("mask_batch", [1, 2])+ def test_video_bthw_mask_equals_the_5d_mask_5624(self, mask_batch, device, dtype):+ # A BTCHW video reads a (B, T, H, W) mask with one channel and repeats a single (1, T, H, W) mask like a 5D+ # one. The default same_on_frame=True also needs the batch_prob rule of #5598 for a 4D mask.+ video = torch.rand(2, 4, 3, 8, 8, device=device, dtype=dtype)+ mask = torch.rand(mask_batch, 4, 8, 8, device=device, dtype=dtype)+ outputs = []+ for candidate in (mask, mask.expand(2, -1, -1, -1)[:, :, None].clone()):+ torch.manual_seed(5)+ aug = K.AugmentationSequential(+ K.VideoSequential(K.RandomAffine(30.0, p=1.0), same_on_frame=False), data_keys=["input", "mask"]+ )+ outputs.append(aug(video, candidate)[1])++ assert outputs[0].shape == (2, 4, 1, 8, 8)+ assert_close(outputs[0], outputs[1])++ def test_5d_mask_without_a_video_raises_5624(self, device, dtype):+ # The mirror case: a 5D mask is only meaningful next to a video. Next to a plain 4D image it is+ # ambiguous, so it must raise here rather than fail later with a confusing shape error.+ image = torch.rand(2, 3, 8, 8, device=device, dtype=dtype)+ mask = torch.rand(1, 4, 1, 8, 8, device=device, dtype=dtype)+ aug = K.AugmentationSequential(K.RandomHorizontalFlip(p=1.0), data_keys=["input", "mask"])++ with pytest.raises(ValueError, match="5D"):+ aug(image, mask)++ def test_3d_augmentation_replay_mask_keeps_its_own_error_5624(self, device, dtype):+ # A 3D augmentation's own "not yet supported" mask error must still surface on replay, not the+ # video/5D-mask ValueError meant for a video (3D volumes and videos are both 5D).+ volume = torch.rand(2, 1, 4, 8, 8, device=device, dtype=dtype)+ aug = K.AugmentationSequential(K.RandomHorizontalFlip3D(p=1.0), data_keys=["input", "mask"])+ aug(volume, data_keys=["input"])+ mask = torch.rand(2, 1, 4, 8, 8, device=device, dtype=dtype)++ with pytest.raises(NotImplementedError, match="3d mask"):+ aug(mask, params=aug._params, data_keys=["mask"])+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)mask = torch.ones(1, 1, 16, 20, device=device, dtype=dtype)diff --git a/tests/augmentation/test_augmentation_compile.py b/tests/augmentation/test_augmentation_compile.pyindex bd90ee08c..2dead5c4e 100644--- a/tests/augmentation/test_augmentation_compile.py+++ b/tests/augmentation/test_augmentation_compile.py@@ -464,3 +464,17 @@ class TestContainerCompile(BaseTester):self.assert_close(out, ref)self.assert_close(out, input.flip(-1))assert counter.frame_count == 1++ @pytest.mark.skipif(not dynamo_is_available(), reason="no Dynamo on this torch/python pair")+ @pytest.mark.parametrize("mask_batch", [1, 2])+ def test_eager_backend_traces_video_container_with_mask_in_one_graph(self, device, dtype, mask_batch):+ # The video mask checks (#5624) run on every call; Dynamo on torch 2.5.1 cannot trace next() with a default.+ torch._dynamo.reset()+ aug = K.AugmentationSequential(K.VideoSequential(K.RandomHorizontalFlip(p=1.0)), data_keys=["input", "mask"])+ video = torch.rand(2, 4, 3, 4, 6, device=device, dtype=dtype)+ mask = torch.rand(mask_batch, 4, 1, 4, 6, device=device, dtype=dtype)+ counter = CompileCounter()+ out_video, out_mask = torch.compile(aug, backend=counter, fullgraph=True)(video, mask)+ self.assert_close(out_video, video.flip(-1))+ self.assert_close(out_mask, mask.expand(2, -1, -1, -1, -1).flip(-1))+ assert counter.frame_count == 1