🐍 Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
fix(augmentation): make RandomJigsaw ensure_perm reject the image-preserving permutation (#4708)
Rızgar Ozan9fa5087fb839
diff --git a/changelog.d/4708.fixed.md b/changelog.d/4708.fixed.mdnew file mode 100644index 000000000..7835ed2a9--- /dev/null+++ b/changelog.d/4708.fixed.md@@ -0,0 +1,5 @@+`RandomJigsaw(ensure_perm=True)` now rejects the permutation that reproduces the image. It used to reject+`[0, ..., N - 1]`, which is the no-op only for a single-row or single-column grid: on a `2 x 2` grid it is a+transpose of the patch grid, while the no-op `[0, 2, 1, 3]` was still drawn, so about 1 call in 23 returned its+input unchanged. The rejected permutation is now `arange(N).view(rows, columns).T.flatten()`. A `1 x 1` grid with+`ensure_perm=True`, which used to hang in the rejection loop, now raises `ValueError` in the constructor. Fixes #4703.diff --git a/kornia/augmentation/_2d/mix/jigsaw.py b/kornia/augmentation/_2d/mix/jigsaw.pyindex 31e956f8f..adf6c295b 100644--- a/kornia/augmentation/_2d/mix/jigsaw.py+++ b/kornia/augmentation/_2d/mix/jigsaw.py@@ -39,9 +39,10 @@ class RandomJigsaw(MixAugmentationBaseV2):Args:grid: the Jigsaw puzzle grid. e.g. (2, 2) meanseach output will mix image patches in a 2x2 grid.- ensure_perm: reject the index-identity permutation ``[0, ..., N - 1]`` when drawing. That is the- image-preserving permutation only for a single-row or single-column grid; for any other grid the- output can still equal the input (`#4703 <https://github.com/kornia/kornia/issues/4703>`_).+ ensure_perm: reject the image-preserving permutation ``arange(N).view(rows, columns).T.flatten()`` when+ drawing, so a selected sample is never returned unchanged. For a single-row or single-column grid that+ permutation is ``[0, ..., N - 1]``; see the Convention block. A ``1 x 1`` grid has no other+ permutation, so it raises ``ValueError`` unless ``ensure_perm=False``.data_keys: the input type sequential for applying augmentations. Only "input" and "image" areimplemented; see the Convention block.p: probability of applying the transformation to each sample.diff --git a/kornia/augmentation/random_generator/_2d/jigsaw.py b/kornia/augmentation/random_generator/_2d/jigsaw.pyindex 8c6ea2062..46f7a2923 100644--- a/kornia/augmentation/random_generator/_2d/jigsaw.py+++ b/kornia/augmentation/random_generator/_2d/jigsaw.py@@ -48,6 +48,8 @@ class JigsawGenerator(RandomGeneratorBase):def __init__(self, grid: Tuple[int, int] = (4, 4), ensure_perm: bool = True) -> None:super().__init__()+ if ensure_perm and grid[0] * grid[1] == 1:+ raise ValueError(f"ensure_perm=True needs at least two patches, but grid={grid} has only one.")self.grid = gridself.ensure_perm = ensure_perm@@ -63,14 +65,20 @@ class JigsawGenerator(RandomGeneratorBase):_common_param_check(batch_size, same_on_batch)perm_times = self.grid[0] * self.grid[1]+ # RandomJigsaw fills destination cells column-major but indexes source patches row-major, so the+ # image-preserving permutation is the transposed index grid, not arange(perm_times).+ identity = torch.arange(perm_times, device=self._device).view(self.grid).T.flatten()# Generate mosiac order in one shotif batch_size == 0:rand_ids = torch.zeros([0, perm_times], device=self._device)elif same_on_batch:- rand_ids = randperm(perm_times, ensure_perm=self.ensure_perm, device=self._device)+ rand_ids = randperm(perm_times, ensure_perm=self.ensure_perm, identity=identity, device=self._device)rand_ids = torch.stack([rand_ids] * batch_size)else:rand_ids = torch.stack(- [randperm(perm_times, ensure_perm=self.ensure_perm, device=self._device) for _ in range(batch_size)]+ [+ randperm(perm_times, ensure_perm=self.ensure_perm, identity=identity, device=self._device)+ for _ in range(batch_size)+ ])return {"permutation": rand_ids}diff --git a/kornia/augmentation/random_generator/utils.py b/kornia/augmentation/random_generator/utils.pyindex eb67e97ae..fc5afa44a 100644--- a/kornia/augmentation/random_generator/utils.py+++ b/kornia/augmentation/random_generator/utils.py@@ -15,15 +15,20 @@# limitations under the License.#-from typing import Any+from typing import Any, Optionalimport torch-def randperm(n: int, ensure_perm: bool = True, **kwargs: Any) -> torch.Tensor:- """`randomperm` with the ability to ensure the different arrangement generated."""+def randperm(n: int, ensure_perm: bool = True, identity: Optional[torch.Tensor] = None, **kwargs: Any) -> torch.Tensor:+ """`randomperm` with the ability to ensure the different arrangement generated.++ ``identity`` is the permutation to reject when ``ensure_perm`` is set; it defaults to ``arange(n)``.+ """perm = torch.randperm(n, **kwargs)if ensure_perm:- while torch.all(torch.eq(perm, torch.arange(n, device=perm.device))):+ if identity is None:+ identity = torch.arange(n, device=perm.device)+ while torch.equal(perm, identity):perm = torch.randperm(n, **kwargs)return permdiff --git a/tests/augmentation/test_augmentation_mix.py b/tests/augmentation/test_augmentation_mix.pyindex 048707d97..30901cf1c 100644--- a/tests/augmentation/test_augmentation_mix.py+++ b/tests/augmentation/test_augmentation_mix.py@@ -712,6 +712,13 @@ class TestRandomJigsaw(BaseTester):with pytest.raises(RuntimeError, match="must be divisible by grid"):aug(image, params=params)+ def test_single_cell_grid(self, device, dtype):+ # A 1 x 1 grid has one permutation, the one ensure_perm rejects; drawing used to loop forever.+ with pytest.raises(ValueError, match="at least two patches"):+ RandomJigsaw(grid=(1, 1))+ image = torch.rand(2, 1, 4, 4, device=device, dtype=dtype)+ self.assert_close(RandomJigsaw(grid=(1, 1), p=1.0, ensure_perm=False)(image), image)+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))"@@ -739,10 +746,10 @@ class TestRandomJigsaw(BaseTester):[[[2.0, 3.0, 0.0, 1.0], [6.0, 7.0, 4.0, 5.0], [8.0, 9.0, 10.0, 11.0], [12.0, 13.0, 14.0, 15.0]]],[[- [16.0, 17.0, 18.0, 19.0],- [20.0, 21.0, 22.0, 23.0],- [24.0, 25.0, 26.0, 27.0],- [28.0, 29.0, 30.0, 31.0],+ [24.0, 25.0, 18.0, 19.0],+ [28.0, 29.0, 22.0, 23.0],+ [16.0, 17.0, 26.0, 27.0],+ [20.0, 21.0, 30.0, 31.0],]],],diff --git a/tests/augmentation/test_conventions_mix.py b/tests/augmentation/test_conventions_mix.pyindex ee38dc14d..3cd107725 100644--- a/tests/augmentation/test_conventions_mix.py+++ b/tests/augmentation/test_conventions_mix.py@@ -570,16 +570,27 @@ class TestMixConventions(BaseTester):self.assert_close(aug(picture, params=params), picture)@pytest.mark.device_agnostic- def test_wart_jigsaw_ensure_perm_rejects_the_wrong_permutation_4703(self):- # ensure_perm rejects arange(N), which is a real shuffle on a 2 x 2 grid, and still draws [0, 2, 1, 3],- # which is the no-op. 400 draws miss one of the 23 remaining permutations with probability 2e-8.+ def test_convention_jigsaw_ensure_perm_rejects_the_image_preserving_permutation_4703(self):+ # ensure_perm rejects [0, 2, 1, 3], the no-op on a 2 x 2 grid, and still draws arange(N), which is a real+ # shuffle there. 400 draws miss one of the 23 remaining permutations with probability 2e-8.aug = K.RandomJigsaw(grid=(2, 2), p=1.0, ensure_perm=True)drawn = set()for _ in range(50):permutation = aug.forward_parameters(torch.Size([8, 1, 4, 4]))["permutation"]drawn.update(tuple(row) for row in permutation.tolist())- assert (0, 1, 2, 3) not in drawn- assert (0, 2, 1, 3) in drawn+ assert (0, 2, 1, 3) not in drawn+ assert (0, 1, 2, 3) in drawn+ assert len(drawn) == 23+ # On a single-row or single-column grid the image-preserving permutation is arange(N), so the only+ # permutation left for two patches is the swap.+ for grid in ((1, 2), (2, 1)):+ permutation = K.RandomJigsaw(grid=grid, p=1.0).forward_parameters(torch.Size([8, 1, 4, 4]))["permutation"]+ assert permutation.tolist() == [[1, 0]] * 8+ # The guarantee as stated: with ensure_perm the output never equals the input.+ cells = torch.arange(4.0).view(2, 2)+ picture = cells.repeat_interleave(2, 0).repeat_interleave(2, 1)[None, None].repeat(64, 1, 1, 1)+ output = aug(picture)+ assert not (output == picture).flatten(1).all(1).any()def test_convention_transplantation3d_is_a_mix_class_over_volumes(self, device, dtype):# The base block's (B, C, H, W) working layout has one exception: the 3D transplantation class.