π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
fix(augmentation): repeat CutMix parameters across video frames (#6138)
Muhammad Talha9ff9a565381a
diff --git a/changelog.d/6138.fixed.md b/changelog.d/6138.fixed.mdnew file mode 100644index 000000000..bb91d6e62--- /dev/null+++ b/changelog.d/6138.fixed.md@@ -0,0 +1 @@+Fixed `VideoSequential` raising an `IndexError` for `RandomCutMixV2` with the default `same_on_frame=True`, and with `same_on_frame=False` when the CutMix has `same_on_batch=True` and the batch holds more than one video. With `same_on_frame=True` the mix parameters are now repeated over the frames along the video axis, so every frame of a video cuts the same box from the matching frame of the same partner video.diff --git a/kornia/augmentation/container/video.py b/kornia/augmentation/container/video.pyindex 817bb29bf..2ec346671 100644--- a/kornia/augmentation/container/video.py+++ b/kornia/augmentation/container/video.py@@ -189,6 +189,35 @@ class VideoSequential(ImageSequential):return v.unsqueeze(1).repeat(1, batch_shape[0], *([1] * (v.ndim - 1))).reshape(-1, *v.shape[1:])return v+ def _broadcast_cutmix_params(self, params: Dict[str, torch.Tensor], frame_num: int) -> None:+ """Repeat the parameters of :class:`~kornia.augmentation.RandomCutMixV2` over the frames of each video.++ The generator lays its parameters out as ``(num_mix, B, ...)``: the video is axis 1, so the repeat of+ :meth:`__broadcast_param__` over axis 0 would repeat the mixes instead of the frames. ``mix_pairs`` also+ holds video indices, which must become indices into the ``B * T`` flattened frames. Frame ``t`` of a video+ is mixed with frame ``t`` of its partner video, so all frames of a video cut the same box from the same+ partner.++ Args:+ params: Parameters drawn for the ``B`` videos; updated in place to cover the ``B * T`` frames.+ frame_num: Number of frames ``T`` in each video.+ """+ for key, value in list(params.items()):+ if not value.numel():+ continue+ if key == "mix_pairs":+ # (num_mix, B) => (num_mix, B * T), entry [m, b * T + t] = pairs[m, b] * T + t.+ frames = torch.arange(frame_num, device=value.device, dtype=value.dtype)+ params[key] = (value[..., None] * frame_num + frames).reshape(value.shape[0], -1)+ elif key == "crop_src":+ # (num_mix, B, 4, 2) => (num_mix, B * T, 4, 2)+ params[key] = value.repeat_interleave(frame_num, dim=1)+ elif key == "batch_prob":+ # (B,) => (B * T,)+ params[key] = self.__repeat_param_across_channels__(value, frame_num)+ # ``image_shape`` is the (H, W) of every image and ``forward_input_shape`` / ``video_batch_size`` are+ # metadata: none of them has a per-video axis, so they stay as drawn.+@staticmethoddef _record_video_batch_size(param: Union[Dict[str, torch.Tensor], List[ParamItem]], original_batch_size: int@@ -257,7 +286,10 @@ class VideoSequential(ImageSequential):params = []for name, module in named_modules:if isinstance(module, (K.RandomCrop, _AugmentationBase, K.MixAugmentationBaseV2)):- is_same_on_batch = getattr(module, "same_on_batch", False)+ # RandomCutMixV2 pairs the images of a batch with each other, so it needs one draw per video, or per+ # frame with same_on_frame=False (same_on_batch is applied by its own generator), never a shared one.+ is_cutmix = isinstance(module, K.RandomCutMixV2)+ is_same_on_batch = getattr(module, "same_on_batch", False) and not is_cutmixif self.same_on_frame and is_same_on_batch:mod_shape = torch.Size([1, *batch_shape[1:]])@@ -270,7 +302,10 @@ class VideoSequential(ImageSequential):mod_param = module.forward_parameters(mod_shape)- if isinstance(mod_param, dict):+ if isinstance(mod_param, dict) and self.same_on_frame and is_cutmix:+ self._record_video_batch_size(mod_param, original_batch_size)+ self._broadcast_cutmix_params(mod_param, frame_num)+ elif isinstance(mod_param, dict):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.diff --git a/tests/augmentation/container/test_video_sequential.py b/tests/augmentation/container/test_video_sequential.pyindex b460cc8ec..8f7c760a8 100644--- a/tests/augmentation/container/test_video_sequential.py+++ b/tests/augmentation/container/test_video_sequential.py@@ -261,3 +261,133 @@ class TestVideoSequential:boxes = torch.rand(0, 3, 2, 4, 2, device=device, dtype=dtype)assert aug.transform_boxes(boxes, params).shape == boxes.shapeassert aug.inverse_boxes(boxes, params).shape == boxes.shape++ @staticmethod+ def _tagged_video(batch_size, frame_num, data_format, device, dtype):+ """Build a video whose pixel value is ``10 * (video + 1) + frame``.++ Every pixel then names the video and the frame it came from, so a mixed output can be decoded back into+ the donor video and donor frame of each pixel.+ """+ video = 10.0 * (torch.arange(batch_size, device=device, dtype=dtype) + 1)[:, None] + torch.arange(+ frame_num, device=device, dtype=dtype+ )+ video = video[:, :, None, None, None].expand(batch_size, frame_num, 3, 8, 8).contiguous()+ return video.transpose(1, 2).contiguous() if data_format == "BCTHW" else video++ @pytest.mark.parametrize("data_format", ["BCTHW", "BTCHW"])+ @pytest.mark.parametrize("random_apply", [False, 1])+ @pytest.mark.parametrize("num_mix", [1, 2])+ @pytest.mark.parametrize("same_on_batch", [False, True])+ def test_cutmix_same_on_frame_shares_box_and_partner(+ self, data_format, random_apply, num_mix, same_on_batch, device, dtype+ ):+ # RandomCutMixV2 draws (num_mix, B, ...) parameters, so the frame repeat must not touch the mix axis.+ batch_size, frame_num = 4, 3+ aug = K.VideoSequential(+ K.RandomCutMixV2(num_mix=num_mix, p=1.0, same_on_batch=same_on_batch, use_correct_lambda=True),+ data_format=data_format,+ same_on_frame=True,+ random_apply=random_apply,+ )+ video = self._tagged_video(batch_size, frame_num, data_format, device, dtype)++ torch.manual_seed(0)+ out = aug(video)+ assert out.shape == video.shape++ out = out.transpose(1, 2) if data_format == "BCTHW" else out # (B, T, C, H, W)+ frame_id = torch.arange(frame_num, device=device, dtype=dtype)[None, :, None, None, None]+ # A frame only ever takes pixels from the same frame index of some video: value = 10 * (donor + 1) + frame.+ donor = (out - frame_id) / 10.0 - 1.0+ assert_close(donor, donor.round())+ # Every frame of a video cuts the same box from the same partner video.+ for frame in range(1, frame_num):+ assert_close(donor[:, frame], donor[:, 0])+ # The cut is not a no-op: at least one video received pixels from another one.+ own = torch.arange(batch_size, device=device, dtype=dtype)[:, None, None, None, None]+ assert (donor != own).any()++ @pytest.mark.parametrize("data_format", ["BCTHW", "BTCHW"])+ @pytest.mark.parametrize("same_on_batch", [False, True])+ @pytest.mark.parametrize("p", [0.0, 1.0])+ def test_cutmix_same_on_frame_with_same_on_batch_and_p(self, data_format, same_on_batch, p, device, dtype):+ aug = K.VideoSequential(+ K.RandomCutMixV2(p=p, same_on_batch=same_on_batch, use_correct_lambda=True),+ data_format=data_format,+ same_on_frame=True,+ )+ video = self._tagged_video(3, 4, data_format, device, dtype)++ out = aug(video)++ assert out.shape == video.shape+ changed = out != video+ if p == 0.0:+ assert not changed.any()+ frame_dim = 2 if data_format == "BCTHW" else 1+ for frame in range(1, 4):+ assert torch.equal(changed.select(frame_dim, frame), changed.select(frame_dim, 0))++ def test_cutmix_video_params_follow_the_flattened_frames(self, device, dtype):+ batch_size, frame_num, num_mix = 3, 4, 2+ aug = K.VideoSequential(+ K.RandomCutMixV2(num_mix=num_mix, p=1.0, use_correct_lambda=True), data_format="BTCHW", same_on_frame=True+ )+ aug(torch.rand(batch_size, frame_num, 3, 8, 8, device=device, dtype=dtype))+ params = aug._params[0].data++ flat = batch_size * frame_num+ assert params["mix_pairs"].shape == (num_mix, flat)+ assert params["crop_src"].shape == (num_mix, flat, 4, 2)+ assert params["image_shape"].shape == (2,)+ assert params["batch_prob"].shape == (flat,)++ pairs = params["mix_pairs"].view(num_mix, batch_size, frame_num)+ boxes = params["crop_src"].view(num_mix, batch_size, frame_num, 4, 2)+ for frame in range(frame_num):+ # Frame t of a video is mixed with frame t of the partner video, in the same box as frame 0.+ assert torch.equal(pairs[..., frame] % frame_num, torch.full_like(pairs[..., frame], frame))+ assert torch.equal(pairs[..., frame] // frame_num, pairs[..., 0] // frame_num)+ assert torch.equal(boxes[:, :, frame], boxes[:, :, 0])++ def test_cutmix_not_same_on_frame_still_runs(self, device, dtype):+ aug = K.VideoSequential(K.RandomCutMixV2(p=1.0, use_correct_lambda=True), same_on_frame=False)+ video = torch.rand(2, 4, 3, 8, 8, device=device, dtype=dtype)+ assert aug(video).shape == video.shape++ @pytest.mark.parametrize("batch_size", [1, 2])+ @pytest.mark.parametrize("frame_num", [1, 4])+ def test_cutmix_default_same_on_frame_replay(self, batch_size, frame_num, device, dtype):+ aug = K.VideoSequential(K.RandomCutMixV2(p=1.0, use_correct_lambda=True))+ video = torch.rand(batch_size, frame_num, 3, 8, 8, device=device, dtype=dtype)+ out = aug(video)++ assert out.shape == video.shape+ assert torch.equal(aug(video, params=aug._params), out)++ @pytest.mark.parametrize("data_format", ["BCTHW", "BTCHW"])+ @pytest.mark.parametrize("num_mix", [1, 2])+ def test_cutmix_not_same_on_frame_with_same_on_batch(self, data_format, num_mix, device, dtype):+ # With same_on_frame=False the B * T frames are one image batch for CutMix, whose own generator applies+ # same_on_batch. One draw per frame index, repeated over the videos, raised IndexError for B > 1.+ batch_size, frame_num = 2, 3+ mix = K.RandomCutMixV2(num_mix=num_mix, p=1.0, same_on_batch=True, use_correct_lambda=True)+ aug = K.VideoSequential(mix, data_format=data_format, same_on_frame=False)+ video = torch.rand(batch_size, frame_num, 3, 8, 8, device=device, dtype=dtype)++ torch.manual_seed(0)+ out = aug(video.transpose(1, 2).contiguous() if data_format == "BCTHW" else video)+ out = out.transpose(1, 2) if data_format == "BCTHW" else out++ torch.manual_seed(0)+ params = mix.forward_parameters(torch.Size((batch_size * frame_num, 3, 8, 8)))+ expected = mix(video.reshape(-1, 3, 8, 8), params=params).reshape(video.shape)+ assert torch.equal(out, expected)++ def test_cutmix_same_on_frame_empty_video_batch(self, device, dtype):+ aug = K.VideoSequential(K.RandomCutMixV2(p=1.0, use_correct_lambda=True))+ video = torch.rand(0, 4, 3, 8, 8, device=device, dtype=dtype)++ assert aug(video).shape == video.shape+ assert aug(video, params=aug._params).shape == video.shape