π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
[Enhance] Added better augmentation support for backpropagation (#826)
shijianjian38dd4e8291cc
diff --git a/kornia/augmentation/__init__.py b/kornia/augmentation/__init__.pyindex eab82c984..758729dd3 100644--- a/kornia/augmentation/__init__.py+++ b/kornia/augmentation/__init__.py@@ -29,7 +29,8 @@ from .augmentation3d import (RandomMotionBlur3D,RandomCrop3D,CenterCrop3D,- RandomEqualize3D+ RandomEqualize3D,+ RandomPerspective3D)from .mix_augmentation import (RandomMixUp,@@ -69,6 +70,7 @@ __all__ = ["RandomRotation3D","RandomMotionBlur3D","RandomAffine3D",+ "RandomPerspective3D","RandomCrop3D","CenterCrop3D","RandomEqualize3D",diff --git a/kornia/augmentation/augmentation.py b/kornia/augmentation/augmentation.pyindex bb0a265c6..43757bca1 100644--- a/kornia/augmentation/augmentation.py+++ b/kornia/augmentation/augmentation.py@@ -1,16 +1,17 @@from typing import Callable, Tuple, Union, List, Optional, Dict, castimport torch+from torch.functional import Tensorimport torch.nn as nnfrom torch.nn.functional import padfrom kornia.constants import Resample, BorderType, SamplePaddingfrom kornia.augmentation import AugmentationBase2D+from kornia.utils import _extract_device_dtypefrom . import functional as Ffrom . import random_generator as rgfrom .utils import (_range_bound,- _singular_range_check)@@ -183,6 +184,7 @@ class ColorJitter(AugmentationBase2D):) -> None:super(ColorJitter, self).__init__(p=p, return_transform=return_transform, same_on_batch=same_on_batch,keepdim=keepdim)+ self._device, self._dtype = _extract_device_dtype([brightness, contrast, hue, saturation])self.brightness = brightnessself.contrast = contrastself.saturation = saturation@@ -194,13 +196,13 @@ class ColorJitter(AugmentationBase2D):def generate_parameters(self, batch_shape: torch.Size) -> Dict[str, torch.Tensor]:brightness: torch.Tensor = _range_bound(- self.brightness, 'brightness', center=1., bounds=(0, 2), device=self.device, dtype=self.dtype)+ self.brightness, 'brightness', center=1., bounds=(0, 2), device=self._device, dtype=self._dtype)contrast: torch.Tensor = _range_bound(- self.contrast, 'contrast', center=1., device=self.device, dtype=self.dtype)+ self.contrast, 'contrast', center=1., device=self._device, dtype=self._dtype)saturation: torch.Tensor = _range_bound(- self.saturation, 'saturation', center=1., device=self.device, dtype=self.dtype)+ self.saturation, 'saturation', center=1., device=self._device, dtype=self._dtype)hue: torch.Tensor = _range_bound(- self.hue, 'hue', bounds=(-0.5, 0.5), device=self.device, dtype=self.dtype)+ self.hue, 'hue', bounds=(-0.5, 0.5), device=self._device, dtype=self._dtype)return rg.random_color_jitter_generator(batch_shape[0], brightness, contrast, saturation, hue, self.same_on_batch,self.device, self.dtype)@@ -315,17 +317,20 @@ class RandomErasing(AugmentationBase2D):) -> None:super(RandomErasing, self).__init__(p=p, return_transform=return_transform, same_on_batch=same_on_batch,keepdim=keepdim)- self.scale = cast(torch.Tensor, scale) if isinstance(scale, torch.Tensor) else torch.tensor(scale)- self.ratio = cast(torch.Tensor, ratio) if isinstance(ratio, torch.Tensor) else torch.tensor(ratio)- self.value: float = value+ self._device, self._dtype = _extract_device_dtype([scale, ratio])+ self.scale = scale+ self.ratio = ratio+ self.value: float = float(value)def __repr__(self) -> str:repr = f"scale={self.scale}, ratio={self.ratio}, value={self.value}"return self.__class__.__name__ + f"({repr}, {super().__repr__()})"def generate_parameters(self, batch_shape: torch.Size) -> Dict[str, torch.Tensor]:+ scale = torch.as_tensor(self.scale, device=self._device, dtype=self._dtype)+ ratio = torch.as_tensor(self.ratio, device=self._device, dtype=self._dtype)return rg.random_rectangles_params_generator(- batch_shape[0], batch_shape[-2], batch_shape[-1], scale=self.scale, ratio=self.ratio,+ batch_shape[0], batch_shape[-2], batch_shape[-1], scale=scale, ratio=ratio,value=self.value, same_on_batch=self.same_on_batch, device=self.device, dtype=self.dtype)def compute_transformation(self, input: torch.Tensor, params: Dict[str, torch.Tensor]) -> torch.Tensor:@@ -372,21 +377,15 @@ class RandomPerspective(AugmentationBase2D):def __init__(self, distortion_scale: Union[torch.Tensor, float] = 0.5,- interpolation: Optional[Union[str, int, Resample]] = None,resample: Union[str, int, Resample] = Resample.BILINEAR.name,return_transform: bool = False, same_on_batch: bool = False,align_corners: bool = False, p: float = 0.5, keepdim: bool = False) -> None:super(RandomPerspective, self).__init__(p=p, return_transform=return_transform, same_on_batch=same_on_batch,keepdim=keepdim)- self.distortion_scale = cast(torch.Tensor, distortion_scale) \- if isinstance(distortion_scale, torch.Tensor) else torch.tensor(distortion_scale)- self.resample: Resample- if interpolation is not None:- import warnings- warnings.warn("interpolation is deprecated. Please use resample instead.", category=DeprecationWarning)- self.resample = Resample.get(interpolation)- self.resample = Resample.get(resample)+ self._device, self._dtype = _extract_device_dtype([distortion_scale])+ self.distortion_scale = distortion_scale+ self.resample: Resample = Resample.get(resample)self.align_corners = align_cornersself.flags: Dict[str, torch.Tensor] = dict(interpolation=torch.tensor(self.resample.value),@@ -399,8 +398,9 @@ class RandomPerspective(AugmentationBase2D):return self.__class__.__name__ + f"({repr}, {super().__repr__()})"def generate_parameters(self, batch_shape: torch.Size) -> Dict[str, torch.Tensor]:+ distortion_scale = torch.as_tensor(self.distortion_scale, device=self._device, dtype=self._dtype)return rg.random_perspective_generator(- batch_shape[0], batch_shape[-2], batch_shape[-1], self.distortion_scale, self.same_on_batch,+ batch_shape[0], batch_shape[-2], batch_shape[-1], distortion_scale, self.same_on_batch,self.device, self.dtype)def compute_transformation(self, input: torch.Tensor, params: Dict[str, torch.Tensor]) -> torch.Tensor:@@ -476,31 +476,11 @@ class RandomAffine(AugmentationBase2D):) -> None:super(RandomAffine, self).__init__(p=p, return_transform=return_transform, same_on_batch=same_on_batch,keepdim=keepdim)- degrees = cast(torch.Tensor, degrees) if isinstance(degrees, torch.Tensor) else torch.tensor(degrees)- self.degrees = _range_bound(degrees, 'degrees', 0, (-360, 360))- self.translate: Optional[torch.Tensor] = None- if translate is not None:- self.translate = _range_bound(translate, 'translate', bounds=(0, 1), check='singular')- self.scale: Optional[torch.Tensor] = None- if scale is not None:- scale = scale if isinstance(scale, torch.Tensor) else torch.tensor(scale)- if len(scale) == 2:- self.scale = _range_bound(scale, 'scale', bounds=(0, float('inf')), check='singular')- elif len(scale) == 4:- self.scale = torch.cat([- _range_bound(scale[:2], 'scale_x', bounds=(0, float('inf')), check='singular'),- _range_bound(scale[2:], 'scale_y', bounds=(0, float('inf')), check='singular')- ])- else:- raise ValueError("'scale' expected to be either 2 or 4 elements. Got {scale}")- self.shear: Optional[torch.Tensor] = None- if shear is not None:- shear = shear if isinstance(shear, torch.Tensor) else torch.tensor(shear)- self.shear = torch.stack([- _range_bound(shear if shear.dim() == 0 else shear[:2], 'shear-x', 0, (-360, 360)),- torch.tensor([0, 0], device=shear.device, dtype=shear.dtype) if shear.dim() == 0 or len(shear) == 2- else _range_bound(shear[2:], 'shear-y', 0, (-360, 360))- ])+ self._device, self._dtype = _extract_device_dtype([degrees, translate, scale, shear])+ self.degrees = degrees+ self.translate = translate+ self.scale = scale+ self.shear = shearself.resample: Resample = Resample.get(resample)self.padding_mode: SamplePadding = SamplePadding.get(padding_mode)self.align_corners = align_corners@@ -516,8 +496,39 @@ class RandomAffine(AugmentationBase2D):return self.__class__.__name__ + f"({repr}, {super().__repr__()})"def generate_parameters(self, batch_shape: torch.Size) -> Dict[str, torch.Tensor]:+ degrees = _range_bound(+ self.degrees, 'degrees', 0, (-360, 360), device=self._device, dtype=self._dtype)+ translate: Optional[torch.Tensor] = None+ scale: Optional[torch.Tensor] = None+ shear: Optional[torch.Tensor] = None++ if self.translate is not None:+ translate = _range_bound(+ self.translate, 'translate', bounds=(0, 1), check='singular', device=self._device, dtype=self._dtype)+ if self.scale is not None:+ scale = torch.as_tensor(self.scale, device=self._device, dtype=self._dtype)+ if len(scale) == 2:+ scale = _range_bound(+ scale, 'scale', bounds=(0, float('inf')), check='singular', device=self._device, dtype=self._dtype)+ elif len(scale) == 4:+ scale = torch.cat([+ _range_bound(scale[:2], 'scale_x', bounds=(0, float('inf')), check='singular',+ device=self._device, dtype=self._dtype),+ _range_bound(scale[2:], 'scale_y', bounds=(0, float('inf')), check='singular',+ device=self._device, dtype=self._dtype)+ ])+ else:+ raise ValueError(f"'scale' expected to be either 2 or 4 elements. Got {scale}")+ if self.shear is not None:+ shear = torch.as_tensor(self.shear, device=self._device, dtype=self._dtype)+ shear = torch.stack([+ _range_bound(shear if shear.dim() == 0 else shear[:2], 'shear-x', 0, (-360, 360),+ device=self._device, dtype=self._dtype),+ torch.tensor([0, 0], device=self._device, dtype=self._dtype) if shear.dim() == 0 or len(shear) == 2+ else _range_bound(shear[2:], 'shear-y', 0, (-360, 360), device=self._device, dtype=self._dtype)+ ])return rg.random_affine_generator(- batch_shape[0], batch_shape[-2], batch_shape[-1], self.degrees, self.translate, self.scale, self.shear,+ batch_shape[0], batch_shape[-2], batch_shape[-1], degrees, translate, scale, shear,self.same_on_batch, self.device, self.dtype)def compute_transformation(self, input: torch.Tensor, params: Dict[str, torch.Tensor]) -> torch.Tensor:@@ -607,7 +618,7 @@ class RandomRotation(AugmentationBase2D):p (float): probability of applying the transformation. Default value is 0.5.degrees (sequence or float or tensor): range of degrees to select from. If degrees is a number therange of degrees to select from will be (-degrees, +degrees).- interpolation (int, str or kornia.Resample): Default: Resample.BILINEAR.+ resample (int, str or kornia.Resample): Default: Resample.BILINEAR.return_transform (bool): if ``True`` return the matrix describing the transformation applied to eachinput tensor. If ``False`` and the input is a tuple the applied transformationwont be concatenated.@@ -644,21 +655,15 @@ class RandomRotation(AugmentationBase2D):def __init__(self, degrees: Union[torch.Tensor, float, Tuple[float, float], List[float]],- interpolation: Optional[Union[str, int, Resample]] = None,resample: Union[str, int, Resample] = Resample.BILINEAR.name,return_transform: bool = False, same_on_batch: bool = False, align_corners: bool = True, p: float = 0.5,keepdim: bool = False) -> None:super(RandomRotation, self).__init__(p=p, return_transform=return_transform, same_on_batch=same_on_batch,keepdim=keepdim)- degrees = cast(torch.Tensor, degrees) if isinstance(degrees, torch.Tensor) else torch.tensor(degrees)- self.degrees = _range_bound(degrees, 'degrees', 0, (-360, 360))- self.resample: Resample- if interpolation is not None:- import warnings- warnings.warn("interpolation is deprecated. Please use resample instead.", category=DeprecationWarning)- self.resample = Resample.get(interpolation)- self.resample = Resample.get(resample)+ self._device, self._dtype = _extract_device_dtype([degrees])+ self.degrees = degrees+ self.resample: Resample = Resample.get(resample)self.align_corners = align_cornersself.flags: Dict[str, torch.Tensor] = dict(interpolation=torch.tensor(self.resample.value),@@ -670,7 +675,8 @@ class RandomRotation(AugmentationBase2D):return self.__class__.__name__ + f"({repr}, {super().__repr__()})"def generate_parameters(self, batch_shape: torch.Size) -> Dict[str, torch.Tensor]:- return rg.random_rotation_generator(batch_shape[0], self.degrees, self.same_on_batch, self.device, self.dtype)+ degrees = _range_bound(self.degrees, 'degrees', 0, (-360, 360), device=self._device, dtype=self._dtype)+ return rg.random_rotation_generator(batch_shape[0], degrees, self.same_on_batch, self.device, self.dtype)def compute_transformation(self, input: torch.Tensor, params: Dict[str, torch.Tensor]) -> torch.Tensor:return F.compute_rotate_tranformation(input, params)@@ -740,7 +746,7 @@ class RandomCrop(AugmentationBase2D):self.pad_if_needed = pad_if_neededself.fill = fillself.padding_mode = padding_mode- self.resample = Resample.get(resample)+ self.resample: Resample = Resample.get(resample)self.align_corners = align_cornersself.flags: Dict[str, torch.Tensor] = dict(interpolation=torch.tensor(self.resample.value),@@ -837,7 +843,6 @@ class RandomResizedCrop(AugmentationBase2D):def __init__(self, size: Tuple[int, int], scale: Union[torch.Tensor, Tuple[float, float]] = (0.08, 1.0),ratio: Union[torch.Tensor, Tuple[float, float]] = (3. / 4., 4. / 3.),- interpolation: Optional[Union[str, int, Resample]] = None,resample: Union[str, int, Resample] = Resample.BILINEAR.name,return_transform: bool = False, same_on_batch: bool = False,align_corners: bool = False, p: float = 1., keepdim: bool = False@@ -845,15 +850,11 @@ class RandomResizedCrop(AugmentationBase2D):# Since PyTorch does not support ragged tensor. So cropping function happens all the time.super(RandomResizedCrop, self).__init__(p=1., return_transform=return_transform, same_on_batch=same_on_batch, p_batch=p, keepdim=keepdim)+ self._device, self._dtype = _extract_device_dtype([scale, ratio])self.size = size- self.scale = cast(torch.Tensor, scale) if isinstance(scale, torch.Tensor) else torch.tensor(scale)- self.ratio = cast(torch.Tensor, ratio) if isinstance(ratio, torch.Tensor) else torch.tensor(ratio)- self.resample: Resample- if interpolation is not None:- import warnings- warnings.warn("interpolation is deprecated. Please use resample instead.", category=DeprecationWarning)- self.resample = Resample.get(interpolation)- self.resample = Resample.get(resample)+ self.scale = scale+ self.ratio = ratio+ self.resample: Resample = Resample.get(resample)self.align_corners = align_cornersself.flags: Dict[str, torch.Tensor] = dict(interpolation=torch.tensor(self.resample.value),@@ -865,8 +866,10 @@ class RandomResizedCrop(AugmentationBase2D):return self.__class__.__name__ + f"({repr}, {super().__repr__()})"def generate_parameters(self, batch_shape: torch.Size) -> Dict[str, torch.Tensor]:+ scale = torch.as_tensor(self.scale, device=self._device, dtype=self._dtype)+ ratio = torch.as_tensor(self.ratio, device=self._device, dtype=self._dtype)target_size: torch.Tensor = rg.random_crop_size_generator(- batch_shape[0], self.size, self.scale, self.ratio, self.same_on_batch, self.device, self.dtype)['size']+ batch_shape[0], self.size, scale, ratio, self.same_on_batch, self.device, self.dtype)['size']return rg.random_crop_generator(batch_shape[0], (batch_shape[-2], batch_shape[-1]), target_size,resize_to=self.size, same_on_batch=self.same_on_batch,device=self.device, dtype=self.dtype)@@ -896,6 +899,7 @@ class RandomMotionBlur(AugmentationBase2D):If Tuple[int, int], it will randomly generate the value from the range.border_type (int, str or kornia.BorderType): the padding mode to be applied before convolving.CONSTANT = 0, REFLECT = 1, REPLICATE = 2, CIRCULAR = 3. Default: BorderType.CONSTANT.+ resample (int, str or kornia.Resample): Default: Resample.NEAREST.keepdim (bool): whether to keep the output shape the same as input (True) or broadcast itto the batch form (False). Default: False.@@ -908,6 +912,8 @@ class RandomMotionBlur(AugmentationBase2D):Additionally, this function accepts another transformation tensor (:math:`(B, 3, 3)`), then theapplied transformation will be merged int to the input transformation tensor and returned.+ Please set ``resample`` to ``'bilinear'`` if more meaningful gradients wanted.+Examples:>>> rng = torch.manual_seed(0)>>> input = torch.ones(1, 1, 5, 5)@@ -925,21 +931,21 @@ class RandomMotionBlur(AugmentationBase2D):angle: Union[torch.Tensor, float, Tuple[float, float]],direction: Union[torch.Tensor, float, Tuple[float, float]],border_type: Union[int, str, BorderType] = BorderType.CONSTANT.name,+ resample: Union[str, int, Resample] = Resample.NEAREST.name,return_transform: bool = False, same_on_batch: bool = False, p: float = 0.5, keepdim: bool = False) -> None:super(RandomMotionBlur, self).__init__(p=p, return_transform=return_transform, same_on_batch=same_on_batch,keepdim=keepdim)self.kernel_size: Union[int, Tuple[int, int]] = kernel_size+ self._device, self._dtype = _extract_device_dtype([angle, direction])- angle = cast(torch.Tensor, angle) if isinstance(angle, torch.Tensor) else torch.tensor(angle)- self.angle = _range_bound(angle, 'angle', center=0., bounds=(-360, 360))-- direction = \- cast(torch.Tensor, direction) if isinstance(direction, torch.Tensor) else torch.tensor(direction)- self.direction = _range_bound(direction, 'direction', center=0., bounds=(-1, 1))+ self.angle = angle+ self.direction = directionself.border_type = BorderType.get(border_type)+ self.resample = Resample.get(resample)self.flags: Dict[str, torch.Tensor] = {- "border_type": torch.tensor(self.border_type.value)+ "border_type": torch.tensor(self.border_type.value),+ "interpolation": torch.tensor(self.resample.value)}def __repr__(self) -> str:@@ -948,8 +954,12 @@ class RandomMotionBlur(AugmentationBase2D):return self.__class__.__name__ + f"({repr}, {super().__repr__()})"def generate_parameters(self, batch_shape: torch.Size) -> Dict[str, torch.Tensor]:+ angle = _range_bound(+ self.angle, 'angle', center=0., bounds=(-360, 360), device=self._device, dtype=self._dtype)+ direction = _range_bound(+ self.direction, 'direction', center=0., bounds=(-1, 1), device=self._device, dtype=self._dtype)return rg.random_motion_blur_generator(- batch_shape[0], self.kernel_size, self.angle, self.direction, self.same_on_batch, self.device, self.dtype)+ batch_shape[0], self.kernel_size, angle, direction, self.same_on_batch, self.device, self.dtype)def compute_transformation(self, input: torch.Tensor, params: Dict[str, torch.Tensor]) -> torch.Tensor:return F.compute_intensity_transformation(input)@@ -1002,21 +1012,20 @@ class RandomSolarize(AugmentationBase2D):same_on_batch: bool = False, return_transform: bool = False, p: float = 0.5, keepdim: bool = False) -> None:super(RandomSolarize, self).__init__(p=p, return_transform=return_transform, same_on_batch=same_on_batch)-- thresholds = \- cast(torch.Tensor, thresholds) if isinstance(thresholds, torch.Tensor) else torch.tensor(thresholds)- self.thresholds = _range_bound(thresholds, 'thresholds', center=0.5, bounds=(0., 1.))-- additions = \- cast(torch.Tensor, additions) if isinstance(additions, torch.Tensor) else torch.tensor(additions)- self.additions = _range_bound(additions, 'additions', bounds=(-0.5, 0.5))+ self._device, self._dtype = _extract_device_dtype([thresholds, additions])+ self.thresholds = thresholds+ self.additions = additionsdef __repr__(self) -> str:repr = f"thresholds={self.thresholds}, additions={self.additions}"return self.__class__.__name__ + f"({repr}, {super().__repr__()})"def generate_parameters(self, batch_shape: torch.Size) -> Dict[str, torch.Tensor]:- return rg.random_solarize_generator(batch_shape[0], self.thresholds, self.additions, self.same_on_batch,+ thresholds = _range_bound(+ self.thresholds, 'thresholds', center=0.5, bounds=(0., 1.), device=self._device, dtype=self._dtype)+ additions = _range_bound(+ self.additions, 'additions', bounds=(-0.5, 0.5), device=self._device, dtype=self._dtype)+ return rg.random_solarize_generator(batch_shape[0], thresholds, additions, self.same_on_batch,self.device, self.dtype)def compute_transformation(self, input: torch.Tensor, params: Dict[str, torch.Tensor]) -> torch.Tensor:@@ -1068,20 +1077,21 @@ class RandomPosterize(AugmentationBase2D):) -> None:super(RandomPosterize, self).__init__(p=p, return_transform=return_transform, same_on_batch=same_on_batch,keepdim=keepdim)- bits = cast(torch.Tensor, bits) if isinstance(bits, torch.Tensor) else torch.tensor(bits)- if len(bits.size()) == 0:- self.bits = torch.tensor([bits, torch.tensor(8)], dtype=torch.float32)- elif len(bits.size()) == 1 and bits.size(0) == 2:- self.bits = torch.tensor([bits[0], bits[1]], dtype=torch.float32)- else:- raise ValueError(f"'bits' shall be either a scalar or a length 2 tensor. Got {bits}.")+ self._device, self._dtype = _extract_device_dtype([bits])+ self.bits = bitsdef __repr__(self) -> str:repr = f"(bits={self.bits}"return self.__class__.__name__ + f"({repr}, {super().__repr__()})"def generate_parameters(self, batch_shape: torch.Size) -> Dict[str, torch.Tensor]:- return rg.random_posterize_generator(batch_shape[0], self.bits, self.same_on_batch, self.device, self.dtype)+ bits = torch.as_tensor(self.bits, device=self._device, dtype=self._dtype)+ if len(bits.size()) == 0:+ bits = bits.repeat(2)+ bits[1] = 8+ elif not (len(bits.size()) == 1 and bits.size(0) == 2):+ raise ValueError(f"'bits' shall be either a scalar or a length 2 tensor. Got {bits}.")+ return rg.random_posterize_generator(batch_shape[0], bits, self.same_on_batch, self.device, self.dtype)def compute_transformation(self, input: torch.Tensor, params: Dict[str, torch.Tensor]) -> torch.Tensor:return F.compute_intensity_transformation(input)@@ -1129,20 +1139,21 @@ class RandomSharpness(AugmentationBase2D):) -> None:super(RandomSharpness, self).__init__(p=p, return_transform=return_transform, same_on_batch=same_on_batch,keepdim=keepdim)- sharpness = cast(torch.Tensor, sharpness) if isinstance(sharpness, torch.Tensor) else torch.tensor(sharpness)- if sharpness.dim() == 0:- self.sharpness = torch.tensor([0, sharpness], dtype=torch.float32)- elif sharpness.dim() == 1 and sharpness.size(0) == 2:- self.sharpness = torch.tensor([sharpness[0], sharpness[1]], dtype=torch.float32)- else:- raise ValueError(f"'sharpness' must be a scalar or a length 2 tensor. Got {sharpness}.")+ self._device, self._dtype = _extract_device_dtype([sharpness])+ self.sharpness = sharpnessdef __repr__(self) -> str:repr = f"sharpness={self.sharpness}"return self.__class__.__name__ + f"({repr}, {super().__repr__()})"def generate_parameters(self, batch_shape: torch.Size) -> Dict[str, torch.Tensor]:- return rg.random_sharpness_generator(batch_shape[0], self.sharpness, self.same_on_batch,+ sharpness = torch.as_tensor(self.sharpness, device=self._device, dtype=self._dtype)+ if sharpness.dim() == 0:+ sharpness = sharpness.repeat(2)+ sharpness[0] = 0.+ elif not (sharpness.dim() == 1 and sharpness.size(0) == 2):+ raise ValueError(f"'sharpness' must be a scalar or a length 2 tensor. Got {sharpness}.")+ return rg.random_sharpness_generator(batch_shape[0], sharpness, self.same_on_batch,self.device, self.dtype)def compute_transformation(self, input: torch.Tensor, params: Dict[str, torch.Tensor]) -> torch.Tensor:diff --git a/kornia/augmentation/augmentation3d.py b/kornia/augmentation/augmentation3d.pyindex b0d576f05..429c4d377 100644--- a/kornia/augmentation/augmentation3d.py+++ b/kornia/augmentation/augmentation3d.py@@ -4,6 +4,7 @@ import torchfrom torch.nn.functional import padfrom kornia.constants import Resample, BorderType+from kornia.utils import _extract_device_dtypefrom .base import AugmentationBase3Dfrom . import functional as Ffrom . import random_generator as rg@@ -288,28 +289,11 @@ class RandomAffine3D(AugmentationBase3D):) -> None:super(RandomAffine3D, self).__init__(p=p, return_transform=return_transform, same_on_batch=same_on_batch,keepdim=keepdim)- self.degrees = _tuple_range_reader(degrees, 3)- self.shear: Optional[torch.Tensor] = None- if shears is not None:- self.shear = _tuple_range_reader(shears, 6)-- # check translation range- self.translate: Optional[torch.Tensor] = None- if translate is not None:- self.translate = translate if isinstance(translate, torch.Tensor) else torch.tensor(translate)- _singular_range_check(self.translate, 'translate', bounds=(0, 1), mode='3d')-- # check scale range- self.scale: Optional[torch.Tensor] = None- if scale is not None:- self.scale = scale if isinstance(scale, torch.Tensor) else torch.tensor(scale)- if self.scale.shape == torch.Size([2]):- self.scale = self.scale.unsqueeze(0).repeat(3, 1)- elif self.scale.shape != torch.Size([3, 2]):- raise ValueError("'scale' shall be either shape (2) or (3, 2). Got {self.scale}")- _singular_range_check(self.scale[0], 'scale-x', bounds=(0, float('inf')), mode='2d')- _singular_range_check(self.scale[1], 'scale-y', bounds=(0, float('inf')), mode='2d')- _singular_range_check(self.scale[2], 'scale-z', bounds=(0, float('inf')), mode='2d')+ self._device, self._dtype = _extract_device_dtype([degrees, shears, translate, scale])+ self.degrees = degrees+ self.shears = shears+ self.translate = translate+ self.scale = scaleself.resample = Resample.get(resample)self.align_corners = align_corners@@ -319,14 +303,36 @@ class RandomAffine3D(AugmentationBase3D):)def __repr__(self) -> str:- repr = (f"(degrees={self.degrees}, translate={self.translate}, scale={self.scale}, shear={self.shear}, "+ repr = (f"(degrees={self.degrees}, translate={self.translate}, scale={self.scale}, shear={self.shears}, "f"resample={self.resample.name}, align_corners={self.align_corners}")return self.__class__.__name__ + f"({repr}, {super().__repr__()})"def generate_parameters(self, batch_shape: torch.Size) -> Dict[str, torch.Tensor]:+ degrees = _tuple_range_reader(self.degrees, 3, self._device, self._dtype)+ shear: Optional[torch.Tensor] = None+ if self.shears is not None:+ shear = _tuple_range_reader(self.shears, 6, self._device, self._dtype)++ # check translation range+ translate: Optional[torch.Tensor] = None+ if self.translate is not None:+ translate = torch.as_tensor(self.translate, device=self._device, dtype=self._dtype)+ _singular_range_check(translate, 'translate', bounds=(0, 1), mode='3d')++ # check scale range+ scale: Optional[torch.Tensor] = None+ if self.scale is not None:+ scale = torch.as_tensor(self.scale, device=self._device, dtype=self._dtype)+ if scale.shape == torch.Size([2]):+ scale = scale.unsqueeze(0).repeat(3, 1)+ elif scale.shape != torch.Size([3, 2]):+ raise ValueError(f"'scale' shall be either shape (2) or (3, 2). Got {self.scale}.")+ _singular_range_check(scale[0], 'scale-x', bounds=(0, float('inf')), mode='2d')+ _singular_range_check(scale[1], 'scale-y', bounds=(0, float('inf')), mode='2d')+ _singular_range_check(scale[2], 'scale-z', bounds=(0, float('inf')), mode='2d')return rg.random_affine_generator3d(- batch_shape[0], batch_shape[-3], batch_shape[-2], batch_shape[-1], self.degrees,- self.translate, self.scale, self.shear, self.same_on_batch, self.device, self.dtype)+ batch_shape[0], batch_shape[-3], batch_shape[-2], batch_shape[-1], degrees,+ translate, scale, shear, self.same_on_batch, self.device, self.dtype)def compute_transformation(self, input: torch.Tensor, params: Dict[str, torch.Tensor]) -> torch.Tensor:return F.compute_affine_transformation3d(input, params)@@ -396,19 +402,14 @@ class RandomRotation3D(AugmentationBase3D):def __init__(self, degrees: Union[torch.Tensor, float, Tuple[float, float, float],Tuple[Tuple[float, float], Tuple[float, float], Tuple[float, float]]],- interpolation: Optional[Union[str, int, Resample]] = None,resample: Union[str, int, Resample] = Resample.BILINEAR.name,return_transform: bool = False, same_on_batch: bool = False,align_corners: bool = False, p: float = 0.5, keepdim: bool = False) -> None:super(RandomRotation3D, self).__init__(p=p, return_transform=return_transform, same_on_batch=same_on_batch,keepdim=keepdim)- self.degrees = _tuple_range_reader(degrees, 3)- if interpolation is not None:- import warnings- warnings.warn("interpolation is deprecated. Please use resample instead.", category=DeprecationWarning)- self.resample = Resample.get(interpolation)-+ self._device, self._dtype = _extract_device_dtype([degrees])+ self.degrees = degreesself.resample = Resample.get(resample)self.align_corners = align_cornersself.flags: Dict[str, torch.Tensor] = dict(@@ -421,7 +422,8 @@ class RandomRotation3D(AugmentationBase3D):return self.__class__.__name__ + f"({repr}, {super().__repr__()})"def generate_parameters(self, batch_shape: torch.Size) -> Dict[str, torch.Tensor]:- return rg.random_rotation_generator3d(batch_shape[0], self.degrees, self.same_on_batch, self.device, self.dtype)+ degrees = _tuple_range_reader(self.degrees, 3, self._device, self._dtype)+ return rg.random_rotation_generator3d(batch_shape[0], degrees, self.same_on_batch, self.device, self.dtype)def compute_transformation(self, input: torch.Tensor, params: Dict[str, torch.Tensor]) -> torch.Tensor:return F.compute_rotate_tranformation3d(input, params)@@ -454,6 +456,8 @@ class RandomMotionBlur3D(AugmentationBase3D):If Tuple[int, int], it will randomly generate the value from the range.border_type (int, str or kornia.BorderType): the padding mode to be applied before convolving.CONSTANT = 0, REFLECT = 1, REPLICATE = 2, CIRCULAR = 3. Default: BorderType.CONSTANT.+ resample (int, str or kornia.Resample): resample mode from "nearest" (0) or "bilinear" (1).+ Default: Resample.NEAREST.keepdim (bool): whether to keep the output shape the same as input (True) or broadcast itto the batch form (False). Default: False.@@ -496,20 +500,20 @@ class RandomMotionBlur3D(AugmentationBase3D):Tuple[Tuple[float, float], Tuple[float, float], Tuple[float, float]]],direction: Union[torch.Tensor, float, Tuple[float, float]],border_type: Union[int, str, BorderType] = BorderType.CONSTANT.name,+ resample: Union[str, int, Resample] = Resample.NEAREST.name,return_transform: bool = False, same_on_batch: bool = False, p: float = 0.5, keepdim: bool = False) -> None:super(RandomMotionBlur3D, self).__init__(p=p, return_transform=return_transform, same_on_batch=same_on_batch, p_batch=1., keepdim=keepdim)+ self._device, self._dtype = _extract_device_dtype([angle, direction])self.kernel_size: Union[int, Tuple[int, int]] = kernel_size-- self.angle: torch.Tensor = _tuple_range_reader(angle, 3)-- direction = \- cast(torch.Tensor, direction) if isinstance(direction, torch.Tensor) else torch.tensor(direction)- self.direction = _range_bound(direction, 'direction', center=0., bounds=(-1, 1))+ self.angle = angle+ self.direction = direction+ self.resample = Resample.get(resample)self.border_type = BorderType.get(border_type)self.flags: Dict[str, torch.Tensor] = {- "border_type": torch.tensor(self.border_type.value)+ "border_type": torch.tensor(self.border_type.value),+ "interpolation": torch.tensor(self.resample.value),}def __repr__(self) -> str:@@ -518,8 +522,11 @@ class RandomMotionBlur3D(AugmentationBase3D):return self.__class__.__name__ + f"({repr}, {super().__repr__()})"def generate_parameters(self, batch_shape: torch.Size) -> Dict[str, torch.Tensor]:+ angle: torch.Tensor = _tuple_range_reader(self.angle, 3, self._device, self._dtype)+ direction = _range_bound(+ self.direction, 'direction', center=0., bounds=(-1, 1), device=self._device, dtype=self._dtype)return rg.random_motion_blur_generator3d(- batch_shape[0], self.kernel_size, self.angle, self.direction, self.same_on_batch, self.device, self.dtype)+ batch_shape[0], self.kernel_size, angle, direction, self.same_on_batch, self.device, self.dtype)def compute_transformation(self, input: torch.Tensor, params: Dict[str, torch.Tensor]) -> torch.Tensor:return F.compute_intensity_transformation3d(input)@@ -804,8 +811,8 @@ class RandomPerspective3D(AugmentationBase3D):) -> None:super(RandomPerspective3D, self).__init__(p=p, return_transform=return_transform, same_on_batch=same_on_batch,keepdim=keepdim)- self.distortion_scale = cast(torch.Tensor, distortion_scale) \- if isinstance(distortion_scale, torch.Tensor) else torch.tensor(distortion_scale)+ self._device, self._dtype = _extract_device_dtype([distortion_scale])+ self.distortion_scale = distortion_scaleself.resample = Resample.get(resample)self.align_corners = align_cornersself.flags: Dict[str, torch.Tensor] = dict(@@ -819,9 +826,10 @@ class RandomPerspective3D(AugmentationBase3D):return self.__class__.__name__ + f"({repr}, {super().__repr__()})"def generate_parameters(self, batch_shape: torch.Size) -> Dict[str, torch.Tensor]:+ distortion_scale = torch.as_tensor(self.distortion_scale, device=self._device, dtype=self._dtype)return rg.random_perspective_generator3d(batch_shape[0], batch_shape[-3], batch_shape[-2], batch_shape[-1],- self.distortion_scale, self.same_on_batch, self.device, self.dtype)+ distortion_scale, self.same_on_batch, self.device, self.dtype)def compute_transformation(self, input: torch.Tensor, params: Dict[str, torch.Tensor]) -> torch.Tensor:return F.compute_perspective_transformation3d(input, params)diff --git a/kornia/augmentation/functional/functional.py b/kornia/augmentation/functional/functional.pyindex 097b99001..956f33bf2 100644--- a/kornia/augmentation/functional/functional.py+++ b/kornia/augmentation/functional/functional.py@@ -10,6 +10,7 @@ from kornia.geometry import (warp_perspective,rotate,crop_by_boxes,+ bbox_generator,warp_affine,hflip,vflip,@@ -273,12 +274,14 @@ def compute_hflip_transformation(input: torch.Tensor) -> torch.Tensor:Returns:torch.Tensor: The applied transformation matrix :math: `(*, 3, 3)`"""+ _validate_input_dtype(input, accepted_dtypes=[torch.float16, torch.float32, torch.float64])+w: int = input.shape[-1]flip_mat: torch.Tensor = torch.tensor([[-1, 0, w - 1],[0, 1, 0],- [0, 0, 1]])+ [0, 0, 1]], device=input.device, dtype=input.dtype)- return flip_mat.repeat(input.size(0), 1, 1).type_as(input)+ return flip_mat.repeat(input.size(0), 1, 1)@_validate_input@@ -312,9 +315,9 @@ def compute_vflip_transformation(input: torch.Tensor) -> torch.Tensor:h: int = input.shape[-2]flip_mat: torch.Tensor = torch.tensor([[1, 0, 0],[0, -1, h - 1],- [0, 0, 1]])+ [0, 0, 1]], device=input.device, dtype=input.dtype)- return flip_mat.repeat(input.size(0), 1, 1).type_as(input)+ return flip_mat.repeat(input.size(0), 1, 1)@_validate_input@@ -643,22 +646,13 @@ def apply_erase_rectangles(input: torch.Tensor, params: Dict[str, torch.Tensor])f"and ({params['xs'].size()}, {params['ys'].size()})")- mask = torch.zeros(input.size()).type_as(input)- values = torch.zeros(input.size()).type_as(input)-- widths = params['widths']- heights = params['heights']- xs = params['xs']- ys = params['ys']- vs = params['values']- for i_elem in range(input.size()[0]):- h = widths[i_elem].item()- w = heights[i_elem].item()- y = ys[i_elem].item()- x = xs[i_elem].item()- v = vs[i_elem].item()- mask[i_elem, :, int(y):int(y + w), int(x):int(x + h)] = 1.- values[i_elem, :, int(y):int(y + w), int(x):int(x + h)] = v+ values = params['values'].unsqueeze(-1).unsqueeze(-1).unsqueeze(-1).repeat(1, *input.shape[1:]).to(input)++ _, c, h, w = input.size()++ bboxes = bbox_generator(params['xs'], params['ys'], params['widths'], params['heights'])+ mask = bbox_to_mask(bboxes, w, h) # Returns B, H, W+ mask = mask.unsqueeze(1).repeat(1, c, 1, 1).to(input) # Transform to B, c, H, Wtransformed = torch.where(mask == 1., values, input)return transformed@@ -795,8 +789,9 @@ def apply_motion_blur(input: torch.Tensor, params: Dict[str, torch.Tensor],angle = params['angle_factor']direction = params['direction_factor']border_type: str = cast(str, BorderType(flags['border_type'].item()).name.lower())+ mode: str = cast(str, Resample(flags['interpolation'].item()).name.lower())- return motion_blur(input, kernel_size, angle, direction, border_type)+ return motion_blur(input, kernel_size, angle, direction, border_type, mode)@_validate_inputdiff --git a/kornia/augmentation/functional/functional3d.py b/kornia/augmentation/functional/functional3d.pyindex 6376aa19b..e1645ed4d 100644--- a/kornia/augmentation/functional/functional3d.py+++ b/kornia/augmentation/functional/functional3d.py@@ -391,8 +391,9 @@ def apply_motion_blur3d(input: torch.Tensor, params: Dict[str, torch.Tensor],angle = params['angle_factor']direction = params['direction_factor']border_type: str = cast(str, BorderType(flags['border_type'].item()).name.lower())+ mode: str = cast(str, Resample(flags['interpolation'].item()).name.lower())- return motion_blur3d(input, kernel_size, angle, direction, border_type)+ return motion_blur3d(input, kernel_size, angle, direction, border_type, mode)def apply_crop3d(input: torch.Tensor, params: Dict[str, torch.Tensor], flags: Dict[str, torch.Tensor]) -> torch.Tensor:diff --git a/kornia/augmentation/mix_augmentation.py b/kornia/augmentation/mix_augmentation.pyindex e1227f143..b077cccf7 100644--- a/kornia/augmentation/mix_augmentation.py+++ b/kornia/augmentation/mix_augmentation.py@@ -83,18 +83,19 @@ class RandomMixUp(MixAugmentationBase):def __init__(self, lambda_val: Optional[Union[torch.Tensor, Tuple[float, float]]] = None,same_on_batch: bool = False, p: float = 1.0, keepdim: bool = False) -> None:super(RandomMixUp, self).__init__(p=1., p_batch=p, same_on_batch=same_on_batch, keepdim=keepdim)- 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.lambda_val = lambda_valdef __repr__(self) -> str:repr = f"lambda_val={self.lambda_val}"return self.__class__.__name__ + f"({repr}, {super().__repr__()})"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)+ if self.lambda_val is None:+ lambda_val = torch.tensor([0., 1.], device=self.device, dtype=self.dtype)+ else:+ lambda_val = cast(torch.Tensor, self.lambda_val) if isinstance(self.lambda_val, torch.Tensor) else \+ torch.tensor(self.lambda_val, device=self.device, dtype=self.dtype)+ return rg.random_mixup_generator(batch_shape[0], self.p, lambda_val, same_on_batch=self.same_on_batch)def apply_transform(self, input: torch.Tensor, label: torch.Tensor, # type: ignoreparams: Dict[str, torch.Tensor]) -> Tuple[torch.Tensor, torch.Tensor]: # type: ignore@@ -186,24 +187,27 @@ class RandomCutMix(MixAugmentationBase):self.height = heightself.width = widthself.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.beta = beta+ self.cut_size = cut_sizedef __repr__(self) -> str:- repr = f"num_mix={self.num_mix}, beta={self.beta}, cut_size={self.cut_size}, "- f"height={self.height}, width={self.width}"+ repr = (f"num_mix={self.num_mix}, beta={self.beta}, cut_size={self.cut_size}, "+ f"height={self.height}, width={self.width}")return self.__class__.__name__ + f"({repr}, {super().__repr__()})"def generate_parameters(self, batch_shape: torch.Size) -> Dict[str, torch.Tensor]:+ if self.beta is None:+ beta = torch.tensor(1., device=self.device, dtype=self.dtype)+ else:+ beta = cast(torch.Tensor, self.beta) if isinstance(self.beta, torch.Tensor) else \+ torch.tensor(self.beta, device=self.device, dtype=self.dtype)+ if self.cut_size is None:+ cut_size = torch.tensor([0., 1.], device=self.device, dtype=self.dtype)+ else:+ cut_size = cast(torch.Tensor, self.cut_size) if isinstance(self.cut_size, torch.Tensor) else \+ torch.tensor(self.cut_size, device=self.device, dtype=self.dtype)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,+ cut_size=cut_size, num_mix=self.num_mix, beta=beta,same_on_batch=self.same_on_batch)def apply_transform(self, input: torch.Tensor, label: torch.Tensor, # type: ignorediff --git a/kornia/augmentation/random_generator/random_generator.py b/kornia/augmentation/random_generator/random_generator.pyindex 925b076dc..49a8848f5 100644--- a/kornia/augmentation/random_generator/random_generator.py+++ b/kornia/augmentation/random_generator/random_generator.py@@ -344,44 +344,46 @@ def random_crop_generator(>>> _ = torch.manual_seed(0)>>> crop_size = torch.tensor([[25, 28], [27, 29], [26, 28]])>>> random_crop_generator(3, (30, 30), size=crop_size, same_on_batch=False)- {'src': tensor([[[ 1, 0],- [28, 0],- [28, 24],- [ 1, 24]],+ {'src': tensor([[[ 1., 0.],+ [28., 0.],+ [28., 24.],+ [ 1., 24.]],<BLANKLINE>- [[ 1, 1],- [29, 1],- [29, 27],- [ 1, 27]],+ [[ 1., 1.],+ [29., 1.],+ [29., 27.],+ [ 1., 27.]],<BLANKLINE>- [[ 0, 3],- [27, 3],- [27, 28],- [ 0, 28]]]), 'dst': tensor([[[ 0, 0],- [27, 0],- [27, 24],- [ 0, 24]],+ [[ 0., 3.],+ [27., 3.],+ [27., 28.],+ [ 0., 28.]]]), 'dst': tensor([[[ 0., 0.],+ [27., 0.],+ [27., 24.],+ [ 0., 24.]],<BLANKLINE>- [[ 0, 0],- [28, 0],- [28, 26],- [ 0, 26]],+ [[ 0., 0.],+ [28., 0.],+ [28., 26.],+ [ 0., 26.]],<BLANKLINE>- [[ 0, 0],- [27, 0],- [27, 25],- [ 0, 25]]])}+ [[ 0., 0.],+ [27., 0.],+ [27., 25.],+ [ 0., 25.]]])}"""_common_param_check(batch_size, same_on_batch)_device, _dtype = _extract_device_dtype([size if isinstance(size, torch.Tensor) else None])+ # Use float point instead+ _dtype = _dtype if _dtype in [torch.float16, torch.float32, torch.float64] else dtypeif not isinstance(size, torch.Tensor):- size = torch.tensor(size, device=device, dtype=dtype).repeat(batch_size, 1)+ size = torch.tensor(size, device=_device, dtype=_dtype).repeat(batch_size, 1)else:- size = size.to(device=device, dtype=dtype)+ size = size.to(device=_device, dtype=_dtype)assert size.shape == torch.Size([batch_size, 2]), ("If `size` is a tensor, it must be shaped as (B, 2). "f"Got {size.shape} while expecting {torch.Size([batch_size, 2])}.")- size = size.long()+ size = size.floor()x_diff = input_size[1] - size[:, 1] + 1y_diff = input_size[0] - size[:, 0] + 1@@ -392,25 +394,29 @@ def random_crop_generator(if batch_size == 0:return dict(- src=torch.zeros([0, 4, 2], device=_device, dtype=torch.long),- dst=torch.zeros([0, 4, 2], device=_device, dtype=torch.long),+ src=torch.zeros([0, 4, 2], device=_device, dtype=_dtype),+ dst=torch.zeros([0, 4, 2], device=_device, dtype=_dtype),)if same_on_batch:# If same_on_batch, select the first then repeat.- x_start = _adapted_uniform((batch_size,), 0, x_diff[0].to(device=device, dtype=dtype), same_on_batch).long()- y_start = _adapted_uniform((batch_size,), 0, y_diff[0].to(device=device, dtype=dtype), same_on_batch).long()+ x_start = _adapted_uniform((batch_size,), 0, x_diff[0].to(device=device, dtype=dtype), same_on_batch).floor()+ y_start = _adapted_uniform((batch_size,), 0, y_diff[0].to(device=device, dtype=dtype), same_on_batch).floor()else:- x_start = _adapted_uniform((1,), 0, x_diff.to(device=device, dtype=dtype), same_on_batch).long()- y_start = _adapted_uniform((1,), 0, y_diff.to(device=device, dtype=dtype), same_on_batch).long()+ x_start = _adapted_uniform((1,), 0, x_diff.to(device=device, dtype=dtype), same_on_batch).floor()+ y_start = _adapted_uniform((1,), 0, y_diff.to(device=device, dtype=dtype), same_on_batch).floor()crop_src = bbox_generator(- x_start.view(-1), y_start.view(-1), size[:, 1], size[:, 0]).to(device=_device, dtype=torch.long)+ x_start.view(-1).to(device=_device, dtype=_dtype),+ y_start.view(-1).to(device=_device, dtype=_dtype),+ size[:, 1].to(device=_device, dtype=_dtype),+ size[:, 0].to(device=_device, dtype=_dtype))if resize_to is None:crop_dst = bbox_generator(- torch.tensor([0] * batch_size, device=device, dtype=torch.long),- torch.tensor([0] * batch_size, device=device, dtype=torch.long),- size[:, 1], size[:, 0]).to(device=_device, dtype=torch.long)+ torch.tensor([0] * batch_size, device=_device, dtype=_dtype),+ torch.tensor([0] * batch_size, device=_device, dtype=_dtype),+ size[:, 1].to(device=_device, dtype=_dtype),+ size[:, 0].to(device=_device, dtype=_dtype))else:assert len(resize_to) == 2 and isinstance(resize_to[0], (int,)) and isinstance(resize_to[1], (int,)) \and resize_to[0] > 0 and resize_to[1] > 0, \@@ -420,7 +426,7 @@ def random_crop_generator([resize_to[1] - 1, 0],[resize_to[1] - 1, resize_to[0] - 1],[0, resize_to[0] - 1],- ]], device=_device, dtype=torch.long).repeat(batch_size, 1, 1)+ ]], device=_device, dtype=_dtype).repeat(batch_size, 1, 1)return dict(src=crop_src,dst=crop_dst)@@ -456,9 +462,9 @@ def random_crop_size_generator(Examples:>>> _ = torch.manual_seed(42)>>> random_crop_size_generator(3, (30, 30), scale=torch.tensor([.7, 1.3]), ratio=torch.tensor([.9, 1.]))- {'size': tensor([[29, 29],- [27, 28],- [26, 29]])}+ {'size': tensor([[29., 29.],+ [27., 28.],+ [26., 29.]])}"""_common_param_check(batch_size, same_on_batch)_joint_range_check(scale, "scale")@@ -480,8 +486,8 @@ def random_crop_size_generator((batch_size, 10), torch.log(ratio[0]), torch.log(ratio[1]), same_on_batch)aspect_ratio = torch.exp(log_ratio)- w = torch.sqrt(area * aspect_ratio).round().int()- h = torch.sqrt(area / aspect_ratio).round().int()+ w = torch.sqrt(area * aspect_ratio).round().floor()+ h = torch.sqrt(area / aspect_ratio).round().floor()# Element-wise w, h conditioncond = ((0 < w) * (w < size[1]) * (0 < h) * (h < size[0])).int()@@ -503,13 +509,13 @@ def random_crop_size_generator(else: # whole imageh_ct = torch.tensor(size[0], device=device, dtype=dtype)w_ct = torch.tensor(size[1], device=device, dtype=dtype)- h_ct = h_ct.int()- w_ct = w_ct.int()+ h_ct = h_ct.floor()+ w_ct = w_ct.floor()h_out = h_out.where(cond_bool, h_ct)w_out = w_out.where(cond_bool, w_ct)- return dict(size=torch.stack([h_out, w_out], dim=1).to(device=_device, dtype=torch.long))+ return dict(size=torch.stack([h_out, w_out], dim=1).to(device=_device, dtype=_dtype))def random_rectangles_params_generator(@@ -559,6 +565,7 @@ def random_rectangles_params_generator(images_area = height * widthtarget_areas = _adapted_uniform((batch_size,), scale[0].to(device=device, dtype=dtype),scale[1].to(device=device, dtype=dtype), same_on_batch) * images_area+if ratio[0] < 1. and ratio[1] > 1.:aspect_ratios1 = _adapted_uniform((batch_size,), ratio[0].to(device=device, dtype=dtype), 1, same_on_batch)aspect_ratios2 = _adapted_uniform((batch_size,), 1, ratio[1].to(device=device, dtype=dtype), same_on_batch)@@ -597,10 +604,10 @@ def random_rectangles_params_generator(xs = xs_ratio * (torch.tensor(width, device=device, dtype=dtype) - widths + 1)ys = ys_ratio * (torch.tensor(height, device=device, dtype=dtype) - heights + 1)- return dict(widths=widths.to(device=_device, dtype=torch.int32),- heights=heights.to(device=_device, dtype=torch.int32),- xs=xs.to(device=_device, dtype=torch.int32),- ys=ys.to(device=_device, dtype=torch.int32),+ return dict(widths=widths.floor().to(device=_device, dtype=_dtype),+ heights=heights.floor().to(device=_device, dtype=_dtype),+ xs=xs.floor().to(device=_device, dtype=_dtype),+ ys=ys.floor().to(device=_device, dtype=_dtype),values=torch.tensor([value] * batch_size, device=_device, dtype=_dtype))@@ -947,36 +954,36 @@ def random_cutmix_generator(>>> 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([[[[ 35, 25],- [208, 25],- [208, 198],- [ 35, 198]],+ [1, 2, 0]]), 'crop_src': tensor([[[[ 35., 25.],+ [208., 25.],+ [208., 198.],+ [ 35., 198.]],<BLANKLINE>- [[156, 137],- [155, 137],- [155, 136],- [156, 136]],+ [[156., 137.],+ [155., 137.],+ [155., 136.],+ [156., 136.]],<BLANKLINE>- [[ 3, 12],- [210, 12],- [210, 219],- [ 3, 219]]],+ [[ 3., 12.],+ [210., 12.],+ [210., 219.],+ [ 3., 219.]]],<BLANKLINE><BLANKLINE>- [[[ 83, 125],- [177, 125],- [177, 219],- [ 83, 219]],+ [[[ 83., 125.],+ [177., 125.],+ [177., 219.],+ [ 83., 219.]],<BLANKLINE>- [[ 54, 8],- [205, 8],- [205, 159],- [ 54, 159]],+ [[ 54., 8.],+ [205., 8.],+ [205., 159.],+ [ 54., 159.]],<BLANKLINE>- [[ 97, 70],- [ 96, 70],- [ 96, 69],- [ 97, 69]]]])}+ [[ 97., 70.],+ [ 96., 70.],+ [ 96., 69.],+ [ 97., 69.]]]])}"""_device, _dtype = _extract_device_dtype([beta, cut_size])beta = torch.as_tensor(1. if beta is None else beta, device=device, dtype=dtype)@@ -1003,8 +1010,8 @@ def random_cutmix_generator(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()+ cut_height = (cutmix_rate * height).floor().to(device=device, dtype=_dtype)+ cut_width = (cutmix_rate * width).floor().to(device=device, dtype=_dtype)_gen_shape = (1,)if same_on_batch:@@ -1015,10 +1022,12 @@ def random_cutmix_generator(# Reserve at least 1 pixel for cropping.x_start = _adapted_uniform(_gen_shape, torch.zeros_like(cut_width, device=device, dtype=dtype),- (width - cut_width - 1).to(device=device, dtype=dtype), same_on_batch).to(device=device, dtype=torch.long)+ (width - cut_width - 1).to(device=device, dtype=dtype), same_on_batch+ ).floor().to(device=device, dtype=_dtype)y_start = _adapted_uniform(_gen_shape, torch.zeros_like(cut_height, device=device, dtype=dtype),- (height - cut_height - 1).to(device=device, dtype=dtype), same_on_batch).to(device=device, dtype=torch.long)+ (height - cut_height - 1).to(device=device, dtype=dtype), same_on_batch+ ).floor().to(device=device, dtype=_dtype)crop_src = bbox_generator(x_start.squeeze(), y_start.squeeze(), cut_width, cut_height)@@ -1027,5 +1036,5 @@ def random_cutmix_generator(return dict(mix_pairs=mix_pairs.to(device=_device, dtype=torch.long),- crop_src=crop_src.to(device=_device, dtype=torch.long)+ crop_src=crop_src.floor().to(device=_device, dtype=_dtype))diff --git a/kornia/augmentation/random_generator/random_generator3d.py b/kornia/augmentation/random_generator/random_generator3d.pyindex b31e199fd..52d9720e2 100644--- a/kornia/augmentation/random_generator/random_generator3d.py+++ b/kornia/augmentation/random_generator/random_generator3d.py@@ -372,30 +372,30 @@ def random_crop_generator3d(if same_on_batch:# If same_on_batch, select the first then repeat.- x_start = _adapted_uniform((batch_size,), 0, x_diff[0], same_on_batch)- y_start = _adapted_uniform((batch_size,), 0, y_diff[0], same_on_batch)- z_start = _adapted_uniform((batch_size,), 0, z_diff[0], same_on_batch)+ x_start = _adapted_uniform((batch_size,), 0, x_diff[0], same_on_batch).floor()+ y_start = _adapted_uniform((batch_size,), 0, y_diff[0], same_on_batch).floor()+ z_start = _adapted_uniform((batch_size,), 0, z_diff[0], same_on_batch).floor()else:- x_start = _adapted_uniform((1,), 0, x_diff, same_on_batch)- y_start = _adapted_uniform((1,), 0, y_diff, same_on_batch)- z_start = _adapted_uniform((1,), 0, z_diff, same_on_batch)+ x_start = _adapted_uniform((1,), 0, x_diff, same_on_batch).floor()+ y_start = _adapted_uniform((1,), 0, y_diff, same_on_batch).floor()+ z_start = _adapted_uniform((1,), 0, z_diff, same_on_batch).floor()crop_src = bbox_generator3d(- x_start.view(-1),- y_start.view(-1),- z_start.view(-1),- size[:, 2] - 1,- size[:, 1] - 1,- size[:, 0] - 1).long()+ x_start.to(device=_device, dtype=_dtype).view(-1),+ y_start.to(device=_device, dtype=_dtype).view(-1),+ z_start.to(device=_device, dtype=_dtype).view(-1),+ size[:, 2].to(device=_device, dtype=_dtype) - 1,+ size[:, 1].to(device=_device, dtype=_dtype) - 1,+ size[:, 0].to(device=_device, dtype=_dtype) - 1)if resize_to is None:crop_dst = bbox_generator3d(- torch.tensor([0] * batch_size, device=device, dtype=dtype),- torch.tensor([0] * batch_size, device=device, dtype=dtype),- torch.tensor([0] * batch_size, device=device, dtype=dtype),- size[:, 2] - 1,- size[:, 1] - 1,- size[:, 0] - 1).long()+ torch.tensor([0] * batch_size, device=_device, dtype=_dtype),+ torch.tensor([0] * batch_size, device=_device, dtype=_dtype),+ torch.tensor([0] * batch_size, device=_device, dtype=_dtype),+ size[:, 2].to(device=_device, dtype=_dtype) - 1,+ size[:, 1].to(device=_device, dtype=_dtype) - 1,+ size[:, 0].to(device=_device, dtype=_dtype) - 1)else:assert len(resize_to) == 3 and isinstance(resize_to[0], (int,)) and isinstance(resize_to[1], (int,)) \and isinstance(resize_to[2], (int,)) and resize_to[0] > 0 and resize_to[1] > 0 and resize_to[2] > 0, \@@ -409,7 +409,7 @@ def random_crop_generator3d([resize_to[-1] - 1, 0, resize_to[-3] - 1],[resize_to[-1] - 1, resize_to[-2] - 1, resize_to[-3] - 1],[0, resize_to[-2] - 1, resize_to[-3] - 1],- ]], device=device, dtype=torch.long).repeat(batch_size, 1, 1)+ ]], device=_device, dtype=_dtype).repeat(batch_size, 1, 1)return dict(src=crop_src.to(device=_device),dst=crop_dst.to(device=_device))diff --git a/kornia/augmentation/utils/helpers.py b/kornia/augmentation/utils/helpers.pyindex 213cb842c..2bc1d98ff 100644--- a/kornia/augmentation/utils/helpers.py+++ b/kornia/augmentation/utils/helpers.py@@ -272,42 +272,5 @@ def _adapted_beta(return _adapted_rsampling(shape, dist, same_on_batch)-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/augmentation/utils/param_validation.py b/kornia/augmentation/utils/param_validation.pyindex a8884ccd3..ec12f9967 100644--- a/kornia/augmentation/utils/param_validation.py+++ b/kornia/augmentation/utils/param_validation.py@@ -26,8 +26,8 @@ def _range_bound(factor: Union[torch.Tensor, float, Tuple[float, float], List[fl# Should be something other than clamp# Currently, single value factor will not out of scope as long as the user provided it.# Note: I personally think throw an error will be better than a coarse clamp.- factor_bound = torch.tensor(- [center - factor, center + factor], device=device, dtype=dtype).clamp(bounds[0], bounds[1])+ factor_bound = factor.repeat(2) * torch.tensor([-1., 1.], device=factor.device, dtype=factor.dtype) + center+ factor_bound = factor_bound.clamp(bounds[0], bounds[1])else:factor_bound = torch.as_tensor(factor, device=device, dtype=dtype)@@ -84,7 +84,9 @@ def _singular_range_check(ranged_factor: torch.Tensor, name: str, bounds: Optiondef _tuple_range_reader(input_range: Union[torch.Tensor, float, tuple],- target_size: int+ target_size: int,+ device: Optional[torch.device] = None,+ dtype: Optional[torch.dtype] = None) -> torch.Tensor:"""Given target_size, it will generate the corresponding (target_size, 2) range tensor for element-wise params.@@ -101,42 +103,43 @@ def _tuple_range_reader(if isinstance(input_range, (float, int)):if input_range < 0:raise ValueError(f"If input_range is only one number it must be a positive number. Got{input_range}")- input_range_tmp = torch.tensor([-input_range, input_range]).repeat(target_shape[0], 1).to(torch.float32)+ input_range_tmp = torch.tensor(+ [-input_range, input_range], device=device, dtype=dtype).repeat(target_shape[0], 1)- elif isinstance(input_range, (tuple)) and len(input_range) == 2 \+ elif isinstance(input_range, (tuple, list)) and len(input_range) == 2 \and isinstance(input_range[0], (float, int)) and isinstance(input_range[1], (float, int)):- input_range_tmp = torch.tensor(input_range).repeat(target_shape[0], 1).to(torch.float32)+ input_range_tmp = torch.tensor(+ input_range, device=device, dtype=dtype).repeat(target_shape[0], 1)- elif isinstance(input_range, (tuple)) and len(input_range) == target_shape[0] \+ elif isinstance(input_range, (tuple, list)) and len(input_range) == target_shape[0] \and all([isinstance(x, (float, int)) for x in input_range]):- input_range_tmp = torch.tensor([(-s, s) for s in input_range]).to(torch.float32)+ input_range_tmp = torch.tensor([(-s, s) for s in input_range], device=device, dtype=dtype)- elif isinstance(input_range, (tuple)) and len(input_range) == target_shape[0] \- and all([isinstance(x, (tuple)) for x in input_range]):- input_range_tmp = torch.tensor(input_range).to(torch.float32)+ elif isinstance(input_range, (tuple, list)) and len(input_range) == target_shape[0] \+ and all([isinstance(x, (tuple, list)) for x in input_range]):+ input_range_tmp = torch.tensor(input_range, device=device, dtype=dtype)else:raise TypeError(- "If not pass a tensor, it must be float, (float, float) for isotropic operation or a tuple of"+ "If not pass a tensor, it must be float, (float, float) for isotropic operation or a tuple of "f"{target_size} floats or {target_size} (float, float) for independent operation. Got {input_range}.")else:# https://mypy.readthedocs.io/en/latest/casts.html cast to please mypy godsinput_range = cast(torch.Tensor, input_range)- if len(input_range.shape) == 0:+ if (len(input_range.shape) == 0) or (len(input_range.shape) == 1 and len(input_range) == 1):if input_range < 0:raise ValueError(f"If input_range is only one number it must be a positive number. Got{input_range}")- input_range_tmp = torch.tensor([-input_range, input_range], dtype=torch.float32).repeat(target_shape[0], 1)-- elif len(input_range.shape) == 1 and len(input_range) == 1:- input_range_tmp = torch.tensor([-input_range[0], input_range[0]], dtype=torch.float32).repeat(- target_shape[0], 1)+ input_range_tmp = input_range.repeat(2) * torch.tensor(+ [-1., 1.], device=input_range.device, dtype=input_range.dtype)+ input_range_tmp = input_range_tmp.repeat(target_shape[0], 1)elif len(input_range.shape) == 1 and len(input_range) == 2:input_range_tmp = input_range.repeat(target_shape[0], 1)elif len(input_range.shape) == 1 and len(input_range) == target_shape[0]:- input_range_tmp = torch.tensor([(-s, s) for s in input_range], dtype=torch.float32)+ input_range_tmp = input_range.unsqueeze(1).repeat(1, 2) * torch.tensor(+ [-1, 1], device=input_range.device, dtype=input_range.dtype)elif input_range.shape == target_shape:input_range_tmp = input_rangediff --git a/kornia/filters/kernels.py b/kornia/filters/kernels.pyindex 910219b75..3cec6073e 100644--- a/kornia/filters/kernels.py+++ b/kornia/filters/kernels.py@@ -607,7 +607,7 @@ def get_laplacian_kernel2d(kernel_size: int) -> torch.Tensor:def get_motion_kernel2d(kernel_size: int, angle: Union[torch.Tensor, float],- direction: Union[torch.Tensor, float] = 0.) -> torch.Tensor:+ direction: Union[torch.Tensor, float] = 0., mode: str = 'nearest') -> torch.Tensor:r"""Return 2D motion blur filter.Args:@@ -617,6 +617,8 @@ def get_motion_kernel2d(kernel_size: int, angle: Union[torch.Tensor, float],Lower values towards -1.0 will point the motion blur towards the back (with angle provided via angle),while higher values towards 1.0 will point the motion blur forward. A value of 0.0 leads to auniformly (but still angled) motion blur.+ mode (str): interpolation mode for rotating the kernel. ``'bilinear'`` or ``'nearest'``.+ Default: ``'nearest'``Returns:torch.Tensor: the motion blur kernel.@@ -666,22 +668,28 @@ def get_motion_kernel2d(kernel_size: int, angle: Union[torch.Tensor, float],kernel_tuple: Tuple[int, int] = (kernel_size, kernel_size)# direction from [-1, 1] to [0, 1] rangedirection = (torch.clamp(direction, -1., 1.) + 1.) / 2.- kernel = torch.zeros((direction.size(0), *kernel_tuple), device=device, dtype=dtype)+ # kernel = torch.zeros((direction.size(0), *kernel_tuple), device=device, dtype=dtype)# Element-wise linspace- kernel[:, kernel_size // 2, :] = torch.stack(+ # kernel[:, kernel_size // 2, :] = torch.stack(+ # [(direction + ((1 - 2 * direction) / (kernel_size - 1)) * i) for i in range(kernel_size)], dim=-1)+ # Alternatively+ # m = ((1 - 2 * direction)[:, None].repeat(1, kernel_size) / (kernel_size - 1))+ # kernel[:, kernel_size // 2, :] = direction[:, None].repeat(1, kernel_size) + m * torch.arange(0, kernel_size)+ k = torch.stack([(direction + ((1 - 2 * direction) / (kernel_size - 1)) * i) for i in range(kernel_size)], dim=-1)+ kernel = torch.nn.functional.pad(k[:, None], [0, 0, kernel_size // 2, kernel_size // 2, 0, 0])+ assert kernel.shape == torch.Size([direction.size(0), *kernel_tuple])kernel = kernel.unsqueeze(1)# rotate (counterclockwise) kernel by given angle- kernel = rotate(kernel, angle, mode='nearest', align_corners=True)+ kernel = rotate(kernel, angle, mode=mode, align_corners=True)kernel = kernel[:, 0]kernel = kernel / kernel.sum(dim=(1, 2), keepdim=True)-return kerneldef get_motion_kernel3d(kernel_size: int, angle: Union[torch.Tensor, Tuple[float, float, float]],- direction: Union[torch.Tensor, float] = 0.) -> torch.Tensor:+ direction: Union[torch.Tensor, float] = 0., mode: str = 'nearest') -> torch.Tensor:r"""Return 3D motion blur filter.Args:@@ -693,6 +701,8 @@ def get_motion_kernel3d(kernel_size: int, angle: Union[torch.Tensor, Tuple[floatLower values towards -1.0 will point the motion blur towards the back (with angle provided via angle),while higher values towards 1.0 will point the motion blur forward. A value of 0.0 leads to auniformly (but still angled) motion blur.+ mode (str): interpolation mode for rotating the kernel. ``'bilinear'`` or ``'nearest'``.+ Default: ``'nearest'``.Returns:torch.Tensor: the motion blur kernel.@@ -759,11 +769,16 @@ def get_motion_kernel3d(kernel_size: int, angle: Union[torch.Tensor, Tuple[floatkernel = torch.zeros((direction.size(0), *kernel_tuple), device=device, dtype=dtype)# Element-wise linspace- kernel[:, kernel_size // 2, kernel_size // 2, :] = torch.stack(+ # kernel[:, kernel_size // 2, kernel_size // 2, :] = torch.stack(+ # [(direction + ((1 - 2 * direction) / (kernel_size - 1)) * i) for i in range(kernel_size)], dim=-1)+ k = torch.stack([(direction + ((1 - 2 * direction) / (kernel_size - 1)) * i) for i in range(kernel_size)], dim=-1)+ kernel = torch.nn.functional.pad(+ k[:, None, None], [0, 0, kernel_size // 2, kernel_size // 2, kernel_size // 2, kernel_size // 2, 0, 0])+ assert kernel.shape == torch.Size([direction.size(0), *kernel_tuple])kernel = kernel.unsqueeze(1)# rotate (counterclockwise) kernel by given angle- kernel = rotate3d(kernel, angle[:, 0], angle[:, 1], angle[:, 2], mode='nearest', align_corners=True)+ kernel = rotate3d(kernel, angle[:, 0], angle[:, 1], angle[:, 2], mode=mode, align_corners=True)kernel = kernel[:, 0]kernel = kernel / kernel.sum(dim=(1, 2, 3), keepdim=True)diff --git a/kornia/filters/motion.py b/kornia/filters/motion.pyindex 97c46044b..aa3a283c8 100644--- a/kornia/filters/motion.py+++ b/kornia/filters/motion.py@@ -107,7 +107,8 @@ def motion_blur(kernel_size: int,angle: Union[float, torch.Tensor],direction: Union[float, torch.Tensor],- border_type: str = 'constant'+ border_type: str = 'constant',+ mode: str = 'nearest') -> torch.Tensor:r"""Perform motion blur on 2D images (4D tensor).@@ -123,6 +124,8 @@ def motion_blur(If tensor, it must be :math:`(B,)`.border_type (str): the padding mode to be applied before convolving. The expected modes are:``'constant'``, ``'reflect'``, ``'replicate'`` or ``'circular'``. Default: ``'constant'``.+ mode (str): interpolation mode for rotating the kernel. ``'bilinear'`` or ``'nearest'``.+ Default: ``'nearest'``Return:torch.Tensor: the blurred image with shape :math:`(B, C, H, W)`.@@ -139,7 +142,7 @@ def motion_blur(False"""assert border_type in ["constant", "reflect", "replicate", "circular"]- kernel: torch.Tensor = get_motion_kernel2d(kernel_size, angle, direction)+ kernel: torch.Tensor = get_motion_kernel2d(kernel_size, angle, direction, mode)return kornia.filter2D(input, kernel, border_type)@@ -148,7 +151,8 @@ def motion_blur3d(kernel_size: int,angle: Union[Tuple[float, float, float], torch.Tensor],direction: Union[float, torch.Tensor],- border_type: str = 'constant'+ border_type: str = 'constant',+ mode: str = 'nearest') -> torch.Tensor:r"""Perform motion blur on 3D volumes (5D tensor).@@ -164,6 +168,8 @@ def motion_blur3d(If tensor, it must be :math:`(B,)`.border_type (str): the padding mode to be applied before convolving. The expected modes are:``'constant'``, ``'reflect'``, ``'replicate'`` or ``'circular'``. Default: ``'constant'``.+ mode (str): interpolation mode for rotating the kernel. ``'bilinear'`` or ``'nearest'``.+ Default: ``'nearest'``Return:torch.Tensor: the blurred image with shape :math:`(B, C, D, H, W)`.@@ -180,5 +186,5 @@ def motion_blur3d(False"""assert border_type in ["constant", "reflect", "replicate", "circular"]- kernel: torch.Tensor = get_motion_kernel3d(kernel_size, angle, direction)+ kernel: torch.Tensor = get_motion_kernel3d(kernel_size, angle, direction, mode)return kornia.filter3D(input, kernel, border_type)diff --git a/kornia/geometry/transform/crop/crop2d.py b/kornia/geometry/transform/crop/crop2d.pyindex 95824013f..e579605e5 100644--- a/kornia/geometry/transform/crop/crop2d.py+++ b/kornia/geometry/transform/crop/crop2d.py@@ -299,6 +299,9 @@ def bbox_to_mask(boxes: torch.Tensor, width: int, height: int) -> torch.Tensor:Returns:torch.Tensor: the output mask tensor.+ Note:+ It is currently non-differentiable.+Examples:>>> boxes = torch.tensor([[... [1., 1.],@@ -314,7 +317,11 @@ def bbox_to_mask(boxes: torch.Tensor, width: int, height: int) -> torch.Tensor:[0., 0., 0., 0., 0.]]])"""validate_bboxes(boxes)- mask = torch.zeros((len(boxes), height, width))+ # zero padding the surroudings+ mask = torch.zeros((len(boxes), height + 2, width + 2))+ # push all points one pixel off+ # in order to zero-out the fully filled rows or columns+ boxes += 1mask_out = []# TODO: Looking for a vectorized way@@ -323,6 +330,7 @@ def bbox_to_mask(boxes: torch.Tensor, width: int, height: int) -> torch.Tensor: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+ m_out = m_out[1:-1, 1:-1]mask_out.append(m_out)return torch.stack(mask_out, dim=0).float()diff --git a/kornia/utils/helpers.py b/kornia/utils/helpers.pyindex 89e284854..21d86a55a 100644--- a/kornia/utils/helpers.py+++ b/kornia/utils/helpers.py@@ -1,10 +1,10 @@-from typing import Tuple, Union, List, cast, Optional+from typing import Tuple, Union, List, Any, Optionalimport torch-def _extract_device_dtype(tensor_list: List[Optional[torch.Tensor]]) -> Tuple[torch.device, torch.dtype]:- """Check if all the input tensors are in the same device.+def _extract_device_dtype(tensor_list: List[Optional[Any]]) -> Tuple[torch.device, torch.dtype]:+ """Check if all the input are in the same device (only if when they are torch.Tensor).If so, it would return a tuple of (device, dtype). Default: (cpu, ``get_default_dtype()``).@@ -15,7 +15,7 @@ def _extract_device_dtype(tensor_list: List[Optional[torch.Tensor]]) -> Tuple[tofor tensor in tensor_list:if tensor is not None:if not isinstance(tensor, (torch.Tensor,)):- raise ValueError(f"Expected None or Tensor. Got {tensor}.")+ continue_device = tensor.device_dtype = tensor.dtypeif device is None and dtype is None:diff --git a/test/augmentation/test_augmentation.py b/test/augmentation/test_augmentation.pyindex a8df50ec0..086883b4b 100644--- a/test/augmentation/test_augmentation.py+++ b/test/augmentation/test_augmentation.py@@ -603,7 +603,6 @@ class TestRandomVerticalFlipAlternative(CommonTests):class TestRandomRotationAlternative(CommonTests):possible_params: Dict["str", Tuple] = {"degrees": (0., (-360., 360.), [0., 0.], torch.tensor((-180., 180))),- "interpolation": (0, Resample.BILINEAR.name, Resample.BILINEAR, None),"resample": (0, Resample.BILINEAR.name, Resample.BILINEAR),"align_corners": (False, True),}diff --git a/test/augmentation/test_augmentation_mix.py b/test/augmentation/test_augmentation_mix.pyindex ff0c09b31..80b8c489f 100644--- a/test/augmentation/test_augmentation_mix.py+++ b/test/augmentation/test_augmentation_mix.py@@ -16,7 +16,7 @@ class TestRandomMixUp:def test_smoke(self, device, dtype):f = RandomMixUp()- repr = "RandomMixUp(lambda_val=tensor([0., 1.]), p=1.0, p_batch=1.0, same_on_batch=False)"+ repr = "RandomMixUp(lambda_val=None, p=1.0, p_batch=1.0, same_on_batch=False)"assert str(f) == reprdef test_random_mixup_p1(self, device, dtype):@@ -107,7 +107,8 @@ class TestRandomCutMix:def test_smoke(self, device, dtype):f = RandomCutMix(width=3, height=3)- repr = "RandomCutMix(num_mix=1, beta=1.0, cut_size=tensor([0., 1.]), , p=1.0, p_batch=1.0, same_on_batch=False)"+ repr = ("RandomCutMix(num_mix=1, beta=None, cut_size=None, height=3, width=3, p=1.0, "+ "p_batch=1.0, same_on_batch=False)")assert str(f) == reprdef test_random_mixup_p1(self, device, dtype):diff --git a/test/augmentation/test_backward.py b/test/augmentation/test_backward.pynew file mode 100644index 000000000..f991e80e2--- /dev/null+++ b/test/augmentation/test_backward.py@@ -0,0 +1,433 @@+import pytest+import torch+import torch.nn as nn++from torch.testing import assert_allclose++from kornia.augmentation import (+ ColorJitter,+ RandomAffine,+ RandomErasing,+ RandomRotation,+ RandomPerspective,+ RandomSharpness,+ RandomResizedCrop,+ RandomMotionBlur+)+++class TestColorJitterBackward:++ @pytest.mark.parametrize("brightness", [0.8, torch.tensor(.8), torch.tensor([0.8, 1.2])])+ @pytest.mark.parametrize("contrast", [0.8, torch.tensor(.8), torch.tensor([0.8, 1.2])])+ @pytest.mark.parametrize("saturation", [0.8, torch.tensor(.8), torch.tensor([0.8, 1.2])])+ @pytest.mark.parametrize("hue", [0.1, torch.tensor(.1), torch.tensor([-0.1, 0.1])])+ @pytest.mark.parametrize("return_transform", [True, False])+ @pytest.mark.parametrize("same_on_batch", [True, False])+ def test_param(self, brightness, contrast, saturation, hue, return_transform, same_on_batch, device, dtype):+ count = 0++ _brightness = brightness if isinstance(brightness, (int, float)) else \+ nn.Parameter(brightness.clone().to(device=device, dtype=dtype))+ _contrast = contrast if isinstance(contrast, (int, float)) else \+ nn.Parameter(contrast.clone().to(device=device, dtype=dtype))+ _saturation = saturation if isinstance(saturation, (int, float)) else \+ nn.Parameter(saturation.clone().to(device=device, dtype=dtype))+ _hue = hue if isinstance(hue, (int, float)) else \+ nn.Parameter(hue.clone().to(device=device, dtype=dtype))++ torch.manual_seed(0)+ input = torch.randint(255, (2, 3, 10, 10), device=device, dtype=dtype) / 255.+ aug = ColorJitter(_brightness, _contrast, _saturation, _hue, return_transform, same_on_batch)++ if return_transform:+ output, _ = aug(input)+ else:+ output = aug(input)++ if len(list(aug.parameters())) != 0:+ mse = nn.MSELoss()+ opt = torch.optim.SGD(aug.parameters(), lr=0.1)+ loss = mse(output, torch.ones_like(output) * 2)+ loss.backward()+ opt.step()++ if not isinstance(brightness, (int, float)):+ assert isinstance(aug.brightness, torch.Tensor)+ # Assert if param not updated+ assert (brightness.to(device=device, dtype=dtype) - aug.brightness.data).sum() != 0+ if not isinstance(contrast, (int, float)):+ assert isinstance(aug.contrast, torch.Tensor)+ # Assert if param not updated+ assert (contrast.to(device=device, dtype=dtype) - aug.contrast.data).sum() != 0+ if not isinstance(saturation, (int, float)):+ assert isinstance(aug.saturation, torch.Tensor)+ # Assert if param not updated+ assert (saturation.to(device=device, dtype=dtype) - aug.saturation.data).sum() != 0+ if not isinstance(hue, (int, float)):+ assert isinstance(aug.hue, torch.Tensor)+ # Assert if param not updated+ assert (hue.to(device=device, dtype=dtype) - aug.hue.data).sum() != 0+++class TestRandomAffineBackward:++ @pytest.mark.parametrize("degrees", [10, [10., 20.], (10, 20), torch.tensor(10.), torch.tensor([10, 20])])+ @pytest.mark.parametrize("translate", [[0.1, 0.2], torch.tensor([0.1, 0.2])])+ @pytest.mark.parametrize("scale", [+ [0.1, 0.2], [0.1, 0.2, 0.3, 0.4], torch.tensor([0.1, 0.2]), torch.tensor([0.1, 0.2, 0.3, 0.4])])+ @pytest.mark.parametrize("shear", [+ [10., 20.], [10., 20., 30., 40.], torch.tensor([10, 20]), torch.tensor([10, 20, 30, 40])])+ @pytest.mark.parametrize("resample", ['bilinear', 'nearest'])+ @pytest.mark.parametrize("align_corners", [True, False])+ @pytest.mark.parametrize("return_transform", [True, False])+ @pytest.mark.parametrize("same_on_batch", [True, False])+ def test_param(self, degrees, translate, scale, shear, resample, align_corners, return_transform,+ same_on_batch, device, dtype):++ _degrees = degrees if isinstance(degrees, (int, float, list, tuple)) else \+ nn.Parameter(degrees.clone().to(device=device, dtype=dtype))+ _translate = translate if isinstance(translate, (int, float, list, tuple)) else \+ nn.Parameter(translate.clone().to(device=device, dtype=dtype))+ _scale = scale if isinstance(scale, (int, float, list, tuple)) else \+ nn.Parameter(scale.clone().to(device=device, dtype=dtype))+ _shear = shear if isinstance(shear, (int, float, list, tuple)) else \+ nn.Parameter(shear.clone().to(device=device, dtype=dtype))++ torch.manual_seed(0)+ input = torch.randint(255, (2, 3, 10, 10), device=device, dtype=dtype) / 255.+ aug = RandomAffine(+ _degrees, _translate, _scale, _shear, resample, align_corners=align_corners,+ return_transform=return_transform, same_on_batch=same_on_batch, p=1.)++ if return_transform:+ output, _ = aug(input)+ else:+ output = aug(input)++ if len(list(aug.parameters())) != 0:+ mse = nn.MSELoss()+ opt = torch.optim.SGD(aug.parameters(), lr=10)+ loss = mse(output, torch.ones_like(output) * 2)+ loss.backward()+ opt.step()++ if not isinstance(degrees, (int, float, list, tuple)):+ assert isinstance(aug.degrees, torch.Tensor)+ # Assert if param not updated+ if resample == 'nearest' and aug.degrees.is_cuda:+ # grid_sample in nearest mode and cuda device returns nan than 0+ pass+ elif resample == 'nearest' or torch.all(aug.degrees._grad == 0.):+ # grid_sample will return grad = 0 for resample nearest+ # https://discuss.pytorch.org/t/autograd-issue-with-f-grid-sample/76894+ assert (degrees.to(device=device, dtype=dtype) - aug.degrees.data).sum() == 0+ else:+ assert (degrees.to(device=device, dtype=dtype) - aug.degrees.data).sum() != 0+ if not isinstance(translate, (int, float, list, tuple)):+ assert isinstance(aug.translate, torch.Tensor)+ # Assert if param not updated+ if resample == 'nearest' and aug.translate.is_cuda:+ # grid_sample in nearest mode and cuda device returns nan than 0+ pass+ elif resample == 'nearest' or torch.all(aug.translate._grad == 0.):+ # grid_sample will return grad = 0 for resample nearest+ # https://discuss.pytorch.org/t/autograd-issue-with-f-grid-sample/76894+ assert (translate.to(device=device, dtype=dtype) - aug.translate.data).sum() == 0+ else:+ assert (translate.to(device=device, dtype=dtype) - aug.translate.data).sum() != 0+ if not isinstance(scale, (int, float, list, tuple)):+ assert isinstance(aug.scale, torch.Tensor)+ # Assert if param not updated+ if resample == 'nearest' and aug.scale.is_cuda:+ # grid_sample in nearest mode and cuda device returns nan than 0+ pass+ elif resample == 'nearest' or torch.all(aug.scale._grad == 0.):+ # grid_sample will return grad = 0 for resample nearest+ # https://discuss.pytorch.org/t/autograd-issue-with-f-grid-sample/76894+ assert (scale.to(device=device, dtype=dtype) - aug.scale.data).sum() == 0+ else:+ assert (scale.to(device=device, dtype=dtype) - aug.scale.data).sum() != 0+ if not isinstance(shear, (int, float, list, tuple)):+ assert isinstance(aug.shear, torch.Tensor)+ # Assert if param not updated+ if resample == 'nearest' and aug.shear.is_cuda:+ # grid_sample in nearest mode and cuda device returns nan than 0+ pass+ elif resample == 'nearest' or torch.all(aug.shear._grad == 0.):+ # grid_sample will return grad = 0 for resample nearest+ # https://discuss.pytorch.org/t/autograd-issue-with-f-grid-sample/76894+ assert (shear.to(device=device, dtype=dtype) - aug.shear.data).sum() == 0+ else:+ assert (shear.to(device=device, dtype=dtype) - aug.shear.data).sum() != 0+++class TestRandomRotationBackward:++ @pytest.mark.parametrize("degrees", [10, [10., 20.], (10, 20), torch.tensor(10.), torch.tensor([10, 20])])+ @pytest.mark.parametrize("resample", ['bilinear', 'nearest'])+ @pytest.mark.parametrize("align_corners", [True, False])+ @pytest.mark.parametrize("return_transform", [True, False])+ @pytest.mark.parametrize("same_on_batch", [True, False])+ def test_param(self, degrees, resample, align_corners, return_transform, same_on_batch, device, dtype):++ _degrees = degrees if isinstance(degrees, (int, float, list, tuple)) else \+ nn.Parameter(degrees.clone().to(device=device, dtype=dtype))++ torch.manual_seed(0)+ input = torch.randint(255, (2, 3, 10, 10), device=device, dtype=dtype) / 255.+ aug = RandomRotation(+ _degrees, resample, align_corners=align_corners,+ return_transform=return_transform, same_on_batch=same_on_batch)++ if return_transform:+ output, _ = aug(input)+ else:+ output = aug(input)++ if len(list(aug.parameters())) != 0:+ mse = nn.MSELoss()+ opt = torch.optim.SGD(aug.parameters(), lr=10)+ loss = mse(output, torch.ones_like(output) * 2)+ loss.backward()+ opt.step()++ if not isinstance(degrees, (int, float, list, tuple)):+ assert isinstance(aug.degrees, torch.Tensor)+ # Assert if param not updated+ if resample == 'nearest' and aug.degrees.is_cuda:+ # grid_sample in nearest mode and cuda device returns nan than 0+ pass+ elif resample == 'nearest' or torch.all(aug.degrees._grad == 0.):+ # grid_sample will return grad = 0 for resample nearest+ # https://discuss.pytorch.org/t/autograd-issue-with-f-grid-sample/76894+ assert (degrees.to(device=device, dtype=dtype) - aug.degrees.data).sum() == 0+ else:+ assert (degrees.to(device=device, dtype=dtype) - aug.degrees.data).sum() != 0+++class TestRandomPerspectiveBackward:++ @pytest.mark.parametrize("distortion_scale", [0.5, torch.tensor(0.5)])+ @pytest.mark.parametrize("resample", ['bilinear', 'nearest'])+ @pytest.mark.parametrize("align_corners", [True, False])+ @pytest.mark.parametrize("return_transform", [True, False])+ @pytest.mark.parametrize("same_on_batch", [True, False])+ def test_param(self, distortion_scale, resample, align_corners, return_transform, same_on_batch, device, dtype):++ _distortion_scale = distortion_scale if isinstance(distortion_scale, (float, int)) else \+ nn.Parameter(distortion_scale.clone().to(device=device, dtype=dtype))++ torch.manual_seed(0)+ input = torch.randint(255, (2, 3, 10, 10), device=device, dtype=dtype) / 255.+ aug = RandomPerspective(+ _distortion_scale, resample=resample, return_transform=return_transform,+ same_on_batch=same_on_batch, align_corners=align_corners, p=1.)++ if return_transform:+ output, _ = aug(input)+ else:+ output = aug(input)++ if len(list(aug.parameters())) != 0:+ mse = nn.MSELoss()+ opt = torch.optim.SGD(aug.parameters(), lr=0.1)+ loss = mse(output, torch.ones_like(output) * 2)+ loss.backward()+ opt.step()++ if not isinstance(distortion_scale, (float, int)):+ assert isinstance(aug.distortion_scale, torch.Tensor)+ # Assert if param not updated+ if resample == 'nearest' and aug.distortion_scale.is_cuda:+ # grid_sample in nearest mode and cuda device returns nan than 0+ pass+ elif resample == 'nearest' or torch.all(aug.distortion_scale._grad == 0.):+ # grid_sample will return grad = 0 for resample nearest+ # https://discuss.pytorch.org/t/autograd-issue-with-f-grid-sample/76894+ assert (distortion_scale.to(device=device, dtype=dtype) - aug.distortion_scale.data).sum() == 0+ else:+ assert (distortion_scale.to(device=device, dtype=dtype) - aug.distortion_scale.data).sum() != 0+++class TestRandomMotionBlurBackward:++ @pytest.mark.parametrize("angle", [20., torch.tensor([-20., 20.])])+ @pytest.mark.parametrize("direction", [[-0.5, 0.5], torch.tensor([-0.5, 0.5])])+ @pytest.mark.parametrize("border_type", ['constant', 'reflect', 'replicate', 'circular'])+ @pytest.mark.parametrize("resample", ['bilinear', 'nearest'])+ @pytest.mark.parametrize("return_transform", [True, False])+ @pytest.mark.parametrize("same_on_batch", [True, False])+ def test_param(self, angle, direction, border_type, resample, return_transform, same_on_batch, device, dtype):++ _angle = angle if isinstance(angle, (float, int, list, tuple)) else \+ nn.Parameter(angle.clone().to(device=device, dtype=dtype))+ _direction = direction if isinstance(direction, (list, tuple)) else \+ nn.Parameter(direction.clone().to(device=device, dtype=dtype))++ torch.manual_seed(0)+ input = torch.randint(255, (2, 3, 10, 10), device=device, dtype=dtype) / 255.+ aug = RandomMotionBlur(+ (3, 3), _angle, _direction, border_type, resample, return_transform, same_on_batch, p=1.)++ if return_transform:+ output, _ = aug(input)+ else:+ output = aug(input)++ if len(list(aug.parameters())) != 0:+ mse = nn.MSELoss()+ opt = torch.optim.SGD(aug.parameters(), lr=0.1)+ loss = mse(output, torch.ones_like(output) * 2)+ loss.backward()+ opt.step()++ if not isinstance(angle, (float, int, list, tuple)):+ assert isinstance(aug.angle, torch.Tensor)+ if resample == 'nearest' and aug.angle.is_cuda:+ # grid_sample in nearest mode and cuda device returns nan than 0+ pass+ elif resample == 'nearest' or torch.all(aug.angle._grad == 0.):+ # grid_sample will return grad = 0 for resample nearest+ # https://discuss.pytorch.org/t/autograd-issue-with-f-grid-sample/76894+ assert (angle.to(device=device, dtype=dtype) - aug.angle.data).sum() == 0+ else:+ # Assert if param not updated+ assert (angle.to(device=device, dtype=dtype) - aug.angle.data).sum() != 0+ if not isinstance(direction, (list, tuple)):+ assert isinstance(aug.direction, torch.Tensor)+ if torch.all(aug.direction._grad == 0.):+ # grid_sample will return grad = 0 for resample nearest+ # https://discuss.pytorch.org/t/autograd-issue-with-f-grid-sample/76894+ assert (direction.to(device=device, dtype=dtype) - aug.direction.data).sum() == 0+ else:+ # Assert if param not updated+ assert (direction.to(device=device, dtype=dtype) - aug.direction.data).sum() != 0+++class TestRandomSharpnessBackward:++ @pytest.mark.parametrize("sharpness", [0.5, [0, 0.5], torch.tensor([0, 0.5])])+ @pytest.mark.parametrize("return_transform", [True, False])+ @pytest.mark.parametrize("same_on_batch", [True, False])+ def test_param(self, sharpness, return_transform, same_on_batch, device, dtype):++ _sharpness = sharpness if isinstance(sharpness, (float, int, list, tuple)) else \+ nn.Parameter(sharpness.clone().to(device=device, dtype=dtype))++ torch.manual_seed(0)+ input = torch.randint(255, (2, 3, 10, 10), device=device, dtype=dtype) / 255.+ aug = RandomSharpness(+ _sharpness, return_transform=return_transform, same_on_batch=same_on_batch)++ if return_transform:+ output, _ = aug(input)+ else:+ output = aug(input)++ if len(list(aug.parameters())) != 0:+ mse = nn.MSELoss()+ opt = torch.optim.SGD(aug.parameters(), lr=0.1)+ loss = mse(output, torch.ones_like(output) * 2)+ loss.backward()+ opt.step()++ if not isinstance(sharpness, (float, int, list, tuple)):+ assert isinstance(aug.sharpness, torch.Tensor)+ # Assert if param not updated+ assert (sharpness.to(device=device, dtype=dtype) - aug.sharpness.data).sum() != 0+++class TestRandomResizedCropBackward:++ @pytest.mark.skip("Param gen is probably breaking grads.")+ @pytest.mark.parametrize("scale", [[0.08, 1.], torch.tensor([0.08, 1.])])+ @pytest.mark.parametrize("ratio", [[3. / 4., 4. / 3.], torch.tensor([3. / 4., 4. / 3.])])+ @pytest.mark.parametrize("resample", ['bilinear', 'nearest'])+ @pytest.mark.parametrize("align_corners", [True, False])+ @pytest.mark.parametrize("return_transform", [True, False])+ @pytest.mark.parametrize("same_on_batch", [True, False])+ def test_param(self, scale, ratio, resample, align_corners, return_transform, same_on_batch, device, dtype):++ _scale = scale if isinstance(scale, (list, tuple)) else \+ nn.Parameter(scale.clone().to(device=device, dtype=dtype))+ _ratio = ratio if isinstance(ratio, (list, tuple)) else \+ nn.Parameter(ratio.clone().to(device=device, dtype=dtype))++ torch.manual_seed(0)+ input = torch.randint(255, (2, 3, 10, 10), device=device, dtype=dtype) / 255.+ aug = RandomResizedCrop(+ (8, 8), _scale, _ratio, resample=resample, return_transform=return_transform,+ same_on_batch=same_on_batch, align_corners=align_corners)++ if return_transform:+ output, _ = aug(input)+ else:+ output = aug(input)++ if len(list(aug.parameters())) != 0:+ mse = nn.MSELoss()+ opt = torch.optim.SGD(aug.parameters(), lr=0.1)+ loss = mse(output, torch.ones_like(output) * 2)+ loss.backward()+ opt.step()++ if not isinstance(scale, (list, tuple)):+ assert isinstance(aug.scale, torch.Tensor)+ # Assert if param not updated+ assert (scale.to(device=device, dtype=dtype) - aug.scale.data).sum() != 0+ if not isinstance(ratio, (list, tuple)):+ assert isinstance(aug.ratio, torch.Tensor)+ # Assert if param not updated+ assert (ratio.to(device=device, dtype=dtype) - aug.ratio.data).sum() != 0+++class TestRandomErasingBackward:++ @pytest.mark.skip("Need differentiable indexing.")+ @pytest.mark.parametrize("scale", [[0.02, 0.33], torch.tensor([0.02, 0.33])])+ @pytest.mark.parametrize("ratio", [[0.3, 3.3], torch.tensor([0.3, 3.3])])+ @pytest.mark.parametrize("value", [0.])+ @pytest.mark.parametrize("return_transform", [True, False])+ @pytest.mark.parametrize("same_on_batch", [True, False])+ def test_param(self, scale, ratio, value, return_transform, same_on_batch, device, dtype):++ _scale = scale if isinstance(scale, (list, tuple)) else \+ nn.Parameter(scale.clone().to(device=device, dtype=dtype))+ _ratio = ratio if isinstance(ratio, (list, tuple)) else \+ nn.Parameter(ratio.clone().to(device=device, dtype=dtype))++ torch.manual_seed(0)+ input = torch.randint(255, (2, 3, 10, 10), device=device, dtype=dtype) / 255.+ aug = RandomErasing(_scale, _ratio, value, return_transform, same_on_batch)++ if return_transform:+ output, _ = aug(input)+ else:+ output = aug(input)++ if len(list(aug.parameters())) != 0:+ mse = nn.MSELoss()+ opt = torch.optim.SGD(aug.parameters(), lr=0.1)+ loss = mse(output, torch.ones_like(output) * 2)+ loss.backward()+ opt.step()++ if not isinstance(scale, (list, tuple)):+ assert isinstance(aug.scale, torch.Tensor)+ if torch.all(aug.scale._grad == 0.):+ # grid_sample will return grad = 0 for resample nearest+ # https://discuss.pytorch.org/t/autograd-issue-with-f-grid-sample/76894+ assert (scale.to(device=device, dtype=dtype) - aug.scale.data).sum() == 0+ else:+ # Assert if param not updated+ assert (scale.to(device=device, dtype=dtype) - aug.scale.data).sum() != 0+ if not isinstance(ratio, (list, tuple)):+ assert isinstance(aug.ratio, torch.Tensor)+ if torch.all(aug.ratio._grad == 0.):+ # grid_sample will return grad = 0 for resample nearest+ # https://discuss.pytorch.org/t/autograd-issue-with-f-grid-sample/76894+ assert (ratio.to(device=device, dtype=dtype) - aug.ratio.data).sum() == 0+ else:+ # Assert if param not updated+ assert (ratio.to(device=device, dtype=dtype) - aug.ratio.data).sum() != 0diff --git a/test/augmentation/test_backward_3d.py b/test/augmentation/test_backward_3d.pynew file mode 100644index 000000000..5c4aecabc--- /dev/null+++ b/test/augmentation/test_backward_3d.py@@ -0,0 +1,258 @@+import pytest+import torch+import torch.nn as nn++from torch.testing import assert_allclose++from kornia.augmentation import (+ RandomAffine3D,+ RandomRotation3D,+ RandomPerspective3D,+ RandomMotionBlur3D+)+++class TestRandomAffine3DBackward:++ @pytest.mark.parametrize("degrees", [+ 10, [10., 20.], [10., 20., 30.], [(10, 20), (10, 20), (10, 20)],+ torch.tensor(10.), torch.tensor([10., 20.]), torch.tensor([10, 20, 30]),+ torch.tensor([(10, 20), (10, 20), (10, 20)])])+ @pytest.mark.parametrize("translate", [[0.1, 0.2, 0.3], torch.tensor([0.1, 0.2, 0.3])])+ @pytest.mark.parametrize("scale", [+ [0.1, 0.2], [(0.1, 0.2), (0.1, 0.2), (0.1, 0.2)],+ torch.tensor([0.1, 0.2]), torch.tensor([(0.1, 0.2), (0.1, 0.2), (0.1, 0.2)])])+ @pytest.mark.parametrize("shear", [+ 10., [10., 20.], [10., 20., 30., 40., 50., 60.],+ [(-10., 10.), (-10., 10.), (-10., 10.), (-10., 10.), (-10., 10.), (-10., 10.)],+ torch.tensor(10), torch.tensor([10, 20]), torch.tensor([10., 20., 30., 40., 50., 60.]),+ torch.tensor([(-10., 10.), (-10., 10.), (-10., 10.), (-10., 10.), (-10., 10.), (-10., 10.)])])+ @pytest.mark.parametrize("resample", ['bilinear', 'nearest'])+ @pytest.mark.parametrize("align_corners", [True, False])+ @pytest.mark.parametrize("return_transform", [True, False])+ @pytest.mark.parametrize("same_on_batch", [True, False])+ def test_param(self, degrees, translate, scale, shear, resample, align_corners, return_transform,+ same_on_batch, device, dtype):++ _degrees = degrees if isinstance(degrees, (int, float, list, tuple)) else \+ nn.Parameter(degrees.clone().to(device=device, dtype=dtype))+ _translate = translate if isinstance(translate, (int, float, list, tuple)) else \+ nn.Parameter(translate.clone().to(device=device, dtype=dtype))+ _scale = scale if isinstance(scale, (int, float, list, tuple)) else \+ nn.Parameter(scale.clone().to(device=device, dtype=dtype))+ _shear = shear if isinstance(shear, (int, float, list, tuple)) else \+ nn.Parameter(shear.clone().to(device=device, dtype=dtype))++ torch.manual_seed(0)+ input = torch.randint(255, (2, 3, 10, 10, 10), device=device, dtype=dtype) / 255.+ aug = RandomAffine3D(+ _degrees, _translate, _scale, _shear, resample, align_corners=align_corners,+ return_transform=return_transform, same_on_batch=same_on_batch, p=1.)++ if return_transform:+ output, _ = aug(input)+ else:+ output = aug(input)++ if len(list(aug.parameters())) != 0:+ mse = nn.MSELoss()+ opt = torch.optim.SGD(aug.parameters(), lr=10)+ loss = mse(output, torch.ones_like(output) * 2) # to ensure that a big loss value could be obtained+ loss.backward()+ opt.step()++ if not isinstance(degrees, (int, float, list, tuple)):+ assert isinstance(aug.degrees, torch.Tensor)+ # Assert if param not updated+ if resample == 'nearest' and aug.degrees.is_cuda:+ # grid_sample in nearest mode and cuda device returns nan than 0+ pass+ elif resample == 'nearest' or torch.all(aug.degrees._grad == 0.):+ # grid_sample will return grad = 0 for resample nearest+ # https://discuss.pytorch.org/t/autograd-issue-with-f-grid-sample/76894+ assert (degrees.to(device=device, dtype=dtype) - aug.degrees.data).sum() == 0+ else:+ assert (degrees.to(device=device, dtype=dtype) - aug.degrees.data).sum() != 0+ if not isinstance(translate, (int, float, list, tuple)):+ assert isinstance(aug.translate, torch.Tensor)+ # Assert if param not updated+ if resample == 'nearest' and aug.translate.is_cuda:+ # grid_sample in nearest mode and cuda device returns nan than 0+ pass+ elif resample == 'nearest' or torch.all(aug.translate._grad == 0.):+ # grid_sample will return grad = 0 for resample nearest+ # https://discuss.pytorch.org/t/autograd-issue-with-f-grid-sample/76894+ assert (translate.to(device=device, dtype=dtype) - aug.translate.data).sum() == 0+ else:+ assert (translate.to(device=device, dtype=dtype) - aug.translate.data).sum() != 0+ if not isinstance(scale, (int, float, list, tuple)):+ assert isinstance(aug.scale, torch.Tensor)+ # Assert if param not updated+ if resample == 'nearest' and aug.scale.is_cuda:+ # grid_sample in nearest mode and cuda device returns nan than 0+ pass+ elif resample == 'nearest' or torch.all(aug.scale._grad == 0.):+ # grid_sample will return grad = 0 for resample nearest+ # https://discuss.pytorch.org/t/autograd-issue-with-f-grid-sample/76894+ assert (scale.to(device=device, dtype=dtype) - aug.scale.data).sum() == 0+ else:+ assert (scale.to(device=device, dtype=dtype) - aug.scale.data).sum() != 0+ if not isinstance(shear, (int, float, list, tuple)):+ assert isinstance(aug.shears, torch.Tensor)+ # Assert if param not updated+ if resample == 'nearest' and aug.shears.is_cuda:+ # grid_sample in nearest mode and cuda device returns nan than 0+ pass+ elif resample == 'nearest' or torch.all(aug.shears._grad == 0.):+ # grid_sample will return grad = 0 for resample nearest+ # https://discuss.pytorch.org/t/autograd-issue-with-f-grid-sample/76894+ assert (shear.to(device=device, dtype=dtype) - aug.shears.data).sum() == 0+ else:+ assert (shear.to(device=device, dtype=dtype) - aug.shears.data).sum() != 0+++class TestRandomRotation3DBackward:++ @pytest.mark.parametrize("degrees", [+ 10, [10., 20.], [10., 20., 30.], [(10, 20), (10, 20), (10, 20)],+ torch.tensor(10.), torch.tensor([10., 20.]), torch.tensor([10, 20, 30]),+ torch.tensor([(10, 20), (10, 20), (10, 20)])])+ @pytest.mark.parametrize("resample", ['bilinear', 'nearest'])+ @pytest.mark.parametrize("align_corners", [True, False])+ @pytest.mark.parametrize("return_transform", [True, False])+ @pytest.mark.parametrize("same_on_batch", [True, False])+ def test_param(self, degrees, resample, align_corners, return_transform, same_on_batch, device, dtype):++ _degrees = degrees if isinstance(degrees, (int, float, list, tuple)) else \+ nn.Parameter(degrees.clone().to(device=device, dtype=dtype))++ torch.manual_seed(0)+ input = torch.randint(255, (2, 3, 10, 10, 10), device=device, dtype=dtype) / 255.+ aug = RandomRotation3D(+ _degrees, resample, align_corners=align_corners,+ return_transform=return_transform, same_on_batch=same_on_batch, p=1.)++ if return_transform:+ output, _ = aug(input)+ else:+ output = aug(input)++ if len(list(aug.parameters())) != 0:+ mse = nn.MSELoss()+ opt = torch.optim.SGD(aug.parameters(), lr=10)+ loss = mse(output, torch.ones_like(output) * 2) # to ensure that a big loss value could be obtained+ loss.backward()+ opt.step()++ if not isinstance(degrees, (int, float, list, tuple)):+ assert isinstance(aug.degrees, torch.Tensor)+ # Assert if param not updated+ if resample == 'nearest' and aug.degrees.is_cuda:+ # grid_sample in nearest mode and cuda device returns nan than 0+ pass+ elif resample == 'nearest' or torch.all(aug.degrees._grad == 0.):+ # grid_sample will return grad = 0 for resample nearest+ # https://discuss.pytorch.org/t/autograd-issue-with-f-grid-sample/76894+ assert (degrees.to(device=device, dtype=dtype) - aug.degrees.data).sum() == 0+ else:+ assert (degrees.to(device=device, dtype=dtype) - aug.degrees.data).sum() != 0+++class TestRandomPerspective3DBackward:++ @pytest.mark.parametrize("distortion_scale", [0.5, torch.tensor(0.5)])+ @pytest.mark.parametrize("resample", ['bilinear', 'nearest'])+ @pytest.mark.parametrize("align_corners", [True, False])+ @pytest.mark.parametrize("return_transform", [True, False])+ @pytest.mark.parametrize("same_on_batch", [True, False])+ def test_param(self, distortion_scale, resample, align_corners, return_transform, same_on_batch, device, dtype):++ _distortion_scale = distortion_scale if isinstance(distortion_scale, (float, int)) else \+ nn.Parameter(distortion_scale.clone().to(device=device, dtype=dtype))++ torch.manual_seed(0)+ input = torch.randint(255, (2, 3, 10, 10, 10), device=device, dtype=dtype) / 255.+ aug = RandomPerspective3D(+ _distortion_scale, resample=resample, return_transform=return_transform,+ same_on_batch=same_on_batch, align_corners=align_corners, p=1.)++ if return_transform:+ output, _ = aug(input)+ else:+ output = aug(input)++ if len(list(aug.parameters())) != 0:+ mse = nn.MSELoss()+ opt = torch.optim.SGD(aug.parameters(), lr=10)+ loss = mse(output, torch.ones_like(output) * 2) # to ensure that a big loss value could be obtained+ loss.backward()+ opt.step()++ if not isinstance(distortion_scale, (float, int)):+ assert isinstance(aug.distortion_scale, torch.Tensor)+ # Assert if param not updated+ if resample == 'nearest' and aug.distortion_scale.is_cuda:+ # grid_sample in nearest mode and cuda device returns nan than 0+ pass+ elif resample == 'nearest' or torch.all(aug.distortion_scale._grad == 0.):+ # grid_sample will return grad = 0 for resample nearest+ # https://discuss.pytorch.org/t/autograd-issue-with-f-grid-sample/76894+ assert (distortion_scale.to(device=device, dtype=dtype) - aug.distortion_scale.data).sum() == 0+ else:+ assert (distortion_scale.to(device=device, dtype=dtype) - aug.distortion_scale.data).sum() != 0+++class TestRandomMotionBlur3DBackward:++ @pytest.mark.parametrize("angle", [20., torch.tensor(20.), torch.tensor([20.])])+ @pytest.mark.parametrize("direction", [[-0.5, 0.5], torch.tensor([-0.5, 0.5])])+ # 'reflect' is not implemented by torch.+ @pytest.mark.parametrize("border_type", ['constant', 'replicate', 'circular'])+ @pytest.mark.parametrize("resample", ['bilinear', 'nearest'])+ @pytest.mark.parametrize("return_transform", [True, False])+ @pytest.mark.parametrize("same_on_batch", [True, False])+ def test_param(self, angle, direction, border_type, resample, return_transform, same_on_batch, device, dtype):++ _angle = angle if isinstance(angle, (float, int, list, tuple)) else \+ nn.Parameter(angle.clone().to(device=device, dtype=dtype))+ _direction = direction if isinstance(direction, (list, tuple)) else \+ nn.Parameter(direction.clone().to(device=device, dtype=dtype))++ torch.manual_seed(0)+ input = torch.randint(255, (2, 3, 10, 10, 10), device=device, dtype=dtype) / 255.+ aug = RandomMotionBlur3D(+ (3, 3), _angle, _direction, border_type, resample, return_transform, same_on_batch, p=1.)++ if return_transform:+ output, _ = aug(input)+ else:+ output = aug(input)++ if len(list(aug.parameters())) != 0:+ mse = nn.MSELoss()+ opt = torch.optim.SGD(aug.parameters(), lr=10)+ loss = mse(output, torch.ones_like(output) * 2) # to ensure that a big loss value could be obtained+ loss.backward()+ opt.step()++ if not isinstance(angle, (float, int, list, tuple)):+ assert isinstance(aug.angle, torch.Tensor)+ if resample == 'nearest' and aug.angle.is_cuda:+ # grid_sample in nearest mode and cuda device returns nan than 0+ pass+ elif resample == 'nearest' or torch.all(aug.angle._grad == 0.):+ # grid_sample will return grad = 0 for resample nearest+ # https://discuss.pytorch.org/t/autograd-issue-with-f-grid-sample/76894+ assert (angle.to(device=device, dtype=dtype) - aug.angle.data).sum() == 0+ else:+ # Assert if param not updated+ assert (angle.to(device=device, dtype=dtype) - aug.angle.data).sum() != 0+ if not isinstance(direction, (list, tuple)):+ assert isinstance(aug.direction, torch.Tensor)+ if torch.all(aug.direction._grad == 0.):+ # grid_sample will return grad = 0 for resample nearest+ # https://discuss.pytorch.org/t/autograd-issue-with-f-grid-sample/76894+ assert (direction.to(device=device, dtype=dtype) - aug.direction.data).sum() == 0+ else:+ # Assert if param not updated+ assert (direction.to(device=device, dtype=dtype) - aug.direction.data).sum() != 0diff --git a/test/augmentation/test_random_generator.py b/test/augmentation/test_random_generator.pyindex d3133d0b4..e08166d74 100644--- a/test/augmentation/test_random_generator.py+++ b/test/augmentation/test_random_generator.py@@ -430,7 +430,7 @@ class TestRandomCropGen(RandomGeneratorBaseTests):batch_size=batch_size, input_size=input_size,size=size,resize_to=resize_to,- same_on_batch=same_on_batch)+ same_on_batch=same_on_batch, device=device, dtype=dtype)@pytest.mark.parametrize('input_size,size,resize_to', [((-300, 300), (200, 200), (100, 100)),@@ -448,7 +448,7 @@ class TestRandomCropGen(RandomGeneratorBaseTests):def test_random_gen(self, device, dtype):torch.manual_seed(42)- degrees = torch.tensor([10, 20])+ degrees = torch.tensor([10, 20], device=device, dtype=dtype)res = random_crop_generator(batch_size=2, input_size=(100, 100),size=torch.tensor([[50, 60], [70, 80]], device=device, dtype=dtype),@@ -462,7 +462,7 @@ class TestRandomCropGen(RandomGeneratorBaseTests):[[19, 29],[98, 29],[98, 98],- [19, 98]]], device=device, dtype=torch.long),+ [19, 98]]], device=device, dtype=dtype),dst=torch.tensor([[[0, 0],[199, 0],@@ -471,7 +471,7 @@ class TestRandomCropGen(RandomGeneratorBaseTests):[[0, 0],[199, 0],[199, 199],- [0, 199]]], device=device, dtype=torch.long),+ [0, 199]]], device=device, dtype=dtype),)assert res.keys() == expected.keys()assert_allclose(res['src'], expected['src'])@@ -479,7 +479,7 @@ class TestRandomCropGen(RandomGeneratorBaseTests):def test_same_on_batch(self, device, dtype):torch.manual_seed(42)- degrees = torch.tensor([10, 20])+ degrees = torch.tensor([10, 20], device=device, dtype=dtype)res = random_crop_generator(batch_size=2, input_size=(100, 100),size=torch.tensor([[50, 60], [70, 80]], device=device, dtype=dtype),@@ -493,7 +493,7 @@ class TestRandomCropGen(RandomGeneratorBaseTests):[[36, 46],[115, 46],[115, 115],- [36, 115]]], device=device, dtype=torch.long),+ [36, 115]]], device=device, dtype=dtype),dst=torch.tensor([[[0, 0],[199, 0],@@ -502,7 +502,7 @@ class TestRandomCropGen(RandomGeneratorBaseTests):[[0, 0],[199, 0],[199, 199],- [0, 199]]], device=device, dtype=torch.long),+ [0, 199]]], device=device, dtype=dtype),)assert res.keys() == expected.keys()assert_allclose(res['src'], expected['src'])@@ -544,7 +544,6 @@ class TestRandomCropSizeGen(RandomGeneratorBaseTests):def test_random_gen(self, device, dtype):torch.manual_seed(42)- degrees = torch.tensor([10, 20])res = random_crop_size_generator(batch_size=8, size=(100, 100),scale=torch.tensor([0.7, 1.3], device=device, dtype=dtype),@@ -559,7 +558,7 @@ class TestRandomCropSizeGen(RandomGeneratorBaseTests):[94, 98],[87, 81],[85, 93],- [83, 90]], device=device, dtype=torch.long)+ [83, 90]], device=device, dtype=dtype))assert res.keys() == expected.keys()assert_allclose(res['size'], expected['size'])@@ -570,7 +569,7 @@ class TestRandomCropSizeGen(RandomGeneratorBaseTests):ratio=torch.tensor([1., 1.], device=device, dtype=dtype),same_on_batch=False)expected = dict(- size=torch.tensor([[100, 100]], device=device, dtype=torch.long)+ size=torch.tensor([[100, 100]], device=device, dtype=dtype))assert res.keys() == expected.keys()assert_allclose(res['size'], expected['size'])@@ -592,7 +591,7 @@ class TestRandomCropSizeGen(RandomGeneratorBaseTests):[99, 95],[99, 95],[99, 95],- [99, 95]], device=device, dtype=torch.long),+ [99, 95]], device=device, dtype=dtype),)assert res.keys() == expected.keys()assert_allclose(res['size'], expected['size'])@@ -645,10 +644,10 @@ class TestRandomRectangleGen(RandomGeneratorBaseTests):batch_size=2, height=height, width=width, scale=scale,ratio=ratio, value=value, same_on_batch=False)expected = dict(- widths=torch.tensor([100, 100], device=device, dtype=torch.int32),- heights=torch.tensor([0, 0], device=device, dtype=torch.int32),- xs=torch.tensor([0, 0], device=device, dtype=torch.int32),- ys=torch.tensor([6, 8], device=device, dtype=torch.int32),+ widths=torch.tensor([100, 100], device=device, dtype=dtype),+ heights=torch.tensor([0, 0], device=device, dtype=dtype),+ xs=torch.tensor([0, 0], device=device, dtype=dtype),+ ys=torch.tensor([6, 8], device=device, dtype=dtype),values=torch.tensor([0.5000, 0.5000], device=device, dtype=dtype))assert res.keys() == expected.keys()@@ -668,10 +667,10 @@ class TestRandomRectangleGen(RandomGeneratorBaseTests):batch_size=2, height=height, width=width, scale=scale,ratio=ratio, value=value, same_on_batch=True)expected = dict(- widths=torch.tensor([100, 100], device=device, dtype=torch.int32),- heights=torch.tensor([0, 0], device=device, dtype=torch.int32),- xs=torch.tensor([0, 0], device=device, dtype=torch.int32),- ys=torch.tensor([10, 10], device=device, dtype=torch.int32),+ widths=torch.tensor([100, 100], device=device, dtype=dtype),+ heights=torch.tensor([0, 0], device=device, dtype=dtype),+ xs=torch.tensor([0, 0], device=device, dtype=dtype),+ ys=torch.tensor([10, 10], device=device, dtype=dtype),values=torch.tensor([0.5000, 0.5000], device=device, dtype=dtype))assert res.keys() == expected.keys()@@ -1052,7 +1051,7 @@ class TestRandomCutMixGen(RandomGeneratorBaseTests):[[39, 1],[38, 1],[38, 0],- [39, 0]]]], device=device, dtype=torch.long)+ [39, 0]]]], device=device, dtype=dtype))assert res.keys() == expected.keys()assert_allclose(res['mix_pairs'], expected['mix_pairs'], rtol=1e-4, atol=1e-4)@@ -1075,7 +1074,7 @@ class TestRandomCutMixGen(RandomGeneratorBaseTests):[[114, 53],[113, 53],[113, 52],- [114, 52]]]], device=device, dtype=torch.long)+ [114, 52]]]], device=device, dtype=dtype))assert res.keys() == expected.keys()assert_allclose(res['mix_pairs'], expected['mix_pairs'], rtol=1e-4, atol=1e-4)diff --git a/test/augmentation/test_random_generator_3d.py b/test/augmentation/test_random_generator_3d.pyindex 56267afb9..c7980e263 100644--- a/test/augmentation/test_random_generator_3d.py+++ b/test/augmentation/test_random_generator_3d.py@@ -374,7 +374,7 @@ class TestRandomCropGen3D(RandomGeneratorBaseTests):[119, 135, 139],[188, 135, 139],[188, 194, 139],- [119, 194, 139]]], device=device, dtype=torch.long),+ [119, 194, 139]]], device=device, dtype=dtype),dst=torch.tensor([[[0, 0, 0],[99, 0, 0],[99, 99, 0],@@ -390,7 +390,7 @@ class TestRandomCropGen3D(RandomGeneratorBaseTests):[0, 0, 99],[99, 0, 99],[99, 99, 99],- [0, 99, 99]]], device=device, dtype=torch.long),+ [0, 99, 99]]], device=device, dtype=dtype),)assert res.keys() == expected.keys()assert_allclose(res['src'], expected['src'], atol=1e-4, rtol=1e-4)@@ -419,7 +419,7 @@ class TestRandomCropGen3D(RandomGeneratorBaseTests):[115, 129, 106],[184, 129, 106],[184, 188, 106],- [115, 188, 106]]], device=device, dtype=torch.long),+ [115, 188, 106]]], device=device, dtype=dtype),dst=torch.tensor([[[0, 0, 0],[99, 0, 0],[99, 99, 0],@@ -435,7 +435,7 @@ class TestRandomCropGen3D(RandomGeneratorBaseTests):[0, 0, 99],[99, 0, 99],[99, 99, 99],- [0, 99, 99]]], device=device, dtype=torch.long),+ [0, 99, 99]]], device=device, dtype=dtype),)assert res.keys() == expected.keys()assert_allclose(res['src'], expected['src'], atol=1e-4, rtol=1e-4)