π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
fix(augmentation): process input before annotations (#5130)
Karnajeet Gosavi82f48924c272
diff --git a/changelog.d/5130.fixed.md b/changelog.d/5130.fixed.mdnew file mode 100644index 000000000..c29c6b700--- /dev/null+++ b/changelog.d/5130.fixed.md@@ -0,0 +1 @@+`AugmentationSequential` now processes `input` before annotations so nested geometric augmentations and auto-augment policies use the current call's transformation matrix, regardless of caller argument order.diff --git a/kornia/augmentation/container/augment.py b/kornia/augmentation/container/augment.pyindex 2cc404938..0e211c5aa 100644--- a/kornia/augmentation/container/augment.py+++ b/kornia/augmentation/container/augment.py@@ -545,14 +545,24 @@ class AugmentationSequential(TransformMatrixMinIn, ImageSequential):if len(args) == 1 and isinstance(args[0], dict):original_keys, data_keys, args, invalid_data = self._preproc_dict_data(cast(Dict[str, DataType], args[0]))- self.transform_op.data_keys = self.transform_op.preproc_datakeys(data_keys)+ 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=self.transform_op.data_keys) # type: ignore+ self._validate_args_datakeys(*args, data_keys=original_data_keys)- in_args = self._arguments_preproc(*args, data_keys=self.transform_op.data_keys) # type: ignore+ in_args = self._arguments_preproc(*args, data_keys=original_data_keys)- if DataKey.INPUT in self.transform_op.data_keys:- inp = in_args[self.transform_op.data_keys.index(DataKey.INPUT)]+ # 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:@@ -563,8 +573,8 @@ class AugmentationSequential(TransformMatrixMinIn, ImageSequential):if params is None:# image data must exist if params is not provided.- if DataKey.INPUT in self.transform_op.data_keys:- inp = in_args[self.transform_op.data_keys.index(DataKey.INPUT)]+ if DataKey.INPUT in original_data_keys:+ inp = in_args[0]# A video input shall be BCDHW while an image input shall be BCHWif self.contains_video_sequential:_, out_shape = self.autofill_dim(inp, dim_range=(3, 5))@@ -587,7 +597,12 @@ class AugmentationSequential(TransformMatrixMinIn, ImageSequential):outputs = [outputs]self._update_transform_matrix_by_module(module)- outputs = self._arguments_postproc(args, outputs, data_keys=self.transform_op.data_keys) # type: ignore+ 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 backself.transform_op.data_keys = self.data_keysdiff --git a/tests/augmentation/test_base.py b/tests/augmentation/test_base.pyindex 2596c9274..90bbc1221 100644--- a/tests/augmentation/test_base.py+++ b/tests/augmentation/test_base.py@@ -888,6 +888,44 @@ class TestConventionAugmentationBase2D(BaseTester):self.assert_close(output_image, expected_image)self.assert_close(output, expected)+ def test_convention_container_transforms_image_first_for_nested_geometric_child(self, device, dtype):+ image = torch.linspace(0, 1, 2 * 3 * 16 * 20, device=device, dtype=dtype).reshape(2, 3, 16, 20)+ keypoints = torch.tensor([[[3.0, 4.0], [10.0, 6.0]], [[5.0, 5.0], [15.0, 12.0]]], device=device, dtype=dtype)+ reference = K.AugmentationSequential(RandomAffine(30.0, p=1.0))+ sequence = K.AugmentationSequential(K.ImageSequential(RandomAffine(30.0, p=1.0)))++ # A fresh nested child used to raise because its matrix was not recorded yet.+ torch.manual_seed(1)+ expected_image, expected_keypoints = reference(image, keypoints, data_keys=["input", "keypoints"])+ torch.manual_seed(1)+ output_keypoints, output_image = sequence(keypoints, image, data_keys=["keypoints", "input"])+ self.assert_close(output_image, expected_image)+ self.assert_close(output_keypoints, expected_keypoints)++ # A prior call used to leave a matrix behind and silently apply that matrix to later calls.+ sequence(image, keypoints, data_keys=["input", "keypoints"])+ for seed in range(2, 6):+ torch.manual_seed(seed)+ expected_image, expected_keypoints = reference(image, keypoints, data_keys=["input", "keypoints"])+ torch.manual_seed(seed)+ output_keypoints, output_image = sequence(keypoints, image, data_keys=["keypoints", "input"])+ self.assert_close(output_image, expected_image)+ self.assert_close(output_keypoints, expected_keypoints)++ def test_convention_container_transforms_image_first_for_auto_policy(self, device, dtype):+ image = torch.linspace(0, 1, 2 * 3 * 16 * 20, device=device, dtype=dtype).reshape(2, 3, 16, 20)+ keypoints = torch.tensor([[[3.0, 4.0], [10.0, 6.0]], [[5.0, 5.0], [15.0, 12.0]]], device=device, dtype=dtype)+ reference = K.AugmentationSequential(K.auto.TrivialAugment())+ sequence = K.AugmentationSequential(K.auto.TrivialAugment())+ sequence(image, keypoints, data_keys=["input", "keypoints"])+ for seed in (2, 4):+ torch.manual_seed(seed)+ expected_image, expected_keypoints = reference(image, keypoints, data_keys=["input", "keypoints"])+ torch.manual_seed(seed)+ output_keypoints, output_image = sequence(keypoints, image, data_keys=["keypoints", "input"])+ self.assert_close(output_image, expected_image)+ self.assert_close(output_keypoints, expected_keypoints)+@pytest.mark.parametrize("p", [0.0, 1.0])def test_convention_intensity_annotation_overrides_in_container_5113(self, device, dtype, p):class Blackout(K.IntensityAugmentationBase2D):