π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
fix(augmentation): track shapes through nested containers (#5603)
Arc000007d691916155ca
diff --git a/changelog.d/5603.fixed.md b/changelog.d/5603.fixed.mdnew file mode 100644index 000000000..6e2407047--- /dev/null+++ b/changelog.d/5603.fixed.md@@ -0,0 +1 @@+Nested augmentation containers now track size changes correctly during export, and nested `PatchSequential(padding="valid")` containers track their cropped image shape.diff --git a/kornia/augmentation/container/image.py b/kornia/augmentation/container/image.pyindex 259ba7620..d8c504704 100644--- a/kornia/augmentation/container/image.py+++ b/kornia/augmentation/container/image.py@@ -478,21 +478,29 @@ def _get_new_batch_shape(param: ParamItem, batch_shape: torch.Size, module: Optiif data is None:return batch_shape- # If data is a list, process all subitems (exit early if all subitems are None)- if isinstance(data, list):- if len(data) > 0 and isinstance(data[0], PatchParamItem):- # The parameter list of a PatchSequential. Its children work on patches and write their output back- # into the patch buffer, so they cannot change the image size; only ``padding="valid"`` crops the image- # to a multiple of the grid size. The recursion below has no module and leaves the shape unchanged.- if module is not None and getattr(module, "padding", None) == "valid":+ # PatchSequential changes the image shape through its own padding/cropping, including when it is empty.+ # Its parameters describe operations on individual patches and cannot encode this image-level change.+ if module is not None:+ from .patch import PatchSequential++ if isinstance(module, PatchSequential):+ if module.padding == "valid":+ # Crop the last two dimensions to a multiple of the grid; video containers track 5-D shapes.rows, columns = module.grid_sizenew_batch_shape = list(batch_shape)new_batch_shape[-2] -= new_batch_shape[-2] % rowsnew_batch_shape[-1] -= new_batch_shape[-1] % columnsreturn torch.Size(new_batch_shape)return batch_shape++ # If data is a list, process all subitems (exit early if all subitems are None)+ if isinstance(data, list):+ if data and isinstance(data[0], PatchParamItem):+ # Patch children transform patches in place; their output_size does not change the image size.+ return batch_shape+ children = dict(module.named_children()) if module is not None else {}for p in data:- batch_shape = _get_new_batch_shape(p, batch_shape)+ batch_shape = _get_new_batch_shape(p, batch_shape, children.get(p.name))return batch_shape# Carefully avoid evaluating expression multiple times; batch_prob is often a 1-element torch.Tensordiff --git a/tests/augmentation/container/test_patch_sequential.py b/tests/augmentation/container/test_patch_sequential.pyindex 1eaf8be21..25d62c0e2 100644--- a/tests/augmentation/container/test_patch_sequential.py+++ b/tests/augmentation/container/test_patch_sequential.py@@ -169,6 +169,38 @@ class TestPatchSequentialRegression(BaseTester):expected[..., rows, cols] = x[..., rows, cols].flip(-1)self.assert_close(seq(x), expected, rtol=0, atol=0)+ @pytest.mark.parametrize("empty", [False, True])+ @pytest.mark.parametrize("grid,image_size,tracked_size", [((2, 2), (9, 9), (8, 8)), ((2, 3), (9, 10), (8, 9))])+ def test_nested_valid_padding_updates_tracked_shape_5596(self, empty, grid, image_size, tracked_size):+ patch_seq = K.PatchSequential(+ *([] if empty else [K.RandomHorizontalFlip(p=1.0)]),+ grid_size=grid,+ padding="valid",+ patchwise_apply=False,+ )+ seq = K.ImageSequential(K.ImageSequential(patch_seq), K.RandomCrop((4, 4), p=1.0))+ params = seq.forward_parameters(torch.Size((64, 1, *image_size)))+ crop_input_size = params[1].data["input_size"]+ assert torch.equal(crop_input_size, crop_input_size.new_tensor(tracked_size).expand_as(crop_input_size))++ def test_nested_valid_padding_in_a_video_clip_5596(self, device, dtype):+ x = torch.zeros(2, 3, 1, 9, 9, device=device, dtype=dtype)+ inner = K.PatchSequential(+ K.RandomHorizontalFlip(p=1.0), grid_size=(2, 2), padding="valid", patchwise_apply=False+ )+ seq = K.AugmentationSequential(K.VideoSequential(inner, same_on_frame=False))+ assert seq(x).shape == (2, 3, 1, 8, 8)++ def test_patch_child_resize_does_not_change_tracked_image_shape_5596(self):+ patch_seq = K.PatchSequential(K.RandomResizedCrop((4, 4), p=1.0), grid_size=(2, 2), patchwise_apply=False)+ seq = K.VideoSequential(+ patch_seq,+ K.RandomCrop((2, 2), p=1.0),+ same_on_frame=False,+ )+ params = seq.forward_parameters(torch.Size((2, 3, 1, 8, 8)))+ assert params[1].data["input_size"][0].tolist() == [8, 8]+@pytest.mark.parametrize("same_on_batch", [True, False, None])def test_location_wise_modules_cover_every_sample(self, same_on_batch, device, dtype):seq = K.PatchSequential(diff --git a/tests/augmentation/test_torch_export.py b/tests/augmentation/test_torch_export.pyindex daf731515..b5690e875 100644--- a/tests/augmentation/test_torch_export.py+++ b/tests/augmentation/test_torch_export.py@@ -113,11 +113,20 @@ def _seq_resize_then_resample_crop() -> torch.nn.Module:return K.AugmentationSequential(K.Resize((16, 16)), K.CenterCrop(8, cropping_mode="resample"), data_keys=["input"])+def _seq_nested_resize_then_resample_crop() -> torch.nn.Module:+ return K.AugmentationSequential(+ K.ImageSequential(K.Resize((16, 16))),+ K.CenterCrop(8, cropping_mode="resample"),+ data_keys=["input"],+ )++TORCH_EXPORT_CONTAINERS: list[Tuple[str, Callable[[], torch.nn.Module]]] = [("Seq[Norm,Bright]", _seq_pointwise),("Seq[Norm,Resize]", _seq_resize),("Seq[Norm,CenterCrop,PadTo]", _seq_crop_pad),("Seq[Resize,CenterCrop-resample]", _seq_resize_then_resample_crop),+ ("Seq[NestedResize,CenterCrop-resample]", _seq_nested_resize_then_resample_crop),]