Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

feat(patchmix): Add PatchMix augmentation (#3664)

Panchadip697be9c669b5
diff --git a/docs/generate_examples.py b/docs/generate_examples.py
index 0766569f7..b9cda522d 100644
--- a/docs/generate_examples.py
+++ b/docs/generate_examples.py
@@ -224,7 +224,7 @@ def main():
sig = f"{aug_name}({', '.join([str(a) for a in args])}, p=1.0)"
print(f"Generated image example for {aug_name}. {sig}")
- mix_augmentations_list = {"RandomMixUpV2": ((), 2, 20), "RandomCutMixV2": ((), 2, 2019)}
+ mix_augmentations_list = {"RandomMixUpV2": ((), 2, 20), "RandomCutMixV2": ((), 2, 2019), "PatchMix": ((), 2, 2024)}
# ITERATE OVER THE TRANSFORMS
for aug_name, (args, _, seed) in mix_augmentations_list.items():
img_in = torch.cat([img1, img2])
@@ -234,7 +234,11 @@ def main():
# set seed
torch.manual_seed(seed)
# apply the augmentation to the image and concat
- img_aug, _ = aug(img_in, torch.tensor([0, 1]))
+ # PatchMix returns (B, C, H, W); index [0] to get (C, H, W) for cat
+ if aug_name == "PatchMix":
+ img_aug = aug(img_in)[0]
+ else:
+ img_aug, _ = aug(img_in, torch.tensor([0, 1]))
output = torch.cat([img_in[0], img_in[1], img_aug], dim=-1)
# save the output image
diff --git a/docs/source/losses.rst b/docs/source/losses.rst
index dce565326..03b9c0737 100644
--- a/docs/source/losses.rst
+++ b/docs/source/losses.rst
@@ -34,7 +34,7 @@ Reconstruction
Semantic Segmentation
---------------------
-.. autofunction:: one_hot
+.. autofunction:: kornia.losses.one_hot
.. autofunction:: binary_focal_loss_with_logits
.. autofunction:: focal_loss
.. autofunction:: dice_loss
diff --git a/kornia/augmentation/_2d/mix/__init__.py b/kornia/augmentation/_2d/mix/__init__.py
index 55fb4c45c..63791543a 100644
--- a/kornia/augmentation/_2d/mix/__init__.py
+++ b/kornia/augmentation/_2d/mix/__init__.py
@@ -19,4 +19,5 @@ from kornia.augmentation._2d.mix.cutmix import RandomCutMixV2
from kornia.augmentation._2d.mix.jigsaw import RandomJigsaw
from kornia.augmentation._2d.mix.mixup import RandomMixUpV2
from kornia.augmentation._2d.mix.mosaic import RandomMosaic
+from kornia.augmentation._2d.mix.patchmix import PatchMix
from kornia.augmentation._2d.mix.transplantation import RandomTransplantation
diff --git a/kornia/augmentation/_2d/mix/patchmix.py b/kornia/augmentation/_2d/mix/patchmix.py
new file mode 100644
index 000000000..b919cb351
--- /dev/null
+++ b/kornia/augmentation/_2d/mix/patchmix.py
@@ -0,0 +1,87 @@
+# LICENSE HEADER MANAGED BY add-license-header
+#
+# Copyright 2018 Kornia Team
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+
+from typing import Any, Dict, List, Optional, Union
+
+import torch
+
+from kornia.augmentation import random_generator as rg
+from kornia.augmentation._2d.mix.base import MixAugmentationBaseV2
+from kornia.constants import DataKey
+
+
+class PatchMix(MixAugmentationBaseV2):
+ r"""PatchMix augmentation.
+
+ .. image:: _static/img/PatchMix.png
+
+ Replaces a random patch in each image of a batch with the corresponding
+ region from a randomly chosen different image in the batch.
+
+ Implementation for `CutMix: Regularization Strategy to Train Strong
+ Classifiers with Localizable Features` :cite:`yun2019cutmix`.
+
+ Args:
+ alpha: Hyperparameter for the Beta distribution used to generate the
+ mixing parameter lambda.
+ patch_size: The size of the square patch to mix.
+ p: Probability for applying the augmentation.
+ same_on_batch: Apply the same transformation across the batch.
+ keepdim: Whether to keep the output shape the same as input ``True``
+ or broadcast it to the batch form ``False``.
+
+ Examples:
+ >>> aug = PatchMix(alpha=1.0, patch_size=4)
+ >>> x = torch.rand(2, 3, 32, 32)
+ >>> out = aug(x)
+ >>> out.shape
+ torch.Size([2, 3, 32, 32])
+ """
+
+ def __init__(
+ self,
+ alpha: float = 1.0,
+ patch_size: int = 16,
+ p: float = 1.0,
+ same_on_batch: bool = False,
+ keepdim: bool = False,
+ data_keys: Optional[List[Union[str, int, DataKey]]] = None,
+ ) -> None:
+ super().__init__(p=1.0, p_batch=p, same_on_batch=same_on_batch, keepdim=keepdim, data_keys=data_keys)
+ self.alpha = alpha
+ self.patch_size = patch_size
+ self._param_generator = rg.PatchMixGenerator(alpha, patch_size, p)
+
+ def generate_parameters(self, batch_shape: torch.Size) -> Dict[str, torch.Tensor]:
+ return self._param_generator(batch_shape, self.same_on_batch)
+
+ def apply_transform(
+ self, input: torch.Tensor, params: Dict[str, torch.Tensor], extra_args: Dict[str, Any]
+ ) -> torch.Tensor:
+ B, _, _, _ = input.shape
+ idx = params["mix_pairs"].to(input.device)
+ patch_coords = params["patch_coords"].to(input.device)
+
+ out = input.clone()
+ for i in range(B):
+ x, y = patch_coords[i]
+ x, y = int(x.item()), int(y.item())
+ out[i, :, y : y + self.patch_size, x : x + self.patch_size] = input[
+ idx[i], :, y : y + self.patch_size, x : x + self.patch_size
+ ]
+
+ return out
diff --git a/kornia/augmentation/__init__.py b/kornia/augmentation/__init__.py
index af6bd7ed2..fea7e1723 100644
--- a/kornia/augmentation/__init__.py
+++ b/kornia/augmentation/__init__.py
@@ -30,6 +30,7 @@ from kornia.augmentation._2d import (
LongestMaxSize,
Normalize,
PadTo,
+ PatchMix,
RandomAffine,
RandomAutoContrast,
RandomBoxBlur,
@@ -134,6 +135,7 @@ __all__ = [
"MixAugmentationBaseV2",
"Normalize",
"PadTo",
+ "PatchMix",
"PatchSequential",
"RandomAffine",
"RandomAffine3D",
diff --git a/kornia/augmentation/random_generator/_2d/__init__.py b/kornia/augmentation/random_generator/_2d/__init__.py
index 49657ca38..b43eda013 100644
--- a/kornia/augmentation/random_generator/_2d/__init__.py
+++ b/kornia/augmentation/random_generator/_2d/__init__.py
@@ -31,6 +31,7 @@ from kornia.augmentation.random_generator._2d.linear_illumination import *
from kornia.augmentation.random_generator._2d.mixup import *
from kornia.augmentation.random_generator._2d.mosaic import *
from kornia.augmentation.random_generator._2d.motion_blur import *
+from kornia.augmentation.random_generator._2d.patchmix import *
from kornia.augmentation.random_generator._2d.perspective import *
from kornia.augmentation.random_generator._2d.plain_uniform import *
from kornia.augmentation.random_generator._2d.planckian_jitter import *
diff --git a/kornia/augmentation/random_generator/_2d/patchmix.py b/kornia/augmentation/random_generator/_2d/patchmix.py
new file mode 100644
index 000000000..6b37911b6
--- /dev/null
+++ b/kornia/augmentation/random_generator/_2d/patchmix.py
@@ -0,0 +1,123 @@
+# LICENSE HEADER MANAGED BY add-license-header
+#
+# Copyright 2018 Kornia Team
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+
+from typing import Dict, Tuple
+
+import torch
+from torch.distributions import Beta, Uniform
+
+from kornia.augmentation.random_generator.base import RandomGeneratorBase
+from kornia.augmentation.utils import _adapted_sampling, _common_param_check
+from kornia.core.utils import _extract_device_dtype
+
+__all__ = ["PatchMixGenerator"]
+
+
+class PatchMixGenerator(RandomGeneratorBase):
+ r"""Generate patchmix indexes and lambdas for a batch of inputs.
+
+ Args:
+ alpha (float): hyperparameter for generating cut size from beta distribution.
+ patch_size (int): size of the patch to be swapped.
+ p (float): probability of applying patchmix.
+
+ Returns:
+ params Dict[str, torch.Tensor]: parameters to be passed for transformation.
+ - mix_pairs (torch.Tensor): element-wise probabilities with a shape of (B).
+ - patch_coords (torch.Tensor): top-left coordinates of the patch (B, 2).
+ - lam (torch.Tensor): mixing parameter (B).
+
+ Note:
+ The generated random numbers are not reproducible across different devices and dtypes. By default,
+ the parameters will be generated on CPU in float32. This can be changed by calling
+ ``self.set_rng_device_and_dtype(device="cuda", dtype=torch.float64)``.
+ """
+
+ def __init__(
+ self,
+ alpha: float = 1.0,
+ patch_size: int = 16,
+ p: float = 1.0,
+ ) -> None:
+ super().__init__()
+ self.alpha = alpha
+ self.patch_size = patch_size
+ self.p = p
+
+ def __repr__(self) -> str:
+ repr = f"alpha={self.alpha}, patch_size={self.patch_size}, p={self.p}"
+ return repr
+
+ def make_samplers(self, device: torch.device, dtype: torch.dtype) -> None:
+ self.beta_sampler = Beta(
+ torch.tensor(self.alpha, device=device, dtype=dtype),
+ torch.tensor(self.alpha, device=device, dtype=dtype),
+ )
+ self.rand_sampler = Uniform(
+ torch.tensor(0.0, device=device, dtype=dtype),
+ torch.tensor(1.0, device=device, dtype=dtype),
+ )
+ self.pair_sampler = Uniform(
+ torch.tensor(0.0, device=device, dtype=dtype),
+ torch.tensor(1.0, device=device, dtype=dtype),
+ )
+
+ def forward(self, batch_shape: Tuple[int, ...], same_on_batch: bool = False) -> Dict[str, torch.Tensor]:
+ batch_size = batch_shape[0]
+ height = batch_shape[-2]
+ width = batch_shape[-1]
+
+ _device, _dtype = _extract_device_dtype([self.alpha])
+ _common_param_check(batch_size, same_on_batch)
+
+ if batch_size == 0:
+ return {
+ "mix_pairs": torch.zeros([0], device=_device, dtype=torch.long),
+ "patch_coords": torch.zeros([0, 2], device=_device, dtype=torch.long),
+ "lam": torch.zeros([0], device=_device, dtype=_dtype),
+ }
+
+ with torch.no_grad():
+ mix_pairs: torch.Tensor = (
+ _adapted_sampling((batch_size,), self.pair_sampler, same_on_batch)
+ .to(device=_device, dtype=_dtype)
+ .argsort(dim=0)
+ )
+ # Sample lam from beta distribution
+ lam = _adapted_sampling((batch_size,), self.beta_sampler, same_on_batch).to(device=_device, dtype=_dtype)
+
+ # Sample patch coordinates
+ # height - patch_size + 1
+ max_y = height - self.patch_size
+ max_x = width - self.patch_size
+
+ y = (
+ (_adapted_sampling((batch_size,), self.rand_sampler, same_on_batch) * (max_y + 1))
+ .floor()
+ .to(torch.long)
+ )
+ x = (
+ (_adapted_sampling((batch_size,), self.rand_sampler, same_on_batch) * (max_x + 1))
+ .floor()
+ .to(torch.long)
+ )
+
+ return {
+ "mix_pairs": mix_pairs.to(device=_device, dtype=torch.long),
+ "patch_coords": torch.stack([x, y], dim=1).to(device=_device, dtype=torch.long),
+ "lam": lam,
+ }
diff --git a/tests/augmentation/_2d/mix/test_patchmix.py b/tests/augmentation/_2d/mix/test_patchmix.py
new file mode 100644
index 000000000..83c4498f2
--- /dev/null
+++ b/tests/augmentation/_2d/mix/test_patchmix.py
@@ -0,0 +1,58 @@
+# LICENSE HEADER MANAGED BY add-license-header
+#
+# Copyright 2018 Kornia Team
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+
+import pytest
+import torch
+
+from kornia.augmentation import PatchMix
+
+
+ "batch_size,channels,height,width,patch_size",
+ [
+ (4, 3, 32, 32, 8),
+ (2, 1, 16, 16, 4),
+ ],
+)
+def test_patchmix_shape_and_type(batch_size, channels, height, width, patch_size):
+ aug = PatchMix(alpha=1.0, patch_size=patch_size)
+ x = torch.rand(batch_size, channels, height, width)
+ params = aug.generate_parameters(x.shape)
+ out = aug.apply_transform(x, params, {})
+ assert out.shape == x.shape
+ assert params["mix_pairs"].shape[0] == batch_size
+ assert params["lam"].shape[0] == batch_size
+ assert out.dtype == x.dtype
+
+
+def test_patchmix_different_inputs():
+ aug = PatchMix(alpha=1.0, patch_size=8)
+ x = torch.rand(4, 3, 32, 32)
+ y = torch.rand(4, 3, 32, 32)
+ params = aug.generate_parameters(x.shape)
+ out1 = aug.apply_transform(x, params, {})
+ out2 = aug.apply_transform(y, params, {})
+ assert not torch.allclose(out1, out2)
+
+
+def test_patchmix_grad():
+ aug = PatchMix(alpha=1.0, patch_size=8)
+ x = torch.rand(2, 3, 16, 16, requires_grad=True)
+ params = aug.generate_parameters(x.shape)
+ out = aug.apply_transform(x, params, {})
+ out.sum().backward()
+ assert x.grad is not None