π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
Fixed non-4-dim input error for sequential (#1146)
Jian Shi94920cdd25ff
diff --git a/kornia/augmentation/container/augment.py b/kornia/augmentation/container/augment.pyindex 168519727..9b2593099 100644--- a/kornia/augmentation/container/augment.py+++ b/kornia/augmentation/container/augment.py@@ -320,9 +320,12 @@ class AugmentationSequential(ImageSequential):if DataKey.INPUT in data_keys:_input = args[data_keys.index(DataKey.INPUT)]if isinstance(_input, (tuple, list)):- params = self.forward_parameters(_input[0].shape)+ inp = _input[0]else:- params = self.forward_parameters(_input.shape)+ inp = _input+ _, out_shape = self.autofill_dim(inp, dim_range=(2, 4))+ if params is None:+ params = self.forward_parameters(out_shape)else:raise ValueError("`params` must be provided whilst INPUT is not in data_keys.")diff --git a/kornia/augmentation/container/base.py b/kornia/augmentation/container/base.pyindex 27eaef808..c06915a4a 100644--- a/kornia/augmentation/container/base.py+++ b/kornia/augmentation/container/base.py@@ -159,3 +159,15 @@ class SequentialBase(nn.Sequential):def contains_label_operations(self, params: List) -> bool:raise NotImplementedError++ def autofill_dim(self, input: torch.Tensor, dim_range: Tuple[int, int] = (2, 4)) -> Tuple[torch.Size, torch.Size]:+ """Fill tensor dim to the upper bound of dim_range.++ If input tensor dim is smaller than the lower bound of dim_range, an error will be thrown out.+ """+ ori_shape = input.shape+ if len(ori_shape) < dim_range[0] or len(ori_shape) > dim_range[1]:+ raise RuntimeError(f"input shape expected to be in {dim_range} while got {ori_shape}.")+ while len(input.shape) < dim_range[1]:+ input = input[None]+ return ori_shape, input.shapediff --git a/kornia/augmentation/container/image.py b/kornia/augmentation/container/image.pyindex 305284ccf..835acda4e 100644--- a/kornia/augmentation/container/image.py+++ b/kornia/augmentation/container/image.py@@ -166,7 +166,13 @@ class ImageSequential(SequentialBase):module = self.get_submodule(param.name)if isinstance(module, (MixAugmentationBase,)):input, label = module(input, label, params=param.data)- elif isinstance(module, (_AugmentationBase, ImageSequential)):+ elif isinstance(module, (ImageSequential,)):+ out = module(input, label, params=param.data)+ if module.return_label:+ input, label = out+ else:+ input = out+ elif isinstance(module, (_AugmentationBase,)):input = module(input, params=param.data)else:assert param.data is None, f"Non-augmentaion operation {param.name} require empty parameters. Got {param}."@@ -213,9 +219,11 @@ class ImageSequential(SequentialBase):self.clear_state()if params is None:if isinstance(input, (tuple, list)):- params = self.forward_parameters(input[0].shape)+ inp = input[0]else:- params = self.forward_parameters(input.shape)+ inp = input+ _, out_shape = self.autofill_dim(inp, dim_range=(2, 4))+ params = self.forward_parameters(out_shape)self.return_label = label is not None or self.contains_label_operations(params)for param in params:module = self.get_submodule(param.name)diff --git a/kornia/augmentation/container/patch.py b/kornia/augmentation/container/patch.pyindex a72d977a3..a257a8318 100644--- a/kornia/augmentation/container/patch.py+++ b/kornia/augmentation/container/patch.py@@ -265,6 +265,12 @@ class PatchSequential(ImageSequential):yield ParamItem(s[0], s[1].forward_parameters(batch_shape[1:])), ielse:yield ParamItem(s[0], None), i+ elif not self.same_on_batch and not self.random_apply:+ for i, nchild in enumerate(self.named_children()):+ if isinstance(nchild[1], (_AugmentationBase, MixAugmentationBase, SequentialBase)):+ yield ParamItem(nchild[0], nchild[1].forward_parameters(batch_shape[1:])), i+ else:+ yield ParamItem(nchild[0], None), ielif not self.random_apply:# same_on_batch + not random_apply => location-wise augmentationfor i, nchild in enumerate(islice(cycle(self.named_children()), batch_shape[0])):diff --git a/test/augmentation/test_container.py b/test/augmentation/test_container.pyindex 42c946818..53750c6e8 100644--- a/test/augmentation/test_container.py+++ b/test/augmentation/test_container.py@@ -211,9 +211,11 @@ class TestAugmentationSequential:K.AugmentationSequential(augmentation_list, data_keys=data_keys)@pytest.mark.parametrize('return_transform', [True, False])+ @pytest.mark.parametrize('same_on_batch', [True, False])@pytest.mark.parametrize('random_apply', [1, (2, 2), (1, 2), (2,), 10, True, False])- def test_mixup(self, return_transform, random_apply, device, dtype):- inp = torch.randn(1, 3, 1000, 500, device=device, dtype=dtype)+ @pytest.mark.parametrize('inp', [torch.randn(1, 3, 1000, 500), torch.randn(3, 1000, 500)])+ def test_mixup(self, inp, return_transform, random_apply, same_on_batch, device, dtype):+ inp = torch.as_tensor(inp, device=device, dtype=dtype)aug = K.AugmentationSequential(K.ColorJitter(0.1, 0.1, 0.1, 0.1, p=1.0),K.RandomAffine(360, p=1.0),@@ -221,13 +223,14 @@ class TestAugmentationSequential:data_keys=["input"],random_apply=random_apply,return_transform=return_transform,+ same_on_batch=same_on_batch,)out = aug(inp)if aug.return_label:out, label = outif return_transform and isinstance(out, (tuple, list)):out = out[0]- assert out.shape == inp.shape+ assert out.shape[-3:] == inp.shape[-3:]reproducibility_test(inp, aug)@pytest.mark.parametrize('random_apply', [1, (2, 2), (1, 2), (2,), 10, True, False])