π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
fix(augmentation): validate mix inputs before probability gate (#4676)
Puttala Jeevan Kumar3470b2f1abf9
diff --git a/changelog.d/4676.fixed.md b/changelog.d/4676.fixed.mdnew file mode 100644index 000000000..ff03e79eb--- /dev/null+++ b/changelog.d/4676.fixed.md@@ -0,0 +1,2 @@+Mix augmentations now reject unsupported data keys even when no samples are selected.+RandomJigsaw validates that image dimensions are divisible by its grid regardless of the probability gate.diff --git a/kornia/augmentation/_2d/mix/base.py b/kornia/augmentation/_2d/mix/base.pyindex 18e34e504..a16a17349 100644--- a/kornia/augmentation/_2d/mix/base.py+++ b/kornia/augmentation/_2d/mix/base.py@@ -49,6 +49,23 @@ class MixAugmentationBaseV2(_BasicAugmentationBase):"""+ def _validate_data_key(self, key: DataKey) -> None:+ # Check the handler without executing a transform or requiring subclasses to declare support twice.+ if key in (DataKey.BBOX, DataKey.BBOX_XYXY, DataKey.BBOX_XYWH):+ if type(self).apply_transform_boxes is MixAugmentationBaseV2.apply_transform_boxes:+ raise NotImplementedError+ elif key == DataKey.KEYPOINTS:+ if type(self).apply_transform_keypoint is MixAugmentationBaseV2.apply_transform_keypoint:+ raise NotImplementedError+ elif key == DataKey.CLASS:+ if type(self).apply_transform_class is MixAugmentationBaseV2.apply_transform_class:+ raise NotImplementedError+ elif key == DataKey.MASK:+ if type(self).apply_transform_mask is MixAugmentationBaseV2.apply_transform_mask:+ raise NotImplementedError+ elif key != DataKey.INPUT:+ raise NotImplementedError+def __init__(self,p: float,@@ -123,6 +140,7 @@ class MixAugmentationBaseV2(_BasicAugmentationBase):def transform_mask(self, input: torch.Tensor, params: Dict[str, torch.Tensor], flags: Dict[str, Any]) -> torch.Tensor:+ self._validate_data_key(DataKey.MASK)batch_prob = params["batch_prob"]to_apply = torch.atleast_1d(batch_prob > 0.5)output = input@@ -135,6 +153,7 @@ class MixAugmentationBaseV2(_BasicAugmentationBase):def transform_boxes(self, input: Union[torch.Tensor, Boxes], params: Dict[str, torch.Tensor], flags: Dict[str, Any]) -> Boxes:+ self._validate_data_key(DataKey.BBOX)# input is BxNx4x2 or Boxes.if isinstance(input, torch.Tensor):if not (len(input.shape) == 4 and input.shape[2:] == torch.Size([4, 2])):@@ -152,6 +171,7 @@ class MixAugmentationBaseV2(_BasicAugmentationBase):def transform_keypoint(self, input: torch.Tensor, params: Dict[str, torch.Tensor], flags: Dict[str, Any]) -> torch.Tensor:+ self._validate_data_key(DataKey.KEYPOINTS)batch_prob = params["batch_prob"]to_apply = torch.atleast_1d(batch_prob > 0.5)output = input@@ -164,6 +184,7 @@ class MixAugmentationBaseV2(_BasicAugmentationBase):def transform_class(self, input: torch.Tensor, params: Dict[str, torch.Tensor], flags: Dict[str, Any]) -> torch.Tensor:+ self._validate_data_key(DataKey.CLASS)batch_prob = params["batch_prob"]to_apply = torch.atleast_1d(batch_prob > 0.5)output = input@@ -221,6 +242,9 @@ class MixAugmentationBaseV2(_BasicAugmentationBase):else:keys = [DataKey.get(inp) for inp in data_keys]+ for key in keys:+ self._validate_data_key(key)+if params is None:in_tensor_idx: int = keys.index(DataKey.INPUT)in_tensor: torch.Tensor = input[in_tensor_idx]diff --git a/kornia/augmentation/_2d/mix/jigsaw.py b/kornia/augmentation/_2d/mix/jigsaw.pyindex 6c2fdf2c0..29e3d9c17 100644--- a/kornia/augmentation/_2d/mix/jigsaw.py+++ b/kornia/augmentation/_2d/mix/jigsaw.py@@ -69,6 +69,15 @@ class RandomJigsaw(MixAugmentationBaseV2):self._param_generator = rg.JigsawGenerator(grid, ensure_perm)self.flags = {"grid": grid}+ def transform_tensor(+ self, input: torch.Tensor, *, shape: Optional[torch.Tensor] = None, match_channel: bool = True+ ) -> torch.Tensor:+ input = super().transform_tensor(input, shape=shape, match_channel=match_channel)+ h, w = input.shape[-2:]+ if h % self.flags["grid"][0] or w % self.flags["grid"][1]:+ raise RuntimeError(f"Input height and width {(h, w)} must be divisible by grid {self.flags['grid']}.")+ return input+def apply_transform(self, input: torch.Tensor, params: Dict[str, torch.Tensor], maybe_flags: Optional[Dict[str, Any]] = None) -> torch.Tensor:@@ -76,9 +85,6 @@ class RandomJigsaw(MixAugmentationBaseV2):# where-blends this result with the non-transformed branch per `batch_prob`.b, c, h, w = input.shapeperm = params["permutation"]- # Note: with a 100x100 image and a grid size of 3x3, it could work if- # we make h = piece_size_h * self.flags["grid"][0] with one pixel loss, then resize to 100 x 100.- # Probably worth to check if we should tolerate such "errorness" or to raise it as an error.piece_size_h, piece_size_w = input.shape[-2] // self.flags["grid"][0], input.shape[-1] // self.flags["grid"][1]# Convert to C BxN H' W'input = (diff --git a/kornia/augmentation/_2d/mix/mosaic.py b/kornia/augmentation/_2d/mix/mosaic.pyindex b0576106a..9e8101ff0 100644--- a/kornia/augmentation/_2d/mix/mosaic.py+++ b/kornia/augmentation/_2d/mix/mosaic.py@@ -78,6 +78,11 @@ class RandomMosaic(MixAugmentationBaseV2):"""+ def _validate_data_key(self, key: DataKey) -> None:+ if key == DataKey.CLASS and type(self).apply_transform_class is RandomMosaic.apply_transform_class:+ raise RuntimeError(f"{self.__class__.__name__} does not support `TAG` types.")+ super()._validate_data_key(key)+def __init__(self,output_size: Optional[Tuple[int, int]] = None,@@ -106,11 +111,6 @@ class RandomMosaic(MixAugmentationBaseV2):"cropping_mode": cropping_mode,}- def apply_transform_mask(- self, input: torch.Tensor, params: Dict[str, torch.Tensor], flags: Dict[str, Any]- ) -> torch.Tensor:- raise NotImplementedError-@torch.no_grad()def apply_transform_boxes(self, input: Boxes, params: Dict[str, torch.Tensor], flags: Dict[str, Any]) -> Boxes:to_apply = params["batch_prob"] > 0.5@@ -151,11 +151,6 @@ class RandomMosaic(MixAugmentationBaseV2):out_boxes.filter_boxes_by_area(flags["min_bbox_size"], inplace=True)return out_boxes- def apply_transform_keypoint(- self, input: torch.Tensor, params: Dict[str, torch.Tensor], flags: Dict[str, Any]- ) -> torch.Tensor:- raise NotImplementedError-def apply_transform_class(self, input: torch.Tensor, params: Dict[str, torch.Tensor], flags: Dict[str, Any]) -> torch.Tensor:diff --git a/tests/augmentation/test_augmentation_mix.py b/tests/augmentation/test_augmentation_mix.pyindex 9c4467c16..f3c7e1ecb 100644--- a/tests/augmentation/test_augmentation_mix.py+++ b/tests/augmentation/test_augmentation_mix.py@@ -22,6 +22,7 @@ import torchfrom kornia.augmentation import (AugmentationSequential,+ PatchMix,RandomCutMixV2,RandomJigsaw,RandomMixUpV2,@@ -34,6 +35,92 @@ from kornia.geometry.bbox import infer_bbox_shapefrom testing.base import BaseTester+class TestMixValidation(BaseTester):+ @pytest.mark.parametrize("p", [0.0, 1.0])+ def test_custom_annotation_handler(self, p, device, dtype):+ class KeypointMix(RandomMixUpV2):+ def apply_transform_keypoint(self, input, params, flags):+ return input + 1++ image = torch.zeros(2, 1, 8, 8, device=device, dtype=dtype)+ keypoints = image.new_zeros(2, 1, 2)+ _, output = KeypointMix(p=p)(image, keypoints, data_keys=["input", "keypoints"])+ self.assert_close(output, keypoints + p)++ @pytest.mark.parametrize("p", [0.0, 1.0])+ @pytest.mark.parametrize("gate", [None, [0.0, 0.0], [1.0, 0.0]])+ @pytest.mark.parametrize("constructor_keys", [False, True])+ @pytest.mark.parametrize(+ ("augmentation", "kwargs", "keys", "error"),+ [+ (RandomMixUpV2, {}, ["bbox", "bbox_xyxy", "bbox_xywh", "keypoints", "mask"], NotImplementedError),+ (+ RandomCutMixV2,+ {"use_correct_lambda": True},+ ["bbox", "bbox_xyxy", "bbox_xywh", "keypoints", "mask"],+ NotImplementedError,+ ),+ (+ RandomJigsaw,+ {"grid": (2, 2)},+ ["bbox", "bbox_xyxy", "bbox_xywh", "keypoints", "class", "label", "mask"],+ NotImplementedError,+ ),+ (+ PatchMix,+ {"patch_size": 2},+ ["bbox", "bbox_xyxy", "bbox_xywh", "keypoints", "class", "label", "mask"],+ NotImplementedError,+ ),+ (RandomMosaic, {}, ["keypoints", "mask"], NotImplementedError),+ (RandomMosaic, {}, ["class", "label"], RuntimeError),+ ],+ )+ def test_unsupported_keys_4651(self, augmentation, kwargs, keys, error, p, gate, constructor_keys, device, dtype):+ image = torch.zeros(2, 1, 8, 8, device=device, dtype=dtype)+ boxes = image.new_tensor([[[1, 1, 4, 4]]]).repeat(2, 1, 1)+ annotations = {+ "bbox": image.new_tensor([[[[1, 1], [4, 1], [4, 4], [1, 4]]]]).repeat(2, 1, 1, 1),+ "bbox_xyxy": boxes,+ "bbox_xywh": boxes,+ "keypoints": image.new_zeros(2, 1, 2),+ "class": torch.arange(2, device=device),+ "label": torch.arange(2, device=device),+ "mask": torch.zeros_like(image),+ }+ for key in keys:+ data_keys = ["input", key]+ aug = augmentation(p=p, **kwargs, **({"data_keys": data_keys} if constructor_keys else {}))+ params = None+ if gate is not None:+ params = aug.forward_parameters(image.shape)+ params["batch_prob"] = torch.tensor(gate)+ with pytest.raises(error) as exc:+ aug(image, annotations[key], params=params, **({} if constructor_keys else {"data_keys": data_keys}))+ assert type(exc.value) is error+ if error is RuntimeError:+ assert str(exc.value) == "RandomMosaic does not support `TAG` types."++ @pytest.mark.parametrize("key", ["bbox_xyxy", "keypoints", "mask"])+ def test_container_rejects_skipped_unsupported_keys_4651(self, key, device, dtype):+ image = torch.zeros(2, 1, 8, 8, device=device, dtype=dtype)+ annotations = {+ "bbox_xyxy": image.new_tensor([[[1, 1, 4, 4]]]).repeat(2, 1, 1),+ "keypoints": image.new_zeros(2, 1, 2),+ "mask": torch.zeros_like(image),+ }+ aug = AugmentationSequential(RandomMixUpV2(p=0.0), data_keys=["input", key])+ with pytest.raises(NotImplementedError):+ aug(image, annotations[key])++ def test_supported_mosaic_boxes_skipped(self, device, dtype):+ image = torch.arange(128, device=device, dtype=dtype).reshape(2, 1, 8, 8)+ boxes = image.new_tensor([[[1, 1, 4, 4]]]).repeat(2, 1, 1)+ output, output_boxes = RandomMosaic(p=0.0)(image, boxes, data_keys=["input", "bbox_xyxy"])+ self.assert_close(output, image, rtol=0, atol=0)+ self.assert_close(output_boxes, boxes, rtol=0, atol=0)++class TestRandomMixUpV2(BaseTester):def test_smoke(self, device, dtype):f = RandomMixUpV2()@@ -577,6 +664,22 @@ class TestRandomMosaic(BaseTester):class TestRandomJigsaw(BaseTester):+ @pytest.mark.parametrize("p", [0.0, 1.0])+ @pytest.mark.parametrize("gate", [None, [0.0, 0.0], [1.0, 0.0]])+ @pytest.mark.parametrize(+ ("shape", "grid"),+ [((2, 1, 9, 13), (2, 3)), ((2, 3, 3, 4), (2, 2)), ((2, 1, 8, 13), (2, 3))],+ )+ def test_invalid_grid_before_gate_4651(self, p, gate, shape, grid, device, dtype):+ image = torch.zeros(shape, device=device, dtype=dtype)+ aug = RandomJigsaw(grid=grid, p=p)+ params = None+ if gate is not None:+ params = aug.forward_parameters(image.shape)+ params["batch_prob"] = torch.tensor(gate)+ with pytest.raises(RuntimeError, match="must be divisible by grid"):+ aug(image, params=params)+def test_smoke(self, device, dtype):f = RandomJigsaw(data_keys=["input"])repr = "RandomJigsaw(grid=(4, 4), p=0.5, p_batch=1.0, same_on_batch=False, grid=(4, 4))"