Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

fix(augmentation): restore call-time data keys after exceptions (#5149)

NiteeshGowda72b0226181ff50
diff --git a/changelog.d/5149.fixed.md b/changelog.d/5149.fixed.md
new file mode 100644
index 000000000..54ffa0ac6
--- /dev/null
+++ b/changelog.d/5149.fixed.md
@@ -0,0 +1,4 @@
+Call-time `data_keys` passed to `AugmentationSequential.forward` or `.inverse` now apply to that call only. A call
+that raised, and an `inverse` call that succeeded, used to leave its keys as the container's default, so a later
+call without `data_keys` raised on an argument-count mismatch or sent each input through another key's handler.
+(#5136)
diff --git a/kornia/augmentation/container/augment.py b/kornia/augmentation/container/augment.py
index 3beab1c14..058afbac7 100644
--- a/kornia/augmentation/container/augment.py
+++ b/kornia/augmentation/container/augment.py
@@ -398,32 +398,36 @@ class AugmentationSequential(TransformMatrixMinIn, ImageSequential):
# NOTE: how to right type to: unpacked args <-> tuple of args to unpack
# issue with `self._preproc_dict_data` return args type
+ original_data_keys = self.transform_op.data_keys
self.transform_op.data_keys = self.transform_op.preproc_datakeys(data_keys)
- self._validate_args_datakeys(*args, data_keys=self.transform_op.data_keys) # type: ignore
+ try:
+ self._validate_args_datakeys(*args, data_keys=self.transform_op.data_keys) # type: ignore
- in_args = self._arguments_preproc(*args, data_keys=self.transform_op.data_keys) # 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
+ 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
- outputs: List[DataType] = in_args
- for param in params[::-1]:
- module = self.get_submodule(param.name)
- 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
- outputs = [outputs]
+ outputs: List[DataType] = in_args
+ for param in params[::-1]:
+ module = self.get_submodule(param.name)
+ 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
+ outputs = [outputs]
- outputs = self._arguments_postproc(args, outputs, data_keys=self.transform_op.data_keys) # type: ignore
+ outputs = self._arguments_postproc(args, outputs, data_keys=self.transform_op.data_keys) # type: ignore
+ finally:
+ self.transform_op.data_keys = original_data_keys
if isinstance(original_keys, tuple):
result = {k: v for v, k in zip(outputs, original_keys)}
if invalid_data:
@@ -550,64 +554,62 @@ class AugmentationSequential(TransformMatrixMinIn, ImageSequential):
original_data_keys = self.transform_op.preproc_datakeys(data_keys)
self.transform_op.data_keys = original_data_keys
- self._validate_args_datakeys(*args, data_keys=original_data_keys)
-
- in_args = self._arguments_preproc(*args, data_keys=original_data_keys)
-
- # 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.
- input_first_order = list(range(len(original_data_keys)))
- if DataKey.INPUT in original_data_keys:
- image_index = original_data_keys.index(DataKey.INPUT)
- input_first_order.insert(0, input_first_order.pop(image_index))
- in_args = [in_args[i] for i in input_first_order]
- self.transform_op.data_keys = [original_data_keys[i] for i in input_first_order]
-
- if DataKey.INPUT in original_data_keys:
- inp = in_args[0]
- if not isinstance(inp, torch.Tensor):
- raise ValueError(f"`INPUT` should be a torch.Tensor but `{type(inp)}` received.")
- if self.contains_3d_augmentation and len(inp.shape) == 4:
- raise RuntimeError(
- f"3D augmentations in AugmentationSequential expect input shape "
- f"(D, H, W) or (B, C, D, H, W), but got {inp.shape}."
- )
+ try:
+ self._validate_args_datakeys(*args, data_keys=original_data_keys)
+
+ in_args = self._arguments_preproc(*args, data_keys=original_data_keys)
+
+ # 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.
+ input_first_order = list(range(len(original_data_keys)))
+ if DataKey.INPUT in original_data_keys:
+ image_index = original_data_keys.index(DataKey.INPUT)
+ input_first_order.insert(0, input_first_order.pop(image_index))
+ in_args = [in_args[i] for i in input_first_order]
+ self.transform_op.data_keys = [original_data_keys[i] for i in input_first_order]
- if params is None:
- # image data must exist if params is not provided.
if DataKey.INPUT in original_data_keys:
inp = in_args[0]
- # A video input shall be BCDHW while an image input shall be BCHW
- if self.contains_video_sequential:
- _, out_shape = self.autofill_dim(inp, dim_range=(3, 5))
- elif self.contains_3d_augmentation:
- _, out_shape = self.autofill_dim(inp, dim_range=(3, 5))
+ if not isinstance(inp, torch.Tensor):
+ raise ValueError(f"`INPUT` should be a torch.Tensor but `{type(inp)}` received.")
+ if self.contains_3d_augmentation and len(inp.shape) == 4:
+ raise RuntimeError(
+ f"3D augmentations in AugmentationSequential expect input shape "
+ f"(D, H, W) or (B, C, D, H, W), but got {inp.shape}."
+ )
+
+ if params is None:
+ # image data must exist if params is not provided.
+ if DataKey.INPUT in original_data_keys:
+ inp = in_args[0]
+ # A video input shall be BCDHW while an image input shall be BCHW
+ if self.contains_video_sequential:
+ _, out_shape = self.autofill_dim(inp, dim_range=(3, 5))
+ elif self.contains_3d_augmentation:
+ _, out_shape = self.autofill_dim(inp, dim_range=(3, 5))
+ else:
+ _, out_shape = self.autofill_dim(inp, dim_range=(2, 4))
+ params = self.forward_parameters(out_shape)
else:
- _, out_shape = self.autofill_dim(inp, dim_range=(2, 4))
- params = self.forward_parameters(out_shape)
- else:
- raise ValueError("`params` must be provided whilst INPUT is not in data_keys.")
-
- outputs: Union[torch.Tensor, List[DataType]] = in_args
- for param in params:
- module = self.get_submodule(param.name)
- outputs = self.transform_op.transform( # 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
- outputs = [outputs]
- self._update_transform_matrix_by_module(module)
-
- if input_first_order != list(range(len(input_first_order))):
- restore_order = [input_first_order.index(i) for i in range(len(input_first_order))]
- outputs = [outputs[i] for i in restore_order]
- self.transform_op.data_keys = original_data_keys
-
- outputs = self._arguments_postproc(args, outputs, data_keys=original_data_keys) # type: ignore
- # Restore it back
- self.transform_op.data_keys = self.data_keys
-
+ raise ValueError("`params` must be provided whilst INPUT is not in data_keys.")
+
+ outputs: Union[torch.Tensor, List[DataType]] = in_args
+ 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
+ outputs = [outputs]
+ self._update_transform_matrix_by_module(module)
+
+ if input_first_order != list(range(len(input_first_order))):
+ restore_order = [input_first_order.index(i) for i in range(len(input_first_order))]
+ outputs = [outputs[i] for i in restore_order]
+ self.transform_op.data_keys = original_data_keys
+
+ outputs = self._arguments_postproc(args, outputs, data_keys=original_data_keys) # type: ignore
+ finally:
+ self.transform_op.data_keys = self.data_keys
if not is_exporting():
self._params = params
diff --git a/tests/augmentation/container/test_augmentation_sequential.py b/tests/augmentation/container/test_augmentation_sequential.py
index 44f132920..036a79bd7 100644
--- a/tests/augmentation/container/test_augmentation_sequential.py
+++ b/tests/augmentation/container/test_augmentation_sequential.py
@@ -100,6 +100,58 @@ class TestAugmentationSequential:
assert out_input.shape == input.shape
+ 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)
+
+ aug = K.AugmentationSequential(
+ K.RandomThinPlateSpline(p=1.0),
+ data_keys=["input"],
+ )
+
+ with pytest.raises(NotImplementedError):
+ aug(image, mask, data_keys=["input", "mask"])
+
+ assert aug.transform_op.data_keys == aug.data_keys
+
+ # A later call without call-time data_keys must use the container defaults.
+ out = aug(image)
+ assert out.shape == image.shape
+
+ def test_call_time_data_keys_are_restored_after_inverse_exception(self, device, dtype):
+ image = torch.rand(1, 1, 4, 8, 8, device=device, dtype=dtype)
+ class_label = torch.tensor([1], device=device)
+
+ aug = K.AugmentationSequential(
+ K.RandomHorizontalFlip3D(p=1.0),
+ data_keys=["input"],
+ )
+
+ outputs = aug(image, class_label, data_keys=["input", "class"])
+
+ with pytest.raises(NotImplementedError, match="3d inverse"):
+ aug.inverse(*outputs, data_keys=["input", "class"])
+
+ assert aug.transform_op.data_keys == aug.data_keys
+
+ # The next keyless call must still use the container defaults.
+ out = aug(image)
+ assert out.shape == image.shape
+
+ def test_call_time_data_keys_are_restored_after_successful_inverse(self, device, dtype):
+ # A successful ``inverse`` with call-time keys must not leave them behind either (#5136).
+ image = torch.rand(1, 3, 8, 10, device=device, dtype=dtype)
+ mask = torch.ones(1, 1, 8, 10, device=device, dtype=dtype)
+
+ aug = K.AugmentationSequential(K.RandomHorizontalFlip(p=1.0), data_keys=["input"])
+
+ out_image, out_mask = aug(image, mask, data_keys=["input", "mask"])
+ aug.inverse(out_image, out_mask, data_keys=["input", "mask"])
+
+ assert aug.transform_op.data_keys == aug.data_keys
+ out = aug(image)
+ assert out.shape == image.shape
+
def test_video(self, device, dtype):
input = torch.randn(2, 3, 5, 6, device=device, dtype=dtype)[None]
bbox = torch.tensor([[[1.0, 1.0], [2.0, 1.0], [2.0, 2.0], [1.0, 2.0]]], device=device, dtype=dtype).expand(