Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

fix(augmentation): pair matching frames for mixes in VideoSequential (#6154)

Parman Mohammadalizadeh74736c1528e6
diff --git a/changelog.d/6154.fixed.md b/changelog.d/6154.fixed.md
new file mode 100644
index 000000000..45b94111d
--- /dev/null
+++ b/changelog.d/6154.fixed.md
@@ -0,0 +1 @@
+Fixed `VideoSequential` mixing `RandomMixUpV2`, `PatchMix` and `RandomMosaic` with the wrong frames. With `same_on_frame=True` the partner indices drawn per video now point at frame `t` of the partner video, and with `same_on_batch=True`, `RandomMixUpV2` and `PatchMix` draw one sample per video instead of mixing every frame with the first one. With `same_on_frame=False` and `same_on_batch=True` those two are now drawn for all `B * T` frames, instead of once per frame index with every partner taken from the first video.
diff --git a/kornia/augmentation/container/video.py b/kornia/augmentation/container/video.py
index 2ec346671..a5de94ecf 100644
--- a/kornia/augmentation/container/video.py
+++ b/kornia/augmentation/container/video.py
@@ -218,6 +218,27 @@ class VideoSequential(ImageSequential):
# ``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.
+ @staticmethod
+ def _batch_index_param(module: nn.Module) -> Optional[str]:
+ """Name the parameter of a mix augmentation that holds indices into the image batch.
+
+ Along its first axis the parameter has one row per image, and its values index the batch as well. Drawn per
+ video, those values are video indices, which must become indices into the ``B * T`` flattened frames.
+ """
+ if isinstance(module, K.RandomMixUpV2):
+ return "mixup_pairs"
+ if isinstance(module, K.PatchMix):
+ return "mix_pairs"
+ if isinstance(module, K.RandomMosaic):
+ return "permutation"
+ return None
+
+ @staticmethod
+ def _video_to_frame_indices(v: torch.Tensor, frame_num: int) -> torch.Tensor:
+ """Map video indices, already repeated over the frames, to frame ``t`` of each indexed video."""
+ frames = torch.arange(v.shape[0], device=v.device, dtype=v.dtype) % frame_num
+ return v * frame_num + frames.view(-1, *([1] * (v.ndim - 1)))
+
@staticmethod
def _record_video_batch_size(
param: Union[Dict[str, torch.Tensor], List[ParamItem]], original_batch_size: int
@@ -286,10 +307,13 @@ class VideoSequential(ImageSequential):
params = []
for name, module in named_modules:
if isinstance(module, (K.RandomCrop, _AugmentationBase, K.MixAugmentationBaseV2)):
- # 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.
+ batch_index_param = self._batch_index_param(module)
is_cutmix = isinstance(module, K.RandomCutMixV2)
- is_same_on_batch = getattr(module, "same_on_batch", False) and not is_cutmix
+ # A mix pairs the images of a batch with each other, so it needs one draw per video, or per frame with
+ # same_on_frame=False, never a shared one. Its own generator applies same_on_batch.
+ is_same_on_batch = (
+ getattr(module, "same_on_batch", False) and batch_index_param is None and not is_cutmix
+ )
if self.same_on_frame and is_same_on_batch:
mod_shape = torch.Size([1, *batch_shape[1:]])
@@ -319,6 +343,8 @@ class VideoSequential(ImageSequential):
mod_param[k] = self.__broadcast_param__(
v, batch_shape, frame_num, self.same_on_frame, is_same_on_batch
)
+ if self.same_on_frame and k == batch_index_param:
+ mod_param[k] = self._video_to_frame_indices(mod_param[k], frame_num)
elif isinstance(mod_param, list):
self._record_video_batch_size(mod_param, original_batch_size)
diff --git a/tests/augmentation/container/test_video_sequential.py b/tests/augmentation/container/test_video_sequential.py
index 8f7c760a8..5eb88a60e 100644
--- a/tests/augmentation/container/test_video_sequential.py
+++ b/tests/augmentation/container/test_video_sequential.py
@@ -262,6 +262,59 @@ class TestVideoSequential:
assert aug.transform_boxes(boxes, params).shape == boxes.shape
assert aug.inverse_boxes(boxes, params).shape == boxes.shape
+ @pytest.mark.parametrize(
+ "mix",
+ [
+ lambda sob: K.RandomMixUpV2(p=1.0, same_on_batch=sob),
+ lambda sob: K.PatchMix(patch_size=2, p=1.0, same_on_batch=sob),
+ lambda sob: K.RandomMosaic(p=1.0),
+ ],
+ ids=["mixup", "patchmix", "mosaic"],
+ )
+ @pytest.mark.parametrize("same_on_batch", [False, True])
+ @pytest.mark.parametrize("data_format", ["BCTHW", "BTCHW"])
+ def test_mix_same_on_frame_pairs_matching_frames(self, mix, same_on_batch, data_format, device, dtype):
+ batch_size, frame_num = 3, 4
+ aug = mix(same_on_batch)
+ video = torch.rand(batch_size, frame_num, 3, 8, 8, device=device, dtype=dtype)
+ seq = K.VideoSequential(aug, data_format=data_format, same_on_frame=True)
+
+ torch.manual_seed(0)
+ out = seq(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 = aug.forward_parameters(torch.Size((batch_size, 3, 8, 8)))
+ for frame in range(frame_num):
+ assert_close(out[:, frame], aug(video[:, frame], params=params))
+
+ @pytest.mark.parametrize(
+ "mix",
+ [
+ lambda sob: K.RandomMixUpV2(p=1.0, same_on_batch=sob),
+ lambda sob: K.PatchMix(patch_size=2, p=1.0, same_on_batch=sob),
+ lambda sob: K.RandomMosaic(p=1.0),
+ ],
+ ids=["mixup", "patchmix", "mosaic"],
+ )
+ @pytest.mark.parametrize("same_on_batch", [False, True])
+ @pytest.mark.parametrize("data_format", ["BCTHW", "BTCHW"])
+ def test_mix_not_same_on_frame_matches_flattened_frames(self, mix, same_on_batch, data_format, device, dtype):
+ # With same_on_frame=False the B * T frames are one image batch for the mix, whose own generator applies
+ # same_on_batch. One draw per frame index, repeated over the videos, took every partner from the first video.
+ batch_size, frame_num = 3, 4
+ aug = mix(same_on_batch)
+ video = torch.rand(batch_size, frame_num, 3, 8, 8, device=device, dtype=dtype)
+ seq = K.VideoSequential(aug, data_format=data_format, same_on_frame=False)
+
+ torch.manual_seed(0)
+ out = seq(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 = aug.forward_parameters(torch.Size((batch_size * frame_num, 3, 8, 8)))
+ assert_close(out, aug(video.reshape(-1, 3, 8, 8), params=params).reshape(video.shape))
+
@staticmethod
def _tagged_video(batch_size, frame_num, data_format, device, dtype):
"""Build a video whose pixel value is ``10 * (video + 1) + frame``.