π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
[Feat] Added Mixup data augmentation (#609)
shijianjianfe6c54c953ad
diff --git a/docs/source/augmentation.rst b/docs/source/augmentation.rstindex ec6d16e35..785b04b4b 100644--- a/docs/source/augmentation.rst+++ b/docs/source/augmentation.rst@@ -148,6 +148,8 @@ Example for semantic segmentation using low-level randomness control:.. autoclass:: RandomPosterize.. autoclass:: RandomSharpness.. autoclass:: RandomEqualize+.. autoclass:: RandomMixUp+.. autoclass:: RandomCutMix.. autoclass:: RandomDepthicalFlip3D.. autoclass:: RandomHorizontalFlip3D.. autoclass:: RandomVerticalFlip3Ddiff --git a/docs/source/geometry.transform.rst b/docs/source/geometry.transform.rstindex 09e564722..824090ab4 100644--- a/docs/source/geometry.transform.rst+++ b/docs/source/geometry.transform.rst@@ -18,8 +18,12 @@ The functions in this section perform various geometrical transformations of 2D.. autofunction:: remap.. autofunction:: invert_affine_transform.. autofunction:: projection_from_Rt+.. autofunction:: crop_by_boxes.. autofunction:: center_crop.. autofunction:: crop_and_resize+.. autofunction:: bbox_to_mask+.. autofunction:: infer_box_shape+.. autofunction:: validate_bboxes.. autofunction:: pyrdown.. autofunction:: pyrup.. autofunction:: build_pyramiddiff --git a/kornia/augmentation/__init__.py b/kornia/augmentation/__init__.pyindex e0cf35a4c..79b02af8d 100644--- a/kornia/augmentation/__init__.py+++ b/kornia/augmentation/__init__.py@@ -25,6 +25,10 @@ from .augmentation3d import (RandomRotation3D,RandomAffine3D)+from .mix_augmentation import (+ RandomMixUp,+ RandomCutMix+)from kornia.enhance.normalize import (Normalize,Denormalize@@ -50,6 +54,8 @@ __all__ = ["RandomSharpness","RandomEqualize","RandomMotionBlur",+ "RandomMixUp",+ "RandomCutMix","AugmentationBase3D","RandomDepthicalFlip3D","RandomVerticalFlip3D",diff --git a/kornia/augmentation/functional.py b/kornia/augmentation/functional.pyindex e9e38d863..75721fa30 100644--- a/kornia/augmentation/functional.py+++ b/kornia/augmentation/functional.py@@ -14,7 +14,9 @@ from kornia.geometry import (warp_affine,hflip,vflip,- deg2rad+ deg2rad,+ bbox_to_mask,+ infer_box_shape)from kornia.color import rgb_to_grayscalefrom kornia.enhance import (@@ -32,7 +34,7 @@ from kornia.filters import motion_blurfrom kornia.geometry.transform.affwarp import _compute_rotation_matrix, _compute_tensor_centerfrom . import random_generator as rg-from .utils import _transform_input, _validate_input_shape, _validate_input_dtype, _range_bound+from .utils import _transform_input, _validate_input_shape, _validate_input_dtype, _range_bound, _shape_validationdef random_hflip(input: torch.Tensor, p: float = 0.5, return_transform: bool = False@@ -908,3 +910,127 @@ def apply_equalize(input: torch.Tensor, params: Dict[str, torch.Tensor]) -> torcfor image, prob in zip(input, params['batch_prob']):res.append(equalize(image) if prob else image)return torch.cat(res, dim=0)+++def apply_mixup(input: torch.Tensor, labels: torch.Tensor,+ params: Dict[str, torch.Tensor]) -> Tuple[torch.Tensor, torch.Tensor]:+ r"""Apply mixup to images in a batch.++ MixUp augmentation strategy: overlap images with different alpha values.++ Args:+ input (torch.Tensor): Tensor to be transformed with shape (H, W), (C, H, W), (B, C, H, W).+ labels (torch.Tensor): Label tensor with shape (B,).+ params (Dict[str, torch.Tensor]):+ - params['mixup_pairs']: Mixup indexes.+ - params['mixup_lambdas']: Lambda for the mixup strength.++ Returns:+ Tuple[torch.Tensor, torch.Tensor]:+ - Adjusted image, shape of :math:`(B, C, H, W)`.+ - Raw labels, corresponding labels and lambdas for each mix, shape of :math:`(B, 3)`.++ Examples:+ >>> input = torch.stack([torch.eye(5).unsqueeze(dim=0), torch.ones(5, 5).unsqueeze(dim=0)])+ >>> labels = torch.tensor([0, 1])+ >>> params = dict(mixup_pairs=torch.tensor([1, 0]), mixup_lambdas=torch.tensor([0.5, 0.9]))+ >>> out_img, out_label = apply_mixup(input, labels, params)+ >>> out_img+ tensor([[[[1.0000, 0.5000, 0.5000, 0.5000, 0.5000],+ [0.5000, 1.0000, 0.5000, 0.5000, 0.5000],+ [0.5000, 0.5000, 1.0000, 0.5000, 0.5000],+ [0.5000, 0.5000, 0.5000, 1.0000, 0.5000],+ [0.5000, 0.5000, 0.5000, 0.5000, 1.0000]]],+ <BLANKLINE>+ <BLANKLINE>+ [[[1.0000, 0.1000, 0.1000, 0.1000, 0.1000],+ [0.1000, 1.0000, 0.1000, 0.1000, 0.1000],+ [0.1000, 0.1000, 1.0000, 0.1000, 0.1000],+ [0.1000, 0.1000, 0.1000, 1.0000, 0.1000],+ [0.1000, 0.1000, 0.1000, 0.1000, 1.0000]]]])+ >>> out_label+ tensor([[0.0000, 1.0000, 0.5000],+ [1.0000, 0.0000, 0.9000]])++ """+ input = _transform_input(input)+ _validate_input_dtype(input, accepted_dtypes=[torch.float16, torch.float32, torch.float64])+ input_permute = input.index_select(dim=0, index=params['mixup_pairs'].to(input.device))+ labels_permute = labels.index_select(dim=0, index=params['mixup_pairs'].to(labels.device))++ lam = params['mixup_lambdas'].view(-1, 1, 1, 1).expand_as(input).to(labels.device)+ inputs = input * (1 - lam) + input_permute * lam+ labels = torch.stack([+ labels.to(input.dtype), labels_permute.to(input.dtype), params['mixup_lambdas'].to(labels.device)], dim=-1)+ return inputs, labels+++def apply_cutmix(input: torch.Tensor, labels: torch.Tensor,+ params: Dict[str, torch.Tensor]) -> Tuple[torch.Tensor, torch.Tensor]:+ r"""Apply cutmix to images in a batch.++ CutMix augmentation strategy: patches are cut and pasted among training images where the ground+ truth labels are also mixed proportionally to the area of the patches.++ Args:+ input (torch.Tensor): Tensor to be transformed with shape (H, W), (C, H, W), (B, C, H, W).+ labels (torch.Tensor): Label tensor with shape (B,).+ params (Dict[str, torch.Tensor]):+ - params['mix_pairs']: Mixup indexes with shape (num_mixes, B).+ - params['crop_src']: Lambda for the mixup strength (num_mixes, B, 4, 2).++ Returns:+ Tuple[torch.Tensor, torch.Tensor]:+ - Adjusted image, shape of :math:`(B, C, H, W)`.+ - Corresponding labels and lambdas for each mix, shape of :math:`(num_mixes, B, 2)`.++ Examples:+ >>> input = torch.stack([torch.zeros(1, 5, 5), torch.ones(1, 5, 5)], dim=0)+ >>> labels = torch.tensor([0, 1])+ >>> params = {'mix_pairs': torch.tensor([[1, 0]]), 'crop_src': torch.tensor([[[+ ... [1., 1.],+ ... [2., 1.],+ ... [2., 2.],+ ... [1., 2.]],+ ... [[1., 1.],+ ... [3., 1.],+ ... [3., 2.],+ ... [1., 2.]]]])}+ >>> apply_cutmix(input, labels, params)+ (tensor([[[[0., 0., 0., 0., 0.],+ [0., 1., 1., 0., 0.],+ [0., 1., 1., 0., 0.],+ [0., 0., 0., 0., 0.],+ [0., 0., 0., 0., 0.]]],+ <BLANKLINE>+ <BLANKLINE>+ [[[1., 1., 1., 1., 1.],+ [1., 0., 0., 0., 1.],+ [1., 0., 0., 0., 1.],+ [1., 1., 1., 1., 1.],+ [1., 1., 1., 1., 1.]]]]), tensor([[[0.0000, 1.0000, 0.1600],+ [1.0000, 0.0000, 0.2400]]]))+ """+ input = _transform_input(input)+ _validate_input_dtype(input, accepted_dtypes=[torch.float16, torch.float32, torch.float64])+ height, width = input.size(2), input.size(3)+ num_mixes = params['mix_pairs'].size(0)+ batch_size = params['mix_pairs'].size(1)++ _shape_validation(params['mix_pairs'], [num_mixes, batch_size], 'mix_pairs')+ _shape_validation(params['crop_src'], [num_mixes, batch_size, 4, 2], 'crop_src')++ out_inputs = input.clone()+ out_labels = []+ for pair, crop in zip(params['mix_pairs'], params['crop_src']):+ input_permute = input.index_select(dim=0, index=pair.to(input.device))+ labels_permute = labels.index_select(dim=0, index=pair.to(labels.device))+ w, h = infer_box_shape(crop)+ lam = w.to(input.dtype) * h.to(input.dtype) / (width * height) # width_beta * height_beta+ # compute mask to match input shape+ mask = bbox_to_mask(crop, width, height).bool().unsqueeze(dim=1).repeat(1, input.size(1), 1, 1)+ out_inputs[mask] = input_permute[mask]+ out_labels.append(torch.stack([+ labels.to(input.dtype), labels_permute.to(input.dtype), lam.to(labels.device)], dim=1))++ return out_inputs, torch.stack(out_labels, dim=0)diff --git a/kornia/augmentation/mix_augmentation.py b/kornia/augmentation/mix_augmentation.pynew file mode 100644index 000000000..6930efd27--- /dev/null+++ b/kornia/augmentation/mix_augmentation.py@@ -0,0 +1,225 @@+from typing import Callable, Tuple, Union, List, Optional, Dict, cast++import torch+import torch.nn as nn+from torch.nn.functional import pad++from kornia.constants import Resample, BorderType+from . import functional as F+from . import random_generator as rg+from .augmentation import AugmentationBase+from .utils import (+ _infer_batch_shape+)+++class MixAugmentation(AugmentationBase):+ r"""MixAugmentation base class for customized augmentation implementations. For any augmentation,+ the implementation of "generate_parameters" and "apply_transform" are required while the+ "compute_transformation" is only required when passing "return_transform" as True.++ In "apply_transform", both input and label tensors are required.++ Args:+ return_transform (bool): if ``True`` return the matrix describing the geometric transformation applied to each+ input tensor. If ``False`` and the input is a tuple the applied transformation+ wont be concatenated.++ """+ def __init__(self):+ super(MixAugmentation, self).__init__(return_transform=False)++ def apply_transform(self, input: torch.Tensor, label: torch.Tensor, # type: ignore+ params: Dict[str, torch.Tensor]) -> Tuple[torch.Tensor, torch.Tensor]: # type: ignore+ raise NotImplementedError++ def forward( # type: ignore+ self, input: torch.Tensor,+ label: torch.Tensor, params: Optional[Dict[str, torch.Tensor]] = None,+ return_transform: Optional[bool] = None+ ) -> Tuple[torch.Tensor, torch.Tensor]:+ if return_transform is None:+ return_transform = self.return_transform+ if params is None:+ batch_shape = self.infer_batch_shape(input)+ self._params = self.generate_parameters(batch_shape)+ else:+ self._params = params++ output = self.apply_transform(input, label, self._params)+ return output+++class RandomMixUp(MixAugmentation):+ r"""Implemention for `mixup: BEYOND EMPIRICAL RISK MINIMIZATION <https://arxiv.org/pdf/1710.09412.pdf>`.++ The function returns (inputs, labels), in which the inputs is the tensor that contains the mixup images+ while the labels is a :math:`(B, 3)` tensor that contains (label_batch, label_permuted_batch, lambda) for+ each image. The implementation is on top of `https://github.com/hongyi-zhang/mixup/blob/master/cifar/utils.py`.+ The loss and accuracy are computed as:+ ```+ def loss_mixup(y, logits):+ criterion = F.cross_entropy+ loss_a = criterion(logits, y[:, 0].long(), reduction='none')+ loss_b = criterion(logits, y[:, 1].long(), reduction='none')+ return ((1 - y[:, 2]) * loss_a + y[:, 2] * loss_b).mean()++ def acc_mixup(y, logits):+ pred = torch.argmax(logits, dim=1).to(y.device)+ return (1 - y[:, 2]) * pred.eq(y[:, 0]).float() + y[:, 2] * pred.eq(y[:, 1]).float()+ ```++ Args:+ p (float): probability for performing mixup. Default is 0.5.+ lambda_val (float or torch.Tensor, optional): min-max value of mixup strength. Default is 0-1.+ same_on_batch (bool): apply the same transformation across the batch.+ This flag will not maintain permutation order. Default: False.++ Inputs:+ Tuple[torch.Tensor, torch.Tensor]:+ - Input image tensors, shape of :math:`(B, C, H, W)`.+ - Label: raw labels, shape of :math:`(B,)`.++ Returns:+ Tuple[torch.Tensor, torch.Tensor]:+ - Adjusted image, shape of :math:`(B, C, H, W)`.+ - Raw labels, permuted labels and lambdas for each mix, shape of :math:`(B, 3)`.++ Note:+ This implementation would randomly mixup images in a batch. Ideally, the larger batch size would be preferred.++ Examples:+ >>> rng = torch.manual_seed(1)+ >>> input = torch.rand(2, 1, 3, 3)+ >>> label = torch.tensor([0, 1])+ >>> mixup = RandomMixUp()+ >>> mixup(input, label)+ (tensor([[[[0.7576, 0.2793, 0.4031],+ [0.7347, 0.0293, 0.7999],+ [0.3971, 0.7544, 0.5695]]],+ <BLANKLINE>+ <BLANKLINE>+ [[[0.4388, 0.6387, 0.5247],+ [0.6826, 0.3051, 0.4635],+ [0.4550, 0.5725, 0.4980]]]]), tensor([[0.0000, 0.0000, 0.1980],+ [1.0000, 1.0000, 0.4162]]))+ """+ def __init__(self, p: float = 1.0, lambda_val: Optional[Union[torch.Tensor, Tuple[float, float]]] = None,+ same_on_batch: bool = False) -> None:+ super(RandomMixUp, self).__init__()+ self.p = p+ if lambda_val is None:+ self.lambda_val = torch.tensor([0, 1.])+ else:+ self.lambda_val = \+ cast(torch.Tensor, lambda_val) if isinstance(lambda_val, torch.Tensor) else torch.tensor(lambda_val)+ self.same_on_batch = same_on_batch++ def __repr__(self) -> str:+ return f"{self.__class__.__name__}(p={self.p}, lambda_val={self.lambda_val}, same_on_batch={self.same_on_batch}"++ def generate_parameters(self, batch_shape: torch.Size) -> Dict[str, torch.Tensor]:+ return rg.random_mixup_generator(batch_shape[0], self.p, self.lambda_val, same_on_batch=self.same_on_batch)++ def apply_transform(self, input: torch.Tensor, label: torch.Tensor, # type: ignore+ params: Dict[str, torch.Tensor]) -> Tuple[torch.Tensor, torch.Tensor]: # type: ignore+ return F.apply_mixup(input, label, params)+++class RandomCutMix(MixAugmentation):+ r"""Implemention for `CutMix: Regularization Strategy to Train Strong Classifiers with Localizable Features+ <https://arxiv.org/pdf/1905.04899.pdf>`.++ The function returns (inputs, labels), in which the inputs is the tensor that contains the mixup images+ while the labels is a :math:`(num_mixes, B, 3)` tensor that contains (label_permuted_batch, lambda)+ for each cutmix. The implementation referred to `https://github.com/clovaai/CutMix-PyTorch`.++ The onehot label may be computed as :+ ```+ def onehot(size, target):+ vec = torch.zeros(size, dtype=torch.float32)+ vec[target] = 1.+ return vec++ def cutmix_label(labels, out_labels, size):+ lb_onehot = onehot(size, labels)+ for out_label in out_labels:+ label_permuted_batch, lam = out_label[:, 0], out_label[:, 1]+ label_permuted_onehot = onehot(size, label_permuted_batch)+ lb_onehot = lb_onehot * lam + label_permuted_onehot * (1. - lam)+ return lb_onehot+ ```++ Args:+ height (int): the width of the input image.+ width (int): the width of the input image.+ p (float): probability for performing cutmix. Default is 0.5.+ num_mix (int): cut mix times. Default is 1.+ beta (float or torch.Tensor, optional): hyperparameter for generating cut size from beta distribution.+ If None, it will be set to 1.+ cut_size ((float, float) or torch.Tensor, optional): controlling the minimum and maximum cut ratio from [0, 1].+ If None, it will be set to [0, 1], which means no restriction.+ same_on_batch (bool): apply the same transformation across the batch.+ This flag will not maintain permutation order. Default: False.++ Inputs:+ Tuple[torch.Tensor, torch.Tensor]:+ - Input image tensors, shape of :math:`(B, C, H, W)`.+ - Raw labels, shape of :math:`(B,)`++ Returns:+ Tuple[torch.Tensor, torch.Tensor]:+ - Adjusted image, shape of :math:`(B, C, H, W)`.+ - Raw labels, permuted labels and lambdas for each mix, shape of :math:`(num_mix, B, 3)`.++ Note:+ This implementation would randomly cutmix images in a batch. Ideally, the larger batch size would be preferred.++ Examples:+ >>> rng = torch.manual_seed(42)+ >>> input = torch.rand(2, 1, 3, 3)+ >>> input[0] = torch.ones((1, 3, 3))+ >>> label = torch.tensor([0, 1])+ >>> cutmix = RandomCutMix(3, 3)+ >>> cutmix(input, label)+ (tensor([[[[1.0000, 1.0000, 1.0000],+ [1.0000, 1.0000, 1.0000],+ [1.0000, 1.0000, 1.0000]]],+ <BLANKLINE>+ <BLANKLINE>+ [[[0.1332, 0.9346, 0.5936],+ [0.8694, 0.5677, 0.7411],+ [0.4294, 0.8854, 0.5739]]]]), tensor([[[0.0000, 0.0000, 0.4444],+ [1.0000, 1.0000, 0.0000]]]))+ """+ def __init__(self, height: int, width: int, p: float = 0.5, num_mix: int = 1,+ cut_size: Optional[Union[torch.Tensor, Tuple[float, float]]] = None,+ beta: Optional[Union[torch.Tensor, float]] = None, same_on_batch: bool = False) -> None:+ super(RandomCutMix, self).__init__()+ self.height = height+ self.width = width+ self.p = p+ self.num_mix = num_mix+ if beta is None:+ self.beta = torch.tensor(1.)+ else:+ self.beta = cast(torch.Tensor, beta) if isinstance(beta, torch.Tensor) else torch.tensor(beta)+ if cut_size is None:+ self.cut_size = torch.tensor([0., 1.])+ else:+ self.cut_size = \+ cast(torch.Tensor, cut_size) if isinstance(cut_size, torch.Tensor) else torch.tensor(cut_size)+ self.same_on_batch = same_on_batch++ def __repr__(self) -> str:+ return f"{self.__class__.__name__}(p={self.p}, num_mix={self.num_mix}, beta={self.beta}, "+ f"cut_size={self.cut_size}, height={self.height}, width={self.width}, same_on_batch={self.same_on_batch}"++ def generate_parameters(self, batch_shape: torch.Size) -> Dict[str, torch.Tensor]:+ return rg.random_cutmix_generator(batch_shape[0], width=self.width, height=self.height, p=self.p,+ cut_size=self.cut_size, num_mix=self.num_mix, beta=self.beta,+ same_on_batch=self.same_on_batch)++ def apply_transform(self, input: torch.Tensor, label: torch.Tensor, # type: ignore+ params: Dict[str, torch.Tensor]) -> Tuple[torch.Tensor, torch.Tensor]: # type: ignore+ return F.apply_cutmix(input, label, params)diff --git a/kornia/augmentation/random_generator.py b/kornia/augmentation/random_generator.pyindex da387025e..83b0be03f 100644--- a/kornia/augmentation/random_generator.py+++ b/kornia/augmentation/random_generator.py@@ -7,7 +7,8 @@ import torchfrom kornia.constants import Resample, BorderType, SamplePaddingfrom .utils import (_adapted_uniform,- _joint_range_check+ _adapted_beta,+ _joint_range_check,)@@ -601,3 +602,157 @@ def random_sharpness_generator(return dict(sharpness_factor=sharpness_factor)+++def random_mixup_generator(+ batch_size: int,+ p: float = 0.5,+ lambda_val: Optional[torch.Tensor] = None,+ same_on_batch: bool = False+) -> Dict[str, torch.Tensor]:+ r"""Generator mixup indexes and lambdas for a batch of inputs.++ Args:+ batch_size (int): the number of images. If batchsize == 1, the output will be as same as the input.+ p (flot): probability of applying mixup.+ lambda_val (torch.Tensor, optional): min-max strength for mixup images, ranged from [0., 1.].+ If None, it will be set to tensor([0., 1.]), which means no restrictions.+ same_on_batch (bool): apply the same transformation across the batch. Default: False.++ Returns:+ params Dict[str, torch.Tensor]: parameters to be passed for transformation.++ Examples:+ >>> rng = torch.manual_seed(0)+ >>> random_mixup_generator(5, 0.7)+ {'mixup_pairs': tensor([4, 0, 3, 1, 2]), 'mixup_lambdas': tensor([0.6323, 0.0000, 0.4017, 0.0223, 0.1689])}+ """+ if lambda_val is None:+ lambda_val = torch.tensor([0., 1.])+ _joint_range_check(lambda_val, 'lambda_val', bounds=(0, 1))++ batch_probs: torch.Tensor = random_prob_generator(batch_size, p, same_on_batch=same_on_batch)['batch_prob']+ mixup_pairs: torch.Tensor = torch.randperm(batch_size)+ mixup_lambdas: torch.Tensor = _adapted_uniform(+ (batch_size,), lambda_val[0], lambda_val[1], same_on_batch=same_on_batch)+ mixup_lambdas = mixup_lambdas * batch_probs.float()++ return dict(+ mixup_pairs=mixup_pairs,+ mixup_lambdas=mixup_lambdas+ )+++def random_cutmix_generator(+ batch_size: int,+ width: int,+ height: int,+ p: float = 0.5,+ num_mix: int = 1,+ beta: Optional[torch.Tensor] = None,+ cut_size: Optional[torch.Tensor] = None,+ same_on_batch: bool = False+) -> Dict[str, torch.Tensor]:+ r"""Generator cutmix indexes and lambdas for a batch of inputs.++ Args:+ batch_size (int): the number of images. If batchsize == 1, the output will be as same as the input.+ width (int): image width.+ height (int): image height.+ p (float): probability of applying cutmix.+ num_mix (int): number of images to mix with. Default is 1.+ beta (float or torch.Tensor, optional): hyperparameter for generating cut size from beta distribution.+ If None, it will be set to 1.+ cut_size ((float, float) or torch.Tensor, optional): controlling the minimum and maximum cut ratio from [0, 1].+ If None, it will be set to [0, 1], which means no restriction.+ same_on_batch (bool): apply the same transformation across the batch. Default: False.++ Returns:+ params Dict[str, torch.Tensor]: parameters to be passed for transformation.++ Examples:+ >>> rng = torch.manual_seed(0)+ >>> random_cutmix_generator(3, 224, 224, p=0.5, num_mix=2)+ {'mix_pairs': tensor([[2, 0, 1],+ [1, 2, 0]]), 'crop_src': tensor([[[[ 36, 25],+ [209, 25],+ [209, 198],+ [ 36, 198]],+ <BLANKLINE>+ [[157, 137],+ [156, 137],+ [156, 136],+ [157, 136]],+ <BLANKLINE>+ [[ 3, 12],+ [210, 12],+ [210, 219],+ [ 3, 219]]],+ <BLANKLINE>+ <BLANKLINE>+ [[[ 83, 126],+ [177, 126],+ [177, 220],+ [ 83, 220]],+ <BLANKLINE>+ [[ 55, 8],+ [206, 8],+ [206, 159],+ [ 55, 159]],+ <BLANKLINE>+ [[ 97, 70],+ [ 96, 70],+ [ 96, 69],+ [ 97, 69]]]])}++ """+ if beta is None:+ beta = torch.tensor(1.)+ if cut_size is None:+ cut_size = torch.tensor([0., 1.])+ _joint_range_check(cut_size, 'cut_size', bounds=(0, 1))++ batch_probs: torch.Tensor = random_prob_generator(batch_size * num_mix, p, same_on_batch)['batch_prob']+ mix_pairs: torch.Tensor = torch.rand(num_mix, batch_size).argsort(dim=1)+ cutmix_betas: torch.Tensor = _adapted_beta((batch_size * num_mix,), beta, beta, same_on_batch=same_on_batch)+ # Note: torch.clamp does not accept tensor, cutmix_betas.clamp(cut_size[0], cut_size[1]) throws:+ # Argument 1 to "clamp" of "_TensorBase" has incompatible type "Tensor"; expected "float"+ cutmix_betas = torch.min(torch.max(cutmix_betas, cut_size[0]), cut_size[1])+ cutmix_rate = torch.sqrt(1. - cutmix_betas) * batch_probs++ cut_height = (cutmix_rate * height).long()+ cut_width = (cutmix_rate * width).long()+ _gen_shape = (1,)++ if same_on_batch:+ _gen_shape = (cut_height.size(0),)+ cut_height = cut_height[0]+ cut_width = cut_width[0]++ x_start = _adapted_uniform(+ _gen_shape, torch.zeros_like(cut_width, dtype=torch.float32), width - cut_width, same_on_batch).long()+ y_start = _adapted_uniform(+ _gen_shape, torch.zeros_like(cut_height, dtype=torch.float32), height - cut_height, same_on_batch).long()++ bbox = torch.tensor([[+ [0, 0],+ [0, 0],+ [0, 0],+ [0, 0],+ ]]).repeat(batch_size * num_mix, 1, 1)++ crop_src = bbox.clone()+ crop_src[:, :, 0] += x_start.view(-1, 1)+ crop_src[:, :, 1] += y_start.view(-1, 1)+ crop_src[:, 1, 0] += cut_width - 1+ crop_src[:, 2, 0] += cut_width - 1+ crop_src[:, 2, 1] += cut_height - 1+ crop_src[:, 3, 1] += cut_height - 1++ # (B * num_mix, 4, 2) => (num_mix, batch_size, 4, 2)+ crop_src = crop_src.view(num_mix, batch_size, 4, 2)++ return dict(+ mix_pairs=mix_pairs,+ crop_src=crop_src+ )diff --git a/kornia/augmentation/utils/__init__.py b/kornia/augmentation/utils/__init__.pyindex 57baac923..e82ca2a31 100644--- a/kornia/augmentation/utils/__init__.py+++ b/kornia/augmentation/utils/__init__.py@@ -13,6 +13,8 @@ from kornia.augmentation.utils.helpers import (_validate_shape,_validate_input_shape,_adapted_uniform,+ _adapted_beta,+ _shape_validation,)__all__ = [@@ -24,6 +26,8 @@ __all__ = ["_validate_shape","_validate_input_shape","_adapted_uniform",+ "_adapted_beta",+ "_shape_validation","_range_bound","_joint_range_check","_singular_range_check",diff --git a/kornia/augmentation/utils/helpers.py b/kornia/augmentation/utils/helpers.pyindex 49595085e..0f104244d 100644--- a/kornia/augmentation/utils/helpers.py+++ b/kornia/augmentation/utils/helpers.py@@ -1,7 +1,7 @@from typing import Tuple, Union, List, cast, Optionalimport torch-from torch.distributions import Uniform+from torch.distributions import Uniform, Betadef _infer_batch_shape(input: Union[torch.Tensor, Tuple[torch.Tensor, torch.Tensor]]) -> torch.Size:@@ -111,18 +111,84 @@ def _validate_input_shape(input: torch.Tensor, channel_index: int, number: int)return input.shape[channel_index] == number-def _adapted_uniform(shape: Union[Tuple, torch.Size], low: Union[torch.Tensor, int, float],- high: Union[torch.Tensor, int, float], same_on_batch=False) -> torch.Tensor:- r""" The uniform function that accepts 'same_on_batch'.+def _adapted_uniform(+ shape: Union[Tuple, torch.Size],+ low: Union[float, int, torch.Tensor],+ high: Union[float, int, torch.Tensor],+ same_on_batch=False+) -> torch.Tensor:+ r""" The uniform sampling function that accepts 'same_on_batch'.If same_on_batch is True, all values generated will be exactly same given a batch_size (shape[0]).By default, same_on_batch is set to False."""if not isinstance(low, torch.Tensor):- low = torch.tensor(low).float()+ low = torch.tensor(low, dtype=torch.float32)if not isinstance(high, torch.Tensor):- high = torch.tensor(high).float()+ high = torch.tensor(high, dtype=torch.float32)dist = Uniform(low, high)if same_on_batch:return dist.rsample((1, *shape[1:])).repeat(shape[0])else:return dist.rsample(shape)+++def _adapted_beta(+ shape: Union[Tuple, torch.Size],+ a: Union[float, int, torch.Tensor],+ b: Union[float, int, torch.Tensor],+ same_on_batch=False+) -> torch.Tensor:+ r""" The beta sampling function that accepts 'same_on_batch'.+ If same_on_batch is True, all values generated will be exactly same given a batch_size (shape[0]).+ By default, same_on_batch is set to False.+ """+ if not isinstance(a, torch.Tensor):+ a = torch.tensor(a, dtype=torch.float32)+ if not isinstance(b, torch.Tensor):+ b = torch.tensor(b, dtype=torch.float32)+ dist = Beta(a, b)+ if same_on_batch:+ return dist.rsample((1, *shape[1:])).repeat(shape[0])+ else:+ return dist.rsample(shape)+++def _check_and_bound(factor: Union[torch.Tensor, float, Tuple[float, float], List[float]], name: str,+ center: float = 0., bounds: Tuple[float, float] = (0, float('inf'))) -> torch.Tensor:+ r"""Check inputs and compute the corresponding factor bounds+ """+ factor_bound: torch.Tensor+ if not isinstance(factor, torch.Tensor):+ factor = torch.tensor(factor, dtype=torch.float32)++ if factor.dim() == 0:+ _center = torch.tensor(center, dtype=torch.float32)++ if factor < 0:+ raise ValueError(f"If {name} is a single number number, it must be non negative. Got {factor.item()}")++ factor_bound = torch.tensor([_center - factor, _center + factor], dtype=torch.float32)+ # Should be something other than clamp+ # Currently, single value factor will not out of scope as long as the user provided it.+ factor_bound = torch.clamp(factor_bound, bounds[0], bounds[1])++ elif factor.shape[0] == 2 and factor.dim() == 1:++ if not bounds[0] <= factor[0] or not bounds[1] >= factor[1]:+ raise ValueError(f"{name} out of bounds. Expected inside {bounds}, got {factor}.")++ if not bounds[0] <= factor[0] <= factor[1] <= bounds[1]:+ raise ValueError(f"{name}[0] should be smaller than {name}[1] got {factor}")++ factor_bound = factor++ else:++ raise TypeError(+ f"The {name} should be a float number or a tuple with length 2 whose values move between {bounds}.")++ return factor_bound+++def _shape_validation(param: torch.Tensor, shape: Union[tuple, list], name: str) -> None:+ assert param.shape == torch.Size(shape), f"Invalid shape for {name}. Expected {shape}. Got {param.shape}"diff --git a/kornia/filters/kernels.py b/kornia/filters/kernels.pyindex 2fbc5b598..79c46678d 100644--- a/kornia/filters/kernels.py+++ b/kornia/filters/kernels.py@@ -1,4 +1,4 @@-from typing import Tuple, List, Union+from typing import Tuple, List, Union, castimport torchimport torch.nn as nn@@ -478,14 +478,20 @@ def get_motion_kernel2d(kernel_size: int, angle: Union[torch.Tensor, float],raise TypeError("ksize must be an odd integer >= than 3")if not isinstance(angle, torch.Tensor):- angle = torch.tensor(angle)+ angle = torch.tensor([angle])- assert angle.dim() == 0, f"angle must be a 0-dim tensor. Got {angle}."+ angle = cast(torch.Tensor, angle)+ if angle.dim() == 0:+ angle = angle.unsqueeze(dim=0)+ assert angle.dim() == 1, f"angle must be a 1-dim tensor. Got {angle}."if not isinstance(direction, torch.Tensor):- direction = torch.tensor(direction)+ direction = torch.tensor([direction])- assert direction.dim() == 0, f"direction must be a 0-dim tensor. Got {direction}."+ direction = cast(torch.Tensor, direction)+ if direction.dim() == 0:+ direction = direction.unsqueeze(dim=0)+ assert direction.dim() == 1, f"direction must be a 1-dim tensor. Got {direction}."kernel_tuple: Tuple[int, int] = (kernel_size, kernel_size)# direction from [-1, 1] to [0, 1] rangediff --git a/kornia/geometry/transform/crop.py b/kornia/geometry/transform/crop.pyindex 4e813baa9..a6f2c0b75 100644--- a/kornia/geometry/transform/crop.py+++ b/kornia/geometry/transform/crop.py@@ -10,6 +10,8 @@ __all__ = ["crop_and_resize","crop_by_boxes","center_crop",+ "bbox_to_mask",+ "infer_box_shape"]@@ -26,6 +28,7 @@ def crop_and_resize(tensor: torch.Tensor, boxes: torch.Tensor, size: Tuple[int,coordinates must be in the x, y order.size (Tuple[int, int]): a tuple with the height and width that will beused to resize the extracted patches.+ interpolation (str): Interpolation flag. Default: 'bilinear'.align_corners (bool): mode for grid_generation. Default: False. Seehttps://pytorch.org/docs/stable/nn.functional.html#torch.nn.functional.interpolate for detailsReturns:@@ -89,6 +92,7 @@ def center_crop(tensor: torch.Tensor, size: Tuple[int, int],(B, C, H, W).size (Tuple[int, int]): a tuple with the expected height and widthof the output patch.+ interpolation (str): Interpolation flag. Default: 'bilinear'.align_corners (bool): mode for grid_generation. Default: False. Seehttps://pytorch.org/docs/stable/nn.functional.html#torch.nn.functional.interpolate for detailsReturns:@@ -156,15 +160,55 @@ def center_crop(tensor: torch.Tensor, size: Tuple[int, int],align_corners)-def crop_by_boxes(tensor, src_box, dst_box,- interpolation: str = 'bilinear',- align_corners: bool = False) -> torch.Tensor:+def crop_by_boxes(tensor: torch.Tensor, src_box: torch.Tensor, dst_box: torch.Tensor,+ interpolation: str = 'bilinear', align_corners: bool = False) -> torch.Tensor:"""A wrapper performs crop transform with bounding boxes.+ Given an input tensor, this function selected the interested areas by the provided bounding boxes (src_box).+ Then the selected areas would be fitted into the targeted bounding boxes (dst_box) by a perspective transformation.+ So far, the ragged tensor is not supported by PyTorch right now. This function hereby requires the bounding boxes+ in a batch must be rectangles with same width and height.++ Args:+ tensor (torch.Tensor): the input tensor with shape (C, H, W) or (B, C, H, W).+ src_box (torch.Tensor): a tensor with shape (B, 4, 2) containing the coordinates of the bounding boxes+ to be extracted. The tensor must have the shape of Bx4x2, where each box is defined in the clockwise+ order: top-left, top-right, bottom-right and bottom-left. The coordinates must be in x, y order.+ dst_box (torch.Tensor): a tensor with shape (B, 4, 2) containing the coordinates of the bounding boxes+ to be placed. The tensor must have the shape of Bx4x2, where each box is defined in the clockwise+ order: top-left, top-right, bottom-right and bottom-left. The coordinates must be in x, y order.+ interpolation (str): Interpolation flag. Default: 'bilinear'.+ align_corners (bool): mode for grid_generation. Default: False. See+ https://pytorch.org/docs/stable/nn.functional.html#torch.nn.functional.interpolate for details++ Returns:+ torch.Tensor: the output tensor with patches.++ Examples:+ >>> input = torch.arange(16, dtype=torch.float32).reshape((1, 4, 4))+ >>> src_box = torch.tensor([[+ ... [1., 1.],+ ... [2., 1.],+ ... [2., 2.],+ ... [1., 2.],+ ... ]]) # 1x4x2+ >>> dst_box = torch.tensor([[+ ... [0., 0.],+ ... [1., 0.],+ ... [1., 1.],+ ... [0., 1.],+ ... ]]) # 1x4x2+ >>> crop_by_boxes(input, src_box, dst_box, align_corners=True)+ tensor([[[ 5.0000, 6.0000],+ [ 9.0000, 10.0000]]])+Note:If the src_box is smaller than dst_box, the following error will be thrown.RuntimeError: solve_cpu: For batch 0: U(2,2) is zero, singular U."""+ validate_bboxes(src_box)+ validate_bboxes(dst_box)+if tensor.ndimension() not in [3, 4]:raise TypeError("Only tensor with shape (C, H, W) and (B, C, H, W) supported. Got %s" % str(tensor.shape))# warping needs data in the shape of BCHW@@ -178,9 +222,11 @@ def crop_by_boxes(tensor, src_box, dst_box,# simulate broadcastingdst_trans_src = dst_trans_src.expand(tensor.shape[0], -1, -1).type_as(tensor)- bbox = _infer_bounding_box(dst_box)+ bbox = infer_box_shape(dst_box)+ assert len(bbox[0].unique()) == 1 and len(bbox[1].unique()) == 1, "cropping height and width" \+ f" must be exact same in a batch. Got height {bbox[0].unique()} and width {bbox[1].unique()}"patches: torch.Tensor = warp_affine(- tensor, dst_trans_src[:, :2, :], (int(bbox[0].int().data.item()), int(bbox[1].int().data.item())),+ tensor, dst_trans_src[:, :2, :], (int(bbox[0].unique().item()), int(bbox[1].unique().item())),flags=interpolation, align_corners=align_corners)# return in the original shape@@ -190,7 +236,7 @@ def crop_by_boxes(tensor, src_box, dst_box,return patches-def _infer_bounding_box(boxes: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor]:+def infer_box_shape(boxes: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor]:r"""Auto-infer the output sizes.Args:@@ -201,29 +247,90 @@ def _infer_bounding_box(boxes: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensorcoordinates must be in the x, y order.Returns:- (torch.Tensor, torch.Tensor): tensor containing the patches with shape BxN1xN2+ Tuple[torch.Tensor, torch.Tensor]:+ - Bounding box heights, shape of :math:`(B,)`.+ - Boundingbox widths, shape of :math:`(B,)`.Example:>>> boxes = torch.tensor([[- [1., 1.],- [2., 1.],- [2., 2.],- [1., 2.],- ]]) # 1x4x2- >>> _infer_bounding_box(boxes)- (2, 2)+ ... [1., 1.],+ ... [2., 1.],+ ... [2., 2.],+ ... [1., 2.],+ ... ], [+ ... [1., 1.],+ ... [3., 1.],+ ... [3., 2.],+ ... [1., 2.],+ ... ]]) # 2x4x2+ >>> infer_box_shape(boxes)+ (tensor([2., 2.]), tensor([2., 3.]))+ """+ validate_bboxes(boxes)+ width: torch.Tensor = (boxes[:, 1, 0] - boxes[:, 0, 0] + 1)+ height: torch.Tensor = (boxes[:, 2, 1] - boxes[:, 0, 1] + 1)+ return (height, width)+++def validate_bboxes(boxes: torch.Tensor) -> None:+ """Validate if a bounding box usable or not.++ This function checks if the boxes are rectangular or not.++ Args:+ boxes (torch.Tensor): a tensor containing the coordinates of the+ bounding boxes to be extracted. The tensor must have the shape+ of Bx4x2, where each box is defined in the following (clockwise)+ order: top-left, top-right, bottom-right, bottom-left. The+ coordinates must be in the x, y order."""assert torch.allclose((boxes[:, 1, 0] - boxes[:, 0, 0] + 1), (boxes[:, 2, 0] - boxes[:, 3, 0] + 1)), \- "Boxes must have be square, while get widths %s and %s" % \+ "Boxes must have be rectangular, while get widths %s and %s" % \(str(boxes[:, 1, 0] - boxes[:, 0, 0] + 1), str(boxes[:, 2, 0] - boxes[:, 3, 0] + 1))assert torch.allclose((boxes[:, 2, 1] - boxes[:, 0, 1] + 1), (boxes[:, 3, 1] - boxes[:, 1, 1] + 1)), \- "Boxes must have be square, while get heights %s and %s" % \+ "Boxes must have be rectangular, while get heights %s and %s" % \(str(boxes[:, 2, 1] - boxes[:, 0, 1] + 1), str(boxes[:, 3, 1] - boxes[:, 1, 1] + 1))- assert len((boxes[:, 1, 0] - boxes[:, 0, 0] + 1).unique()) == 1, \- "Boxes can only have one widths, got %s" % str((boxes[:, 1, 0] - boxes[:, 0, 0] + 1).unique())- assert len((boxes[:, 2, 1] - boxes[:, 0, 1] + 1).unique()) == 1, \- "Boxes can only have one heights, got %s" % str((boxes[:, 2, 1] - boxes[:, 0, 1] + 1).unique())- width: torch.Tensor = (boxes[:, 1, 0] - boxes[:, 0, 0] + 1)[0]- height: torch.Tensor = (boxes[:, 2, 1] - boxes[:, 0, 1] + 1)[0]- return (height, width)++def bbox_to_mask(boxes: torch.Tensor, width: int, height: int) -> torch.Tensor:+ """Convert bounding boxes to masks. Covered area is 1. and the remaining is 0.++ Args:+ boxes (torch.Tensor): a tensor containing the coordinates of the+ bounding boxes to be extracted. The tensor must have the shape+ of Bx4x2, where each box is defined in the following (clockwise)+ order: top-left, top-right, bottom-right, bottom-left. The+ coordinates must be in the x, y order.+ width (int): width of the masked image.+ height (int): height of the masked image.++ Returns:+ torch.Tensor: the output mask tensor.++ Examples:+ >>> boxes = torch.tensor([[+ ... [1., 1.],+ ... [3., 1.],+ ... [3., 2.],+ ... [1., 2.],+ ... ]]) # 1x4x2+ >>> bbox_to_mask(boxes, 5, 5)+ tensor([[[0., 0., 0., 0., 0.],+ [0., 1., 1., 1., 0.],+ [0., 1., 1., 1., 0.],+ [0., 0., 0., 0., 0.],+ [0., 0., 0., 0., 0.]]])+ """+ validate_bboxes(boxes)+ mask = torch.zeros((len(boxes), height, width))++ mask_out = []+ # TODO: Looking for a vectorized way+ for m, box in zip(mask, boxes):+ m = m.index_fill(1, torch.arange(box[0, 0].item(), box[1, 0].item() + 1, dtype=torch.long), torch.tensor(1))+ m = m.index_fill(0, torch.arange(box[1, 1].item(), box[2, 1].item() + 1, dtype=torch.long), torch.tensor(1))+ m = m.unsqueeze(dim=0)+ m_out = (m == 1).all(dim=1) * (m == 1).all(dim=2).T+ mask_out.append(m_out)++ return torch.stack(mask_out, dim=0).float()diff --git a/test/augmentation/test_augmentation_mix.py b/test/augmentation/test_augmentation_mix.pynew file mode 100644index 000000000..8aab54a56--- /dev/null+++ b/test/augmentation/test_augmentation_mix.py@@ -0,0 +1,227 @@+from typing import Union, Tuple++import torch+from torch.testing import assert_allclose+from torch.autograd import gradcheck++import kornia+import kornia.testing as utils # test utils+from kornia.augmentation import (+ RandomMixUp,+ RandomCutMix+)+++class TestRandomMixUp:++ def smoke_test(self, device, dtype):+ f = RandomMixUp()+ repr = "RandomMixUp(p=1.0, max_lambda=tensor(1.0), same_on_batch=False)"+ assert str(f) == repr++ def test_random_mixup_p1(self, device, dtype):+ torch.manual_seed(0)+ f = RandomMixUp()++ input = torch.stack([+ torch.ones(1, 3, 4, device=device, dtype=dtype),+ torch.zeros(1, 3, 4, device=device, dtype=dtype)+ ])+ label = torch.tensor([1, 0], device=device)+ lam = torch.tensor([0.1320, 0.3074], device=device, dtype=dtype)++ expected = torch.stack([+ torch.ones(1, 3, 4, device=device, dtype=dtype) * (1 - lam[0]),+ torch.ones(1, 3, 4, device=device, dtype=dtype) * lam[1]]+ )++ out_image, out_label = f(input, label)++ assert_allclose(out_image, expected, rtol=1e-4, atol=1e-4)+ assert (out_label[:, 0] == label).all()+ assert (out_label[:, 1] == torch.tensor([0, 1], device=device, dtype=dtype)).all()+ assert_allclose(out_label[:, 2], lam, rtol=1e-4, atol=1e-4)++ def test_random_mixup_p0(self, device, dtype):+ torch.manual_seed(0)+ f = RandomMixUp(p=0.)++ input = torch.stack([+ torch.ones(1, 3, 4, device=device, dtype=dtype),+ torch.zeros(1, 3, 4, device=device, dtype=dtype)+ ])+ label = torch.tensor([1, 0], device=device)+ lam = torch.tensor([0., 0.], device=device, dtype=dtype)++ expected = input.clone()++ out_image, out_label = f(input, label)++ assert_allclose(out_image, expected, rtol=1e-4, atol=1e-4)+ assert (out_label[:, 0] == label).all()+ assert (out_label[:, 1] == torch.tensor([0, 1], device=device, dtype=dtype)).all()+ assert_allclose(out_label[:, 2], lam, rtol=1e-4, atol=1e-4)++ def test_random_mixup_lam0(self, device, dtype):+ torch.manual_seed(0)+ f = RandomMixUp(lambda_val=(0., 0.))++ input = torch.stack([+ torch.ones(1, 3, 4, device=device, dtype=dtype),+ torch.zeros(1, 3, 4, device=device, dtype=dtype)+ ])+ label = torch.tensor([1, 0], device=device)+ lam = torch.tensor([0., 0.], device=device, dtype=dtype)++ expected = input.clone()++ out_image, out_label = f(input, label)++ assert_allclose(out_image, expected, rtol=1e-4, atol=1e-4)+ assert (out_label[:, 0] == label).all()+ assert (out_label[:, 1] == torch.tensor([0, 1])).all()+ assert_allclose(out_label[:, 2], lam, rtol=1e-4, atol=1e-4)++ def test_random_mixup_same_on_batch(self, device, dtype):+ torch.manual_seed(0)+ f = RandomMixUp(same_on_batch=True)++ input = torch.stack([+ torch.ones(1, 3, 4, device=device, dtype=dtype),+ torch.zeros(1, 3, 4, device=device, dtype=dtype)+ ])+ label = torch.tensor([1, 0], device=device)+ lam = torch.tensor([0.0885, 0.0885], device=device, dtype=dtype)++ expected = torch.stack([+ torch.ones(1, 3, 4, device=device, dtype=dtype) * (1 - lam[0]),+ torch.ones(1, 3, 4, device=device, dtype=dtype) * lam[1]+ ])++ out_image, out_label = f(input, label)+ assert_allclose(out_image, expected, rtol=1e-4, atol=1e-4)+ assert (out_label[:, 0] == label).all()+ assert (out_label[:, 1] == torch.tensor([0, 1], device=device, dtype=dtype)).all()+ assert_allclose(out_label[:, 2], lam, rtol=1e-4, atol=1e-4)+++class TestRandomCutMix:++ def smoke_test(self, device, dtype):+ f = RandomCutMix(width=3, height=3)+ repr = "RandomCutMix(p=1, num_mix=1, beta=tensor(0.),, width=3, height=3, same_on_batch=False"+ assert str(f) == repr++ def test_random_mixup_p1(self, device, dtype):+ torch.manual_seed(76)+ f = RandomCutMix(width=4, height=3, p=1.)++ input = torch.stack([+ torch.ones(1, 3, 4, device=device, dtype=dtype),+ torch.zeros(1, 3, 4, device=device, dtype=dtype)+ ])+ label = torch.tensor([1, 0], device=device)+ lam = torch.tensor([0.1320, 0.3074], device=device, dtype=dtype)++ expected = torch.tensor([[[[0., 0., 0., 1.],+ [0., 0., 0., 1.],+ [1., 1., 1., 1.]]],+ [[[1., 1., 1., 0.],+ [1., 1., 1., 0.],+ [0., 0., 0., 0.]]]], device=device, dtype=dtype)++ out_image, out_label = f(input, label)++ assert_allclose(out_image, expected, rtol=1e-4, atol=1e-4)+ assert (out_label[0, :, 0] == label).all()+ assert (out_label[0, :, 1] == torch.tensor([0, 1], device=device, dtype=dtype)).all()+ assert (out_label[0, :, 2] == torch.tensor([0.5, 0.5], device=device, dtype=dtype)).all()++ def test_random_mixup_p0(self, device, dtype):+ torch.manual_seed(76)+ f = RandomCutMix(p=0., width=4, height=3)++ input = torch.stack([+ torch.ones(1, 3, 4, device=device, dtype=dtype),+ torch.zeros(1, 3, 4, device=device, dtype=dtype)+ ])+ label = torch.tensor([1, 0], device=device)++ expected = input.clone()++ out_image, out_label = f(input, label)++ assert_allclose(out_image, expected, rtol=1e-4, atol=1e-4)+ assert (out_label[0, :, 0] == label).all()+ assert (out_label[0, :, 1] == torch.tensor([0, 1], device=device, dtype=dtype)).all()+ assert (out_label[0, :, 2] == torch.tensor([0., 0.], device=device, dtype=dtype)).all()++ def test_random_mixup_beta0(self, device, dtype):+ torch.manual_seed(76)+ f = RandomCutMix(beta=0., width=4, height=3)++ input = torch.stack([+ torch.ones(1, 3, 4, device=device, dtype=dtype),+ torch.zeros(1, 3, 4, device=device, dtype=dtype)+ ])+ label = torch.tensor([1, 0], device=device)++ expected = input.clone()++ out_image, out_label = f(input, label)++ assert_allclose(out_image, expected, rtol=1e-4, atol=1e-4)+ assert (out_label[0, :, 0] == label).all()+ assert (out_label[0, :, 1] == torch.tensor([0, 1])).all()+ assert (out_label[0, :, 2] == torch.tensor([0., 0.])).all()++ def test_random_mixup_num2(self, device, dtype):+ torch.manual_seed(76)+ f = RandomCutMix(width=4, height=3, num_mix=5)++ input = torch.stack([+ torch.ones(1, 3, 4, device=device, dtype=dtype),+ torch.zeros(1, 3, 4, device=device, dtype=dtype)+ ])+ label = torch.tensor([1, 0], device=device)++ expected = torch.tensor([[[[0., 0., 0., 1.],+ [0., 0., 0., 1.],+ [1., 1., 1., 1.]]],+ [[[1., 1., 0., 0.],+ [1., 1., 0., 0.],+ [0., 0., 0., 0.]]]], device=device, dtype=dtype)++ out_image, out_label = f(input, label)++ assert_allclose(out_image, expected, rtol=1e-4, atol=1e-4)+ assert (out_label[:, :, 0] == label).all()+ assert (out_label[:, :, 1] == torch.tensor([[1, 0], [1, 0], [1, 0], [1, 0], [0, 1]])).all()+ assert_allclose(out_label[:, :, 2], torch.tensor([[0., 0.], [0., 0.], [0., 0.0833], [0., 0.], [0.5, 0.3333]],+ device=device, dtype=dtype), rtol=1e-4, atol=1e-4)++ def test_random_mixup_same_on_batch(self, device, dtype):+ torch.manual_seed(0)+ f = RandomCutMix(same_on_batch=True, width=4, height=3)++ input = torch.stack([+ torch.ones(1, 3, 4, device=device, dtype=dtype),+ torch.zeros(1, 3, 4, device=device, dtype=dtype)+ ])+ label = torch.tensor([1, 0], device=device)+ lam = torch.tensor([0.0885, 0.0885], device=device, dtype=dtype)++ expected = torch.tensor([[[[0., 0., 1., 1.],+ [1., 1., 1., 1.],+ [1., 1., 1., 1.]]],+ [[[1., 1., 0., 0.],+ [0., 0., 0., 0.],+ [0., 0., 0., 0.]]]], device=device, dtype=dtype)++ out_image, out_label = f(input, label)++ assert_allclose(out_image, expected, rtol=1e-4, atol=1e-4)+ assert (out_label[0, :, 0] == label).all()+ assert (out_label[0, :, 1] == torch.tensor([0, 1], device=device, dtype=dtype)).all()+ assert_allclose(out_label[0, :, 2],+ torch.tensor([0.1667, 0.1667], device=device, dtype=dtype), rtol=1e-4, atol=1e-4)diff --git a/test/geometry/transform/test_crop.py b/test/geometry/transform/test_crop.pyindex de982b425..997e2246c 100644--- a/test/geometry/transform/test_crop.py+++ b/test/geometry/transform/test_crop.py@@ -20,7 +20,7 @@ class TestBoundingBoxInferring:]]).to(device)expected_height = 2expected_width = 3- h, w = kornia.geometry.transform.crop._infer_bounding_box(boxes)+ h, w = kornia.geometry.transform.crop.infer_box_shape(boxes)assert (h, w) == (expected_height, expected_width)def test_bounding_boxes_dim_inferring_batch(self, device):@@ -37,8 +37,8 @@ class TestBoundingBoxInferring:]]).to(device)expected_height = 2expected_width = 3- h, w = kornia.geometry.transform.crop._infer_bounding_box(boxes)- assert (h, w) == (expected_height, expected_width)+ h, w = kornia.geometry.transform.crop.infer_box_shape(boxes)+ assert (h.unique().item(), w.unique().item()) == (expected_height, expected_width)@pytest.mark.skip(reason="Crashes with pytorch internal error")# RuntimeError: isDifferentiableType(variable.scalar_type()) INTERNAL ASSERT FAILED at