Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

fix(augmentation): keep PatchMix patches inside the image and stop same_on_batch pairing each image with itself (#4680)

Aditya Malkar0fa1b6948136
diff --git a/changelog.d/4680.fixed.md b/changelog.d/4680.fixed.md
new file mode 100644
index 000000000..dc25fa55b
--- /dev/null
+++ b/changelog.d/4680.fixed.md
@@ -0,0 +1,8 @@
+`PatchMix` rejects a `patch_size` larger than the input instead of drawing negative corners.
+The corner range was `height - patch_size` with nothing checking that the patch fits, so a
+larger patch made it negative and the negative slice that followed copied an arbitrary
+rectangle: the default `patch_size=16` on an 8x10 input changed a 7x5 region, and
+`patch_size=9` changed a non-square 8x9 one, neither raising. `same_on_batch=True` also
+returned its input unchanged, because the pairing is an argsort of drawn values and sharing
+that draw made every value equal, so the permutation was the identity and each image was
+patched with itself. The pairing draw is no longer shared; the patch location still is.
diff --git a/kornia/augmentation/random_generator/_2d/patchmix.py b/kornia/augmentation/random_generator/_2d/patchmix.py
index 6b37911b6..ae35234c3 100644
--- a/kornia/augmentation/random_generator/_2d/patchmix.py
+++ b/kornia/augmentation/random_generator/_2d/patchmix.py
@@ -92,8 +92,12 @@ class PatchMixGenerator(RandomGeneratorBase):
}
with torch.no_grad():
+ # The draw behind the pairing is never shared across the batch: identical values
+ # argsort to the identity, which pairs every image with itself and makes the whole
+ # augmentation a no-op. `same_on_batch` shares the patch location below instead,
+ # matching the convention that it does not equate batch-pairing indices.
mix_pairs: torch.Tensor = (
- _adapted_sampling((batch_size,), self.pair_sampler, same_on_batch)
+ _adapted_sampling((batch_size,), self.pair_sampler, same_on_batch=False)
.to(device=_device, dtype=_dtype)
.argsort(dim=0)
)
@@ -102,6 +106,12 @@ class PatchMixGenerator(RandomGeneratorBase):
# Sample patch coordinates
# height - patch_size + 1
+ if self.patch_size > min(height, width):
+ raise ValueError(
+ f"Expect `patch_size` to fit the input: got {self.patch_size} for an input of "
+ f"{height}x{width}. A larger patch makes the corner range negative, and the "
+ f"negative slice that follows copies an arbitrary rectangle instead of raising."
+ )
max_y = height - self.patch_size
max_x = width - self.patch_size
diff --git a/tests/augmentation/_2d/mix/test_patchmix.py b/tests/augmentation/_2d/mix/test_patchmix.py
index 83c4498f2..f61cda048 100644
--- a/tests/augmentation/_2d/mix/test_patchmix.py
+++ b/tests/augmentation/_2d/mix/test_patchmix.py
@@ -56,3 +56,53 @@ def test_patchmix_grad():
out = aug.apply_transform(x, params, {})
out.sum().backward()
assert x.grad is not None
+
+
[email protected]("patch_size", [9, 16])
+def test_patchmix_rejects_a_patch_larger_than_the_input(patch_size):
+ """A patch wider or taller than the image made the corner range negative.
+
+ The corners were then drawn negative and the negative slice that followed copied an
+ arbitrary rectangle: `patch_size=16` on an 8x10 input changed a 7x5 region, and
+ `patch_size=9` changed a non-square 8x9 one, neither raising.
+ """
+ x = torch.rand(4, 1, 8, 10)
+ with pytest.raises(ValueError, match=r"Expect `patch_size` to fit the input"):
+ PatchMix(patch_size=patch_size, p=1.0)(x)
+
+
[email protected]("patch_size", [1, 4, 8])
+def test_patchmix_corners_stay_inside_the_input(patch_size):
+ """Every corner a fitting patch draws leaves the patch inside the image."""
+ x = torch.rand(4, 1, 8, 10)
+ torch.manual_seed(0)
+ aug = PatchMix(patch_size=patch_size, p=1.0)
+ aug(x)
+ coords = aug._params["patch_coords"]
+ assert int(coords.min()) >= 0
+ assert int(coords[:, 0].max()) + patch_size <= x.shape[-1]
+ assert int(coords[:, 1].max()) + patch_size <= x.shape[-2]
+
+
+def test_patchmix_same_on_batch_shares_the_location_not_the_pairing():
+ """`same_on_batch` used to make the whole augmentation an identity.
+
+ The pairing is an argsort of the drawn values; sharing that draw across the batch made
+ every value equal, so the argsort was the identity permutation and each image was
+ patched with itself. The location is what `same_on_batch` shares.
+ """
+ torch.manual_seed(0)
+ aug = PatchMix(patch_size=4, p=1.0, same_on_batch=True)
+ x = torch.rand(4, 1, 8, 8)
+ out = aug(x)
+
+ assert not torch.equal(out, x)
+ coords = aug._params["patch_coords"].tolist()
+ assert len({tuple(row) for row in coords}) == 1
+
+ unchanged = 0
+ for seed in range(50):
+ torch.manual_seed(seed)
+ sample = torch.rand(4, 1, 8, 8)
+ unchanged += int(torch.equal(PatchMix(patch_size=4, p=1.0, same_on_batch=True)(sample), sample))
+ assert unchanged < 10
diff --git a/tests/augmentation/test_base.py b/tests/augmentation/test_base.py
index 170722efc..50ef4574b 100644
--- a/tests/augmentation/test_base.py
+++ b/tests/augmentation/test_base.py
@@ -614,7 +614,10 @@ class TestConventionAugmentationBase2D(BaseTester):
rows = []
for seed in range(8):
torch.manual_seed(seed)
- kwargs = {"use_correct_lambda": True} if augmentation_cls is K.RandomCutMixV2 else {}
+ kwargs: dict = {"use_correct_lambda": True} if augmentation_cls is K.RandomCutMixV2 else {}
+ # PatchMix's default patch_size of 16 does not fit this 6x8 input.
+ if augmentation_cls is K.PatchMix:
+ kwargs = {"patch_size": 4}
params = augmentation_cls(p=0.5, **kwargs).forward_parameters((4, 3, 6, 8))
rows.append(params["batch_prob"].tolist())
assert all(len(set(row)) == 1 for row in rows)