π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
Fix AugmentationSequential crash with mix-only augmentations (#3424)
Saksham Tiwari745c6f116c6a
diff --git a/kornia/augmentation/container/image.py b/kornia/augmentation/container/image.pyindex 338319407..18228c97a 100644--- a/kornia/augmentation/container/image.py+++ b/kornia/augmentation/container/image.py@@ -188,20 +188,28 @@ class ImageSequential(ImageSequentialBase, ImageModuleForSequentialMixIn):multinomial_weights = self.random_apply_weights.clone()# Mix augmentation can only be applied once per forwardmix_indices = self.get_mix_augmentation_indices(self.named_children())- # kick out the mix augmentations+multinomial_weights[mix_indices] = 0- indices = torch.multinomial(- multinomial_weights,- num_samples,- # enable replacement if non-mix augmentation is less than required- replacement=num_samples > multinomial_weights.sum().item(),- )++ total_weight = multinomial_weights.sum()+ if total_weight == 0:+ indices = torch.tensor([], device=multinomial_weights.device, dtype=torch.long)+ else:+ indices = torch.multinomial(+ multinomial_weights,+ num_samples,+ replacement=num_samples > total_weight.item(),+ )mix_added = Falseif with_mix and len(mix_indices) != 0:# Make the selection fair.if (torch.rand(1) < ((len(mix_indices) + len(indices)) / len(self))).item():- indices[-1] = torch.multinomial((~multinomial_weights.bool()).float(), 1)+ mix_idx = torch.multinomial((~multinomial_weights.bool()).float(), 1)+ if len(indices) == 0:+ indices = mix_idx+ else:+ indices[-1] = mix_idxindices = indices[torch.randperm(len(indices))]mix_added = Truediff --git a/tests/augmentation/container/test_augmentation_sequential.py b/tests/augmentation/container/test_augmentation_sequential.pyindex 462e4ff38..f23acf6a0 100644--- a/tests/augmentation/container/test_augmentation_sequential.py+++ b/tests/augmentation/container/test_augmentation_sequential.py@@ -59,6 +59,22 @@ class TestAugmentationSequential:assert out.shape[-3:] == inp.shape[-3:]reproducibility_test(inp, aug)+ def test_mixup_cutmix_only(self, device, dtype):+ mixup = K.RandomMixUpV2(p=1.0, data_keys=["input"])+ cutmix = K.RandomCutMixV2(p=1.0, data_keys=["input"])+ aug = K.AugmentationSequential(+ mixup,+ cutmix,+ data_keys=["input"],+ random_apply=1,+ )++ input = torch.randn(2, 3, 224, 224, device=device, dtype=dtype)++ out_input = aug(input)++ assert out_input.shape == input.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(