Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

fix: correct same_on_frame and same_on_batch logic in VideoSequential (#3330)

RakshithaKowlikar0ef19f680286
diff --git a/kornia/augmentation/container/video.py b/kornia/augmentation/container/video.py
index d8f5b970b..387e363d5 100644
--- a/kornia/augmentation/container/video.py
+++ b/kornia/augmentation/container/video.py
@@ -157,6 +157,20 @@ class VideoSequential(ImageSequential):
repeated = param[:, None, ...].repeat(1, frame_num, *([1] * len(param.shape[1:])))
return repeated.reshape(-1, *list(param.shape[1:]))
+ def __broadcast_param__(
+ self, v: Tensor, batch_shape: torch.Size, frame_num: int, same_on_frame: bool, same_on_batch: bool
+ ) -> Tensor:
+ if not v.numel():
+ return v
+
+ if same_on_frame and same_on_batch:
+ return v.repeat(batch_shape[0] * frame_num, *([1] * (v.ndim - 1)))
+ elif same_on_frame:
+ return self.__repeat_param_across_channels__(v, frame_num)
+ elif same_on_batch:
+ return v.unsqueeze(1).repeat(1, batch_shape[0], *([1] * (v.ndim - 1))).reshape(-1, *v.shape[1:])
+ return v
+
def _input_shape_convert_in(self, input: Tensor, frame_num: int) -> Tensor:
# Convert any shape to (B, T, C, H, W)
if self.data_format == "BCTHW":
@@ -183,39 +197,48 @@ class VideoSequential(ImageSequential):
# Got param generation shape to (B, C, H, W). Ignoring T.
batch_shape = self.__infer_channel_exclusive_batch_shape__(batch_shape, self._temporal_channel)
- if not self.same_on_frame:
- # Overwrite param generation shape to (B * T, C, H, W).
- batch_shape = torch.Size([batch_shape[0] * frame_num, *batch_shape[1:]])
-
params = []
for name, module in named_modules:
- if isinstance(module, K.RandomCrop):
- mod_param = module.forward_parameters(batch_shape)
- if self.same_on_frame:
- mod_param["src"] = mod_param["src"].repeat(frame_num, 1, 1)
- mod_param["dst"] = mod_param["dst"].repeat(frame_num, 1, 1)
- param = ParamItem(name, mod_param)
- elif isinstance(module, (SequentialBase,)):
- seq_param = module.forward_parameters(batch_shape)
- if self.same_on_frame:
- raise ValueError("Sequential is currently unsupported for ``same_on_frame``.")
- param = ParamItem(name, seq_param)
- elif isinstance(module, (_AugmentationBase, K.MixAugmentationBaseV2)):
- mod_param = module.forward_parameters(batch_shape)
- if self.same_on_frame:
+ if isinstance(module, (K.RandomCrop, _AugmentationBase, K.MixAugmentationBaseV2)):
+ is_same_on_batch = getattr(module, "same_on_batch", False)
+
+ if self.same_on_frame and is_same_on_batch:
+ mod_shape = torch.Size([1, *batch_shape[1:]])
+ elif self.same_on_frame:
+ mod_shape = batch_shape
+ elif is_same_on_batch:
+ mod_shape = torch.Size([frame_num, *batch_shape[1:]])
+ else:
+ mod_shape = torch.Size([batch_shape[0] * frame_num, *batch_shape[1:]])
+
+ mod_param = module.forward_parameters(mod_shape)
+
+ if isinstance(mod_param, dict):
for k, v in 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))):
+ if k == "order" and isinstance(module, (K.ColorJiggle, K.ColorJitter)):
continue
if k == "forward_input_shape":
mod_param.update({k: v})
continue
- mod_param.update({k: self.__repeat_param_across_channels__(v, frame_num)})
+ mod_param[k] = self.__broadcast_param__(
+ v, batch_shape, frame_num, self.same_on_frame, is_same_on_batch
+ )
+
param = ParamItem(name, mod_param)
+
+ elif isinstance(module, (SequentialBase,)):
+ seq_param = module.forward_parameters(batch_shape)
+ if self.same_on_frame:
+ raise ValueError("Sequential is currently unsupported for ``same_on_frame``.")
+ param = ParamItem(name, seq_param)
+
else:
param = ParamItem(name, None)
+
batch_shape = _get_new_batch_shape(param, batch_shape)
params.append(param)
+
return params
def transform_inputs(
diff --git a/tests/augmentation/container/test_video_sequential.py b/tests/augmentation/container/test_video_sequential.py
index fc74fe57b..a8736b23b 100644
--- a/tests/augmentation/container/test_video_sequential.py
+++ b/tests/augmentation/container/test_video_sequential.py
@@ -166,3 +166,49 @@ class TestVideoSequential:
output = aug(imgs)
assert output.dtype == dtype, "Output image dtype should match the input dtype"
+
+ @pytest.mark.parametrize("data_format", ["BCTHW", "BTCHW"])
+ @pytest.mark.parametrize(
+ "same_on_frame,same_on_batch",
+ [
+ (True, True),
+ (True, False),
+ (False, True),
+ (False, False),
+ ],
+ )
+ def test_all_frame_and_batch(self, data_format, same_on_frame, same_on_batch, device, dtype):
+ aug = K.VideoSequential(
+ K.RandomCrop(size=(4, 4), p=1.0, same_on_batch=same_on_batch),
+ data_format=data_format,
+ same_on_frame=same_on_frame,
+ )
+
+ if data_format == "BCTHW":
+ if same_on_frame:
+ start = torch.randn(1, 3, 1, 5, 6, device=device, dtype=dtype).repeat(1, 1, 4, 1, 1)
+ x = start.repeat(2, 1, 1, 1, 1)
+ else:
+ start = torch.randn(1, 3, 4, 5, 6, device=device, dtype=dtype)
+ x = start.repeat(2, 1, 1, 1, 1)
+ elif same_on_frame:
+ start = torch.randn(1, 1, 3, 5, 6, device=device, dtype=dtype).repeat(1, 4, 1, 1, 1)
+ x = start.repeat(2, 1, 1, 1, 1)
+ else:
+ start = torch.randn(1, 4, 3, 5, 6, device=device, dtype=dtype)
+ x = start.repeat(2, 1, 1, 1, 1)
+
+ torch.manual_seed(0)
+ y = aug(x)
+
+ if data_format == "BCTHW":
+ same_frame = torch.allclose(y[:, :, 0], y[:, :, 1])
+ same_batch = torch.allclose(y[0, :, 0], y[1, :, 0])
+ else:
+ same_frame = torch.allclose(y[:, 0], y[:, 1])
+ same_batch = torch.allclose(y[0, 0], y[1, 0])
+
+ assert same_frame == same_on_frame
+ assert same_batch == same_on_batch
+
+ reproducibility_test(x, aug)