π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
fix(augmentation): track the image shape of a PatchSequential nested in another container (#5588)
εΊζ’η4cb3d3fdd1f5
diff --git a/changelog.d/5588.fixed.md b/changelog.d/5588.fixed.mdnew file mode 100644index 000000000..6a6827380--- /dev/null+++ b/changelog.d/5588.fixed.md@@ -0,0 +1,6 @@+`ImageSequential`, `AugmentationSequential` and `VideoSequential` now accept a nested `PatchSequential` (#5584).+Previously the parent's shape tracking read the nested container's `PatchParamItem` entries as `ParamItem` and raised+`AttributeError: 'PatchParamItem' object has no attribute 'data'` for every `PatchSequential` child, with and without+`patchwise_apply`. The image shape tracked after the nested container is now its input shape, cropped to a multiple of+the grid size for `padding="valid"`, so a size-dependent sibling such as `RandomCrop` draws its parameters for the image+it receives.diff --git a/kornia/augmentation/container/image.py b/kornia/augmentation/container/image.pyindex e7c7e3312..259ba7620 100644--- a/kornia/augmentation/container/image.py+++ b/kornia/augmentation/container/image.py@@ -29,7 +29,7 @@ from kornia.core.ops import eye_likefrom kornia.core.utils import is_exportingfrom .base import ImageSequentialBase-from .params import ParamItem+from .params import ParamItem, PatchParamItem__all__ = ["ImageSequential"]@@ -480,6 +480,17 @@ def _get_new_batch_shape(param: ParamItem, batch_shape: torch.Size, module: Opti# 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":+ rows, columns = module.grid_size+ new_batch_shape = list(batch_shape)+ new_batch_shape[-2] -= new_batch_shape[-2] % rows+ new_batch_shape[-1] -= new_batch_shape[-1] % columns+ return torch.Size(new_batch_shape)+ return batch_shapefor p in data:batch_shape = _get_new_batch_shape(p, batch_shape)return batch_shapediff --git a/kornia/augmentation/container/video.py b/kornia/augmentation/container/video.pyindex 0d70691a2..2b9fefae0 100644--- a/kornia/augmentation/container/video.py+++ b/kornia/augmentation/container/video.py@@ -264,7 +264,7 @@ class VideoSequential(ImageSequential):else:param = ParamItem(name, None)- batch_shape = _get_new_batch_shape(param, batch_shape)+ batch_shape = _get_new_batch_shape(param, batch_shape, module)params.append(param)return paramsdiff --git a/tests/augmentation/container/test_patch_sequential.py b/tests/augmentation/container/test_patch_sequential.pyindex db7376b4b..1eaf8be21 100644--- a/tests/augmentation/container/test_patch_sequential.py+++ b/tests/augmentation/container/test_patch_sequential.py@@ -436,6 +436,62 @@ class TestPatchSequentialRegression(BaseTester):params = seq._paramsself.gradcheck(lambda value: seq(value, params=params), (x.requires_grad_(),))+ @pytest.mark.parametrize("container", [K.ImageSequential, K.AugmentationSequential])+ def test_nested_in_a_container_5584(self, container, device, dtype):+ # The parent reads the nested PatchSequential's PatchParamItem list while tracking the image shape; it used+ # to treat the items as ParamItem and raise AttributeError. A patch sequential does not change the image+ # size, so the sibling after it draws its crop for the full image.+ x = torch.arange(2 * 3 * 8 * 8, device=device).to(dtype).reshape(2, 3, 8, 8) / 384+ inner = K.PatchSequential(K.RandomInvert(p=1.0), grid_size=(2, 2), patchwise_apply=False)+ seq = container(inner, K.RandomCrop((6, 6), p=1.0))+ params = seq.forward_parameters(x.shape)+ assert params[1].data["input_size"][0].tolist() == [8, 8]+ out = seq(x, params=params)+ expected = K.RandomCrop((6, 6), p=1.0)(inner(x, params=params[0].data), params=params[1].data)+ self.assert_close(out, expected, rtol=0, atol=0)++ def test_nested_valid_padding_tracks_the_cropped_size_5584(self, device, dtype):+ # padding="valid" crops a 9 x 9 image to 8 x 8 before the patches are taken, and the sibling must see that.+ x = torch.arange(2 * 1 * 9 * 9, device=device).to(dtype).reshape(2, 1, 9, 9)+ inner = K.PatchSequential(+ K.RandomHorizontalFlip(p=1.0), grid_size=(2, 2), padding="valid", patchwise_apply=False+ )+ seq = K.ImageSequential(inner, K.RandomCrop((4, 4), p=1.0))+ params = seq.forward_parameters(x.shape)+ assert params[1].data["input_size"][0].tolist() == [8, 8]+ assert params[1].data["src"].max().item() <= 7+ assert seq(x, params=params).shape == (2, 1, 4, 4)++ def test_nested_in_video_sequential_5584(self, device, dtype):+ x = torch.arange(2 * 3 * 3 * 9 * 9, device=device).to(dtype).reshape(2, 3, 3, 9, 9)+ inner = K.PatchSequential(+ K.RandomHorizontalFlip(p=1.0), grid_size=(2, 2), padding="valid", patchwise_apply=False+ )+ seq = K.VideoSequential(inner, K.RandomCrop((4, 4), p=1.0), same_on_frame=False)+ params = seq.forward_parameters(x.shape)+ assert params[1].data["input_size"][0].tolist() == [8, 8]+ assert seq(x, params=params).shape == (2, 3, 3, 4, 4)++ @pytest.mark.parametrize(+ "children, grid_size, padding, image_size, tracked",+ [+ # a child resizing each 4 x 4 patch to 4 x 4 reports output_size 4 x 4; the image stays 8 x 8+ (lambda: [K.RandomResizedCrop((4, 4), p=1.0)], (2, 2), "same", (8, 8), [8, 8]),+ # a non-square grid crops the rows and the columns by their own remainders: 9 x 10 becomes 8 x 9+ (lambda: [K.RandomHorizontalFlip(p=1.0)], (2, 3), "valid", (9, 10), [8, 9]),+ # an empty patch sequential hands the parent an empty parameter list+ (list, (2, 2), "same", (8, 8), [8, 8]),+ ],+ ids=["patch_size_child", "non_square_valid", "no_children"],+ )+ def test_nested_tracks_the_image_shape_5584(self, children, grid_size, padding, image_size, tracked, device, dtype):+ inner = K.PatchSequential(*children(), grid_size=grid_size, padding=padding, patchwise_apply=False)+ seq = K.ImageSequential(inner, K.RandomCrop((2, 2), p=1.0))+ x = torch.zeros(2, 1, *image_size, device=device, dtype=dtype)+ params = seq.forward_parameters(x.shape)+ assert params[1].data["input_size"][0].tolist() == tracked+ assert seq(x, params=params).shape == (2, 1, 2, 2)+@pytest.mark.usefixtures("restore_torch_rng")class TestConventionPatchSequential(BaseTester):