Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

[feat] Added mix augmentations in containers (#1139)

Jian Shic55a537f1c1a
diff --git a/kornia/augmentation/augmentation.py b/kornia/augmentation/augmentation.py
index 5bb09998c..5a4511fb7 100644
--- a/kornia/augmentation/augmentation.py
+++ b/kornia/augmentation/augmentation.py
@@ -4,7 +4,7 @@ from typing import cast, Dict, List, Optional, Tuple, Union
import torch
from torch.nn.functional import pad
-from kornia.augmentation.base import GeometricAugmentationBase2D, IntensityAugmentationBase2D
+from kornia.augmentation.base import GeometricAugmentationBase2D, IntensityAugmentationBase2D, TensorWithTransformMat
from kornia.color import rgb_to_grayscale
from kornia.constants import BorderType, pi, Resample, SamplePadding
from kornia.enhance import (
@@ -1118,7 +1118,7 @@ class RandomCrop(GeometricAugmentationBase2D):
def inverse(
self,
- input: Union[torch.Tensor, Tuple[torch.Tensor, torch.Tensor]],
+ input: TensorWithTransformMat,
params: Optional[Dict[str, torch.Tensor]] = None,
size: Optional[Tuple[int, int]] = None,
**kwargs,
@@ -1135,10 +1135,10 @@ class RandomCrop(GeometricAugmentationBase2D):
def forward(
self,
- input: Union[torch.Tensor, Tuple[torch.Tensor, torch.Tensor]],
+ input: TensorWithTransformMat,
params: Optional[Dict[str, torch.Tensor]] = None,
return_transform: Optional[bool] = None,
- ) -> Union[torch.Tensor, Tuple[torch.Tensor, torch.Tensor]]:
+ ) -> TensorWithTransformMat:
if isinstance(input, (tuple, list)):
input_temp = _transform_input(input[0])
input_pad = self.compute_padding(input[0].shape)
@@ -1868,11 +1868,28 @@ class RandomGaussianBlur(IntensityAugmentationBase2D):
class GaussianBlur(RandomGaussianBlur):
- warnings.warn(
- "GaussianBlur is no longer maintained and will be removed from the future versions. "
- "Please use RandomGaussianBlur instead.",
- category=DeprecationWarning,
- )
+ def __init__(
+ self,
+ kernel_size: Tuple[int, int],
+ sigma: Tuple[float, float],
+ border_type: str = 'reflect',
+ return_transform: bool = False,
+ same_on_batch: bool = False,
+ p: float = 0.5,
+ ) -> None:
+ super(GaussianBlur, self).__init__(
+ kernel_size=kernel_size,
+ sigma=sigma,
+ border_type=border_type,
+ return_transform=return_transform,
+ same_on_batch=same_on_batch,
+ p=p,
+ )
+ warnings.warn(
+ "GaussianBlur is no longer maintained and will be removed from the future versions. "
+ "Please use RandomGaussianBlur instead.",
+ category=DeprecationWarning,
+ )
class RandomInvert(IntensityAugmentationBase2D):
@@ -1902,7 +1919,7 @@ class RandomInvert(IntensityAugmentationBase2D):
def __init__(
self,
- max_val: torch.Tensor = torch.tensor(1.0),
+ max_val: Union[float, torch.Tensor] = torch.tensor(1.0),
return_transform: bool = False,
same_on_batch: bool = False,
p: float = 0.5,
@@ -1910,6 +1927,7 @@ class RandomInvert(IntensityAugmentationBase2D):
super(RandomInvert, self).__init__(
p=p, return_transform=return_transform, same_on_batch=same_on_batch, p_batch=1.0
)
+ self.max_val = max_val
def __repr__(self) -> str:
return self.__class__.__name__ + f"({super().__repr__()})"
@@ -1917,7 +1935,7 @@ class RandomInvert(IntensityAugmentationBase2D):
def apply_transform(
self, input: torch.Tensor, params: Dict[str, torch.Tensor], transform: Optional[torch.Tensor] = None
) -> torch.Tensor:
- return invert(input)
+ return invert(input, torch.as_tensor(self.max_val, device=input.device, dtype=input.dtype))
class RandomChannelShuffle(IntensityAugmentationBase2D):
diff --git a/kornia/augmentation/augmentation3d.py b/kornia/augmentation/augmentation3d.py
index 8361adac4..31a606d1a 100644
--- a/kornia/augmentation/augmentation3d.py
+++ b/kornia/augmentation/augmentation3d.py
@@ -19,7 +19,7 @@ from kornia.geometry.transform.affwarp import _compute_rotation_matrix3d, _compu
from kornia.utils import _extract_device_dtype
from . import random_generator as rg
-from .base import AugmentationBase3D
+from .base import AugmentationBase3D, TensorWithTransformMat
from .utils import _range_bound, _singular_range_check, _tuple_range_reader
@@ -900,10 +900,10 @@ class RandomCrop3D(AugmentationBase3D):
def forward( # type: ignore
self,
- input: Union[torch.Tensor, Tuple[torch.Tensor, torch.Tensor]],
+ input: TensorWithTransformMat,
params: Optional[Dict[str, torch.Tensor]] = None,
return_transform: Optional[bool] = None,
- ) -> Union[torch.Tensor, Tuple[torch.Tensor, torch.Tensor]]:
+ ) -> TensorWithTransformMat:
if type(input) is tuple:
input = (self.precrop_padding(input[0]), input[1])
else:
diff --git a/kornia/augmentation/base.py b/kornia/augmentation/base.py
index 508548fb2..67f0f163d 100644
--- a/kornia/augmentation/base.py
+++ b/kornia/augmentation/base.py
@@ -16,6 +16,8 @@ from .utils import (
_validate_input_dtype,
)
+TensorWithTransformMat = Union[torch.Tensor, Tuple[torch.Tensor, torch.Tensor]]
+
class _BasicAugmentationBase(nn.Module):
r"""_BasicAugmentationBase base class for customized augmentation implementations.
@@ -54,7 +56,7 @@ class _BasicAugmentationBase(nn.Module):
def __unpack_input__(self, input: torch.Tensor) -> torch.Tensor:
return input
- def __check_batching__(self, input: Union[torch.Tensor, Tuple[torch.Tensor, torch.Tensor]]):
+ def __check_batching__(self, input: TensorWithTransformMat):
"""Check if a transformation matrix is returned,
it has to be in the same batching mode as output."""
raise NotImplementedError
@@ -102,7 +104,7 @@ class _BasicAugmentationBase(nn.Module):
batch_prob = batch_prob.repeat(batch_shape[0])
return batch_prob
- def forward_parameters(self, batch_shape):
+ def forward_parameters(self, batch_shape) -> Dict[str, torch.Tensor]:
to_apply = self.__batch_prob_generator__(batch_shape, self.p, self.p_batch, self.same_on_batch)
_params = self.generate_parameters(torch.Size((int(to_apply.sum().item()), *batch_shape[1:])))
if _params is None:
@@ -110,15 +112,13 @@ class _BasicAugmentationBase(nn.Module):
_params['batch_prob'] = to_apply
return _params
- def apply_func(
- self, input: torch.Tensor, params: Dict[str, torch.Tensor]
- ) -> Union[torch.Tensor, Tuple[torch.Tensor, torch.Tensor]]:
+ def apply_func(self, input: torch.Tensor, params: Dict[str, torch.Tensor]) -> TensorWithTransformMat:
input = self.transform_tensor(input)
return self.apply_transform(input, params)
def forward( # type: ignore
self, input: torch.Tensor, params: Optional[Dict[str, torch.Tensor]] = None # type: ignore
- ) -> Union[torch.Tensor, Tuple[torch.Tensor, torch.Tensor]]:
+ ) -> TensorWithTransformMat:
in_tensor = self.__unpack_input__(input)
self.__check_batching__(input)
ori_shape = in_tensor.shape
@@ -177,7 +177,7 @@ class _AugmentationBase(_BasicAugmentationBase):
raise NotImplementedError
def __unpack_input__( # type: ignore
- self, input: Union[torch.Tensor, Tuple[torch.Tensor, torch.Tensor]]
+ self, input: TensorWithTransformMat
) -> Tuple[torch.Tensor, Optional[torch.Tensor]]:
if isinstance(input, tuple):
in_tensor = input[0]
@@ -192,7 +192,7 @@ class _AugmentationBase(_BasicAugmentationBase):
in_transform: Optional[torch.Tensor], # type: ignore
params: Dict[str, torch.Tensor],
return_transform: bool = False,
- ) -> Union[torch.Tensor, Tuple[torch.Tensor, torch.Tensor]]:
+ ) -> TensorWithTransformMat:
to_apply = params['batch_prob']
# if no augmentation needed
@@ -222,10 +222,10 @@ class _AugmentationBase(_BasicAugmentationBase):
def forward( # type: ignore
self,
- input: Union[torch.Tensor, Tuple[torch.Tensor, torch.Tensor]],
+ input: TensorWithTransformMat,
params: Optional[Dict[str, torch.Tensor]] = None, # type: ignore
return_transform: Optional[bool] = None,
- ) -> Union[torch.Tensor, Tuple[torch.Tensor, torch.Tensor]]:
+ ) -> TensorWithTransformMat:
in_tensor, in_transform = self.__unpack_input__(input)
self.__check_batching__(input)
ori_shape = in_tensor.shape
@@ -264,7 +264,7 @@ class AugmentationBase2D(_AugmentationBase):
form ``False``.
"""
- def __check_batching__(self, input: Union[torch.Tensor, Tuple[torch.Tensor, torch.Tensor]]):
+ def __check_batching__(self, input: TensorWithTransformMat):
if isinstance(input, tuple):
inp, mat = input
if len(inp.shape) == 4:
@@ -358,7 +358,7 @@ class GeometricAugmentationBase2D(AugmentationBase2D):
def inverse(
self,
- input: Union[torch.Tensor, Tuple[torch.Tensor, torch.Tensor]],
+ input: TensorWithTransformMat,
params: Optional[Dict[str, torch.Tensor]] = None,
size: Optional[Tuple[int, int]] = None,
**kwargs,
@@ -414,7 +414,7 @@ class AugmentationBase3D(_AugmentationBase):
same_on_batch: apply the same transformation across the batch.
"""
- def __check_batching__(self, input: Union[torch.Tensor, Tuple[torch.Tensor, torch.Tensor]]):
+ def __check_batching__(self, input: TensorWithTransformMat):
if isinstance(input, tuple):
inp, mat = input
if len(inp.shape) == 5:
@@ -455,7 +455,7 @@ class MixAugmentationBase(_BasicAugmentationBase):
def __init__(self, p: float, p_batch: float, same_on_batch: bool = False, keepdim: bool = False) -> None:
super(MixAugmentationBase, self).__init__(p, p_batch=p_batch, same_on_batch=same_on_batch, keepdim=keepdim)
- def __check_batching__(self, input: Union[torch.Tensor, Tuple[torch.Tensor, torch.Tensor]]):
+ def __check_batching__(self, input: TensorWithTransformMat):
if isinstance(input, tuple):
inp, mat = input
if len(inp.shape) == 4:
@@ -468,18 +468,28 @@ class MixAugmentationBase(_BasicAugmentationBase):
else:
raise ValueError(f'Unrecognized output shape. Expected 2, 3, or 4, got {len(inp.shape)}')
+ def __unpack_input__( # type: ignore
+ self, input: TensorWithTransformMat
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor]]:
+ if isinstance(input, tuple):
+ in_tensor = input[0]
+ in_transformation = input[1]
+ return in_tensor, in_transformation
+ in_tensor = input
+ return in_tensor, None
+
def transform_tensor(self, input: torch.Tensor) -> torch.Tensor:
"""Convert any incoming (H, W), (C, H, W) and (B, C, H, W) into (B, C, H, W)."""
_validate_input_dtype(input, accepted_dtypes=[torch.float16, torch.float32, torch.float64])
return _transform_input(input)
def apply_transform( # type: ignore
- self, input: torch.Tensor, label: torch.Tensor, params: Dict[str, torch.Tensor] # type: ignore
+ self, input: torch.Tensor, label: torch.Tensor, params: Dict[str, torch.Tensor]
) -> Tuple[torch.Tensor, torch.Tensor]:
raise NotImplementedError
def apply_func( # type: ignore
- self, in_tensor: torch.Tensor, label: torch.Tensor, params: Dict[str, torch.Tensor] # type: ignore
+ self, in_tensor: torch.Tensor, label: torch.Tensor, params: Dict[str, torch.Tensor]
) -> Tuple[torch.Tensor, torch.Tensor]:
to_apply = params['batch_prob']
@@ -497,15 +507,28 @@ class MixAugmentationBase(_BasicAugmentationBase):
return output, label
def forward( # type: ignore
- self, input: torch.Tensor, label: torch.Tensor, params: Optional[Dict[str, torch.Tensor]] = None # type: ignore
- ) -> Tuple[torch.Tensor, torch.Tensor]:
- in_tensor = self.__unpack_input__(input)
+ self,
+ input: TensorWithTransformMat,
+ label: Optional[torch.Tensor] = None,
+ params: Optional[Dict[str, torch.Tensor]] = None,
+ ) -> Tuple[TensorWithTransformMat, torch.Tensor]:
+ in_tensor, in_trans = self.__unpack_input__(input)
ori_shape = in_tensor.shape
in_tensor = self.transform_tensor(in_tensor)
+ # If label is not provided, it would output the indices instead.
+ if label is None:
+ if isinstance(input, (tuple, list)):
+ device = input[0].device
+ else:
+ device = input.device
+ label = torch.arange(0, in_tensor.size(0), device=device, dtype=torch.long)
if params is None:
batch_shape = in_tensor.shape
params = self.forward_parameters(batch_shape)
self._params = params
- output = self.apply_func(in_tensor, label, self._params)
- return _transform_output_shape(output, ori_shape) if self.keepdim else output # type: ignore
+ output, lab = self.apply_func(in_tensor, label, self._params)
+ output = _transform_output_shape(output, ori_shape) if self.keepdim else output # type: ignore
+ if in_trans is not None:
+ return (output, in_trans), lab
+ return output, lab
diff --git a/kornia/augmentation/container/augment.py b/kornia/augmentation/container/augment.py
index 116236fc1..168519727 100644
--- a/kornia/augmentation/container/augment.py
+++ b/kornia/augmentation/container/augment.py
@@ -5,7 +5,13 @@ from typing import cast, Dict, List, Optional, Tuple, Union
import torch
import torch.nn as nn
-from kornia.augmentation.base import _AugmentationBase, GeometricAugmentationBase2D, IntensityAugmentationBase2D
+from kornia.augmentation.base import (
+ _AugmentationBase,
+ GeometricAugmentationBase2D,
+ IntensityAugmentationBase2D,
+ TensorWithTransformMat,
+)
+from kornia.augmentation.container.base import SequentialBase
from kornia.constants import DataKey
from kornia.geometry.bbox import transform_bbox
from kornia.geometry.linalg import transform_points
@@ -42,8 +48,9 @@ class AugmentationSequential(ImageSequential):
If True, the whole list of args will be processed as a sequence in a random order.
If False, the whole list of args will be processed as a sequence in original order.
- Return:
- the tensor (, and the transformation matrix) has been sequentially modified by the args.
+ Note:
+ Mix augmentations (e.g. RandomMixUp, RandomCutMix) can only be working with "input" data key.
+ It is not clear how to deal with the conversions of masks, bounding boxes and keypoints.
Examples:
>>> import kornia
@@ -149,65 +156,56 @@ class AugmentationSequential(ImageSequential):
def apply_by_key(
self,
- input: Union[torch.Tensor, Tuple[torch.Tensor, torch.Tensor]],
- module_name: str,
- module: Optional[nn.Module] = None,
- param: Optional[ParamItem] = None,
+ input: TensorWithTransformMat,
+ label: Optional[torch.Tensor],
+ module: Optional[nn.Module],
+ param: ParamItem,
dcate: Union[str, int, DataKey] = DataKey.INPUT,
- ) -> Union[torch.Tensor, Tuple[torch.Tensor, torch.Tensor]]:
- if param is not None:
- assert module_name == param.name
+ ) -> Tuple[TensorWithTransformMat, Optional[torch.Tensor]]:
if module is None:
- # TODO (jian): double check why typing is crashing
- module = self.get_submodule(module_name) # type: ignore
+ module = self.get_submodule(param.name)
if DataKey.get(dcate) in [DataKey.INPUT]:
- return self.apply_to_input(input, module_name, module, param)
+ return self.apply_to_input(input, label, module=module, param=param)
if DataKey.get(dcate) in [DataKey.MASK]:
if isinstance(input, (tuple,)):
- return (self.apply_to_mask(input[0], module, param), *input[1:])
- return self.apply_to_mask(input, module, param)
+ return (self.apply_to_mask(input[0], module, param), *input[1:]), None
+ return self.apply_to_mask(input, module, param), None
if DataKey.get(dcate) in [DataKey.BBOX, DataKey.BBOX_XYXY]:
if isinstance(input, (tuple,)):
- return (self.apply_to_bbox(input[0], module, param, mode='xyxy'), *input[1:])
- return self.apply_to_bbox(input, module, param, mode='xyxy')
+ return (self.apply_to_bbox(input[0], module, param, mode='xyxy'), *input[1:]), None
+ return self.apply_to_bbox(input, module, param, mode='xyxy'), None
if DataKey.get(dcate) in [DataKey.BBOX_XYHW]:
if isinstance(input, (tuple,)):
- return (self.apply_to_bbox(input[0], module, param, mode='xyhw'), *input[1:])
- return self.apply_to_bbox(input, module, param, mode='xyhw')
+ return (self.apply_to_bbox(input[0], module, param, mode='xyhw'), *input[1:]), None
+ return self.apply_to_bbox(input, module, param, mode='xyhw'), None
if DataKey.get(dcate) in [DataKey.KEYPOINTS]:
if isinstance(input, (tuple,)):
- return (self.apply_to_keypoints(input[0], module, param), *input[1:])
- return self.apply_to_keypoints(input, module, param)
+ return (self.apply_to_keypoints(input[0], module, param), *input[1:]), None
+ return self.apply_to_keypoints(input, module, param), None
raise NotImplementedError(f"input type of {dcate} is not implemented.")
- def inverse_input(
- self, input: torch.Tensor, module: nn.Module, param: Optional[Dict[str, torch.Tensor]] = None
- ) -> torch.Tensor:
- if isinstance(module, GeometricAugmentationBase2D) and param is None:
- input = module.inverse(input)
- elif isinstance(module, GeometricAugmentationBase2D) and param is not None:
- input = module.inverse(input, param)
- else:
- pass # No need to update anything
+ def inverse_input(self, input: torch.Tensor, module: nn.Module, param: Optional[ParamItem] = None) -> torch.Tensor:
+ if isinstance(module, GeometricAugmentationBase2D):
+ input = module.inverse(input, None if param is None else cast(Dict, param.data))
return input
def inverse_bbox(
- self,
- input: torch.Tensor,
- module: nn.Module,
- param: Optional[Dict[str, torch.Tensor]] = None,
- mode: str = "xyxy",
+ self, input: torch.Tensor, module: nn.Module, param: Optional[ParamItem] = None, mode: str = "xyxy"
) -> torch.Tensor:
if isinstance(module, GeometricAugmentationBase2D):
- transform = module.compute_inverse_transformation(module.get_transformation_matrix(input, param))
+ transform = module.compute_inverse_transformation(
+ module.get_transformation_matrix(input, None if param is None else cast(Dict, param.data))
+ )
input = transform_bbox(torch.as_tensor(transform, device=input.device, dtype=input.dtype), input, mode)
return input
def inverse_keypoints(
- self, input: torch.Tensor, module: nn.Module, param: Optional[Dict[str, torch.Tensor]] = None
+ self, input: torch.Tensor, module: nn.Module, param: Optional[ParamItem] = None
) -> torch.Tensor:
if isinstance(module, GeometricAugmentationBase2D):
- transform = module.compute_inverse_transformation(module.get_transformation_matrix(input, param))
+ transform = module.compute_inverse_transformation(
+ module.get_transformation_matrix(input, None if param is None else cast(Dict, param.data))
+ )
input = transform_points(torch.as_tensor(transform, device=input.device, dtype=input.dtype), input)
return input
@@ -215,7 +213,7 @@ class AugmentationSequential(ImageSequential):
self,
input: torch.Tensor,
module: nn.Module,
- param: Optional[Dict[str, torch.Tensor]] = None,
+ param: Optional[ParamItem] = None,
dcate: Union[str, int, DataKey] = DataKey.INPUT,
) -> torch.Tensor:
if DataKey.get(dcate) in [DataKey.INPUT, DataKey.MASK]:
@@ -244,10 +242,14 @@ class AugmentationSequential(ImageSequential):
assert len(args) == len(data_keys), (
"The number of inputs must align with the number of data_keys, " f"Got {len(args)} and {len(data_keys)}."
)
- if params is None and self._params is None:
- raise ValueError("No parameters avaliable for inversing.")
- else:
- params = self._params
+ if params is None:
+ if self._params is None:
+ raise ValueError(
+ "No parameters avaliable for inversing, please run a forward pass first "
+ "or passing valid params into this function."
+ )
+ else:
+ params = self._params
outputs = []
for input, dcate in zip(args, data_keys):
@@ -255,9 +257,6 @@ class AugmentationSequential(ImageSequential):
input, _ = input # ignore the transformation matrix whilst inverse
for (name, module), param in zip_longest(list(self.get_forward_sequence(params))[::-1], params[::-1]):
if isinstance(module, _AugmentationBase):
- # Check if a param recorded
- param = self._params[name] if name in self._params else None
- # Check if a param provided. If provided, it will overwrite the recorded ones.
param = params[name] if name in params else param
else:
param = None
@@ -268,50 +267,94 @@ class AugmentationSequential(ImageSequential):
pass # Do nothing
elif isinstance(module, PatchSequential) and module.is_intensity_only() and dcate in DataKey:
pass # Do nothing
+ elif isinstance(module, (SequentialBase,)):
+ raise ValueError("Sequential is currently unsupported.")
else:
raise NotImplementedError(f"data_key {dcate} is not implemented for {module}.")
outputs.append(input)
- if len(outputs) == 1:
+ if len(outputs) == 1 and isinstance(outputs, (tuple, list)):
return outputs[0]
return outputs
+ def __packup_output__( # type: ignore
+ self, output: List[TensorWithTransformMat], label: Optional[torch.Tensor] = None
+ ) -> Union[
+ TensorWithTransformMat,
+ Tuple[TensorWithTransformMat, Optional[torch.Tensor]],
+ List[TensorWithTransformMat],
+ Tuple[List[TensorWithTransformMat], Optional[torch.Tensor]],
+ ]:
+ if len(output) == 1 and isinstance(output, (tuple, list)) and self.return_label:
+ return output[0], label
+ if len(output) == 1 and isinstance(output, (tuple, list)):
+ return output[0]
+ if self.return_label:
+ return output, label
+ return output
+
def forward( # type: ignore
self,
- *args: Union[torch.Tensor, Tuple[torch.Tensor, torch.Tensor]],
+ *args: TensorWithTransformMat,
+ label: Optional[torch.Tensor] = None,
params: Optional[List[ParamItem]] = None,
data_keys: Optional[List[Union[str, int, DataKey]]] = None,
) -> Union[
- torch.Tensor, Tuple[torch.Tensor, torch.Tensor], List[Union[torch.Tensor, Tuple[torch.Tensor, torch.Tensor]]]
+ TensorWithTransformMat,
+ Tuple[TensorWithTransformMat, Optional[torch.Tensor]],
+ List[TensorWithTransformMat],
+ Tuple[List[TensorWithTransformMat], Optional[torch.Tensor]],
]:
"""Compute multiple tensors simultaneously according to ``self.data_keys``."""
if data_keys is None:
data_keys = cast(List[Union[str, int, DataKey]], self.data_keys)
+ else:
+ data_keys = [DataKey.get(inp) for inp in data_keys]
assert len(args) == len(
data_keys
), f"The number of inputs must align with the number of data_keys. Got {len(args)} and {len(data_keys)}."
- outputs = []
- self._params = []
- named_modules = list(self.get_forward_sequence(params))
- for input, dcate in zip(args, data_keys):
- # use the parameter if the first round has been finished.
- params = self._params if params is None or len(params) == 0 else params
- for param, (name, module) in zip_longest(params, named_modules):
+ if params is None:
+ if DataKey.INPUT in data_keys:
+ _input = args[data_keys.index(DataKey.INPUT)]
+ if isinstance(_input, (tuple, list)):
+ params = self.forward_parameters(_input[0].shape)
+ else:
+ params = self.forward_parameters(_input.shape)
+ else:
+ raise ValueError("`params` must be provided whilst INPUT is not in data_keys.")
+
+ outputs: List[TensorWithTransformMat] = [None] * len(data_keys) # type: ignore
+ if DataKey.INPUT in data_keys:
+ idx = data_keys.index(DataKey.INPUT)
+ out = super().forward(args[idx], label, params=params)
+ if self.return_label:
+ input, label = cast(Tuple[TensorWithTransformMat, torch.Tensor], out)
+ else:
+ input = cast(TensorWithTransformMat, out)
+ outputs[idx] = input
+
+ self.return_label = label is not None or self.contains_label_operations(params)
+
+ for idx, (input, dcate, out) in enumerate(zip(args, data_keys, outputs)):
+ if out is not None:
+ continue
+ for param in params:
+ module = self.get_submodule(param.name)
if dcate == DataKey.INPUT:
- input = self.apply_to_input(input, name, module, param)
+ input, label = self.apply_to_input(input, label, module=module, param=param)
elif isinstance(module, GeometricAugmentationBase2D) and dcate in DataKey:
- input = self.apply_by_key(input, name, module, param, dcate)
+ input, label = self.apply_by_key(input, label, module, param, dcate)
elif isinstance(module, IntensityAugmentationBase2D) and dcate in DataKey:
pass # Do nothing
elif isinstance(module, PatchSequential) and module.is_intensity_only() and dcate in DataKey:
pass # Do nothing
+ elif isinstance(module, (SequentialBase,)):
+ raise ValueError("Sequential is currently unsupported.")
else:
raise NotImplementedError(f"data_key {dcate} is not implemented for {module}.")
- outputs.append(input)
- if len(outputs) == 1:
- return outputs[0]
+ outputs[idx] = input
- return outputs
+ return self.__packup_output__(outputs, label)
diff --git a/kornia/augmentation/container/base.py b/kornia/augmentation/container/base.py
new file mode 100644
index 000000000..27eaef808
--- /dev/null
+++ b/kornia/augmentation/container/base.py
@@ -0,0 +1,161 @@
+from collections import OrderedDict
+from typing import Any, Iterator, List, NamedTuple, Optional, Tuple, Union
+
+import torch
+import torch.nn as nn
+
+from kornia.augmentation.base import _AugmentationBase, MixAugmentationBase
+
+__all__ = ["SequentialBase", "ParamItem"]
+
+
+class ParamItem(NamedTuple):
+ name: str
+ data: Optional[Union[dict, list]]
+
+
+class SequentialBase(nn.Sequential):
+ r"""SequentialBase for creating kornia modulized processing pipeline.
+
+ Args:
+ *args : a list of kornia augmentation and image operation modules.
+ same_on_batch: apply the same transformation across the batch.
+ If None, it will not overwrite the function-wise settings.
+ return_transform: if ``True`` return the matrix describing the transformation
+ applied to each. If None, it will not overwrite the function-wise settings.
+ keepdim: whether to keep the output shape the same as input (True) or broadcast it
+ to the batch form (False). If None, it will not overwrite the function-wise settings.
+ """
+
+ def __init__(
+ self,
+ *args: nn.Module,
+ same_on_batch: Optional[bool] = None,
+ return_transform: Optional[bool] = None,
+ keepdim: Optional[bool] = None,
+ ) -> None:
+ # To name the modules properly
+ _args = OrderedDict()
+ for idx, mod in enumerate(args):
+ if not isinstance(mod, nn.Module):
+ raise NotImplementedError(f"Only nn.Module are supported at this moment. Got {mod}.")
+ _args.update({f"{mod.__class__.__name__}_{idx}": mod})
+ super().__init__(_args)
+ self._same_on_batch = same_on_batch
+ self._return_transform = return_transform
+ self._keepdim = keepdim
+ self._params: Optional[List[Any]] = None
+ self.update_attribute(same_on_batch, return_transform, keepdim)
+
+ def update_attribute(
+ self,
+ same_on_batch: Optional[bool] = None,
+ return_transform: Optional[bool] = None,
+ keepdim: Optional[bool] = None,
+ ) -> None:
+ for mod in self.children():
+ # MixAugmentation does not have return transform
+ if isinstance(mod, (_AugmentationBase, MixAugmentationBase)):
+ if same_on_batch is not None:
+ mod.same_on_batch = same_on_batch
+ if keepdim is not None:
+ mod.keepdim = keepdim
+ if isinstance(mod, _AugmentationBase):
+ if return_transform is not None:
+ mod.return_transform = return_transform
+
+ def get_submodule(self, target: str) -> nn.Module:
+ """Get submodule.
+
+ This code is taken from torch 1.9.0 since it is not introduced
+ back to torch 1.7.1. We included this for maintaining more
+ backward torch versions.
+
+ Args:
+ target: The fully-qualified string name of the submodule
+ to look for. (See above example for how to specify a
+ fully-qualified string.)
+
+ Returns:
+ torch.nn.Module: The submodule referenced by ``target``
+
+ Raises:
+ AttributeError: If the target string references an invalid
+ path or resolves to something that is not an
+ ``nn.Module``
+ """
+ if target == "":
+ return self
+
+ atoms: List[str] = target.split(".")
+ mod: torch.nn.Module = self
+
+ for item in atoms:
+
+ if not hasattr(mod, item):
+ raise AttributeError(mod._get_name() + " has no " "attribute `" + item + "`")
+
+ mod = getattr(mod, item)
+
+ if not isinstance(mod, torch.nn.Module):
+ raise AttributeError("`" + item + "` is not " "an nn.Module")
+
+ return mod
+
+ @property
+ def same_on_batch(self) -> Optional[bool]:
+ return self._same_on_batch
+
+ @same_on_batch.setter
+ def same_on_batch(self, same_on_batch: Optional[bool]) -> None:
+ self._same_on_batch = same_on_batch
+ self.update_attribute(same_on_batch=same_on_batch)
+
+ @property
+ def return_transform(self) -> Optional[bool]:
+ return self._return_transform
+
+ @return_transform.setter
+ def return_transform(self, return_transform: Optional[bool]) -> None:
+ self._return_transform = return_transform
+ self.update_attribute(return_transform=return_transform)
+
+ @property
+ def keepdim(self) -> Optional[bool]:
+ return self._keepdim
+
+ @keepdim.setter
+ def keepdim(self, keepdim: Optional[bool]) -> None:
+ self._keepdim = keepdim
+ self.update_attribute(keepdim=keepdim)
+
+ def clear_state(self) -> None:
+ self._params = None
+
+ def update_params(self, param: Any) -> None:
+ if self._params is None:
+ self._params = [param]
+ else:
+ self._params.append(param)
+
+ # TODO: Implement this for all submodules.
+ def forward_parameters(self, batch_shape: torch.Size) -> List[ParamItem]:
+ raise NotImplementedError
+
+ def get_children_by_indices(self, indices: torch.Tensor) -> Iterator[Tuple[str, nn.Module]]:
+ modules = list(self.named_children())
+ for idx in indices:
+ yield modules[idx]
+
+ def get_children_by_params(self, params: List[ParamItem]) -> Iterator[Tuple[str, nn.Module]]:
+ modules = list(self.named_children())
+ for param in params:
+ yield modules[list(dict(self.named_children()).keys()).index(param.name)]
+
+ def get_params_by_module(self, named_modules: Iterator[Tuple[str, nn.Module]]) -> Iterator[ParamItem]:
+ # This will not take module._params
+ for name, _ in named_modules:
+ yield ParamItem(name, None)
+
+ def contains_label_operations(self, params: List) -> bool:
+ raise NotImplementedError
diff --git a/kornia/augmentation/container/image.py b/kornia/augmentation/container/image.py
index 50f9662f4..305284ccf 100644
--- a/kornia/augmentation/container/image.py
+++ b/kornia/augmentation/container/image.py
@@ -1,21 +1,17 @@
-from collections import OrderedDict
-from itertools import zip_longest
-from typing import Any, Iterator, List, NamedTuple, Optional, Tuple, Union
+from typing import Iterator, List, Optional, Tuple, Union
import torch
import torch.nn as nn
-from kornia.augmentation.base import _AugmentationBase
-
-__all__ = ["ImageSequential"]
+from kornia.augmentation.base import _AugmentationBase, MixAugmentationBase, TensorWithTransformMat
+from .base import ParamItem, SequentialBase
-class ParamItem(NamedTuple):
- name: str
- data: Union[dict, list]
+__all__ = ["ImageSequential"]
-class ImageSequential(nn.Sequential):
+# TODO: Add forward_parameters for ImageSequential
+class ImageSequential(SequentialBase):
r"""Sequential for creating kornia image processing pipeline.
Args:
@@ -34,34 +30,36 @@ class ImageSequential(nn.Sequential):
If True, the whole list of args will be processed as a sequence in a random order.
If False, the whole list of args will be processed as a sequence in original order.
- Returns:
- the tensor (, and the transformation matrix) has been sequentially modified by the args.
+ Note:
+ Transformation matrix returned only considers the transformation applied in ``kornia.augmentation`` module.
+ Those transformations in ``kornia.geometry`` will not be taken into account.
Examples:
+ >>> _ = torch.manual_seed(77)
>>> import kornia
- >>> input = torch.randn(2, 3, 5, 6)
+ >>> input, label = torch.randn(2, 3, 5, 6), torch.tensor([0, 1])
>>> aug_list = ImageSequential(
... kornia.color.BgrToRgb(),
... kornia.augmentation.ColorJitter(0.1, 0.1, 0.1, 0.1, p=1.0),
... kornia.filters.MedianBlur((3, 3)),
... kornia.augmentation.RandomAffine(360, p=1.0),
... kornia.enhance.Invert(),
+ ... kornia.augmentation.RandomMixUp(p=1.0),
... return_transform=True,
... same_on_batch=True,
... random_apply=10,
... )
- >>> out = aug_list(input)
+ >>> out, lab = aug_list(input, label=label)
+ >>> lab
+ tensor([[0.0000, 1.0000, 0.1214],
+ [1.0000, 0.0000, 0.1214]])
>>> out[0].shape, out[1].shape
(torch.Size([2, 3, 5, 6]), torch.Size([2, 3, 3]))
Reproduce with provided params.
- >>> out2 = aug_list(input, params=aug_list._params)
- >>> torch.equal(out[0], out2[0]), torch.equal(out[1], out2[1])
- (True, True)
-
- Note:
- Transformation matrix returned only considers the transformation applied in ``kornia.augmentation`` module.
- Those transformations in ``kornia.geometry`` will not be taken into account.
+ >>> out2, lab2 = aug_list(input, label=label, params=aug_list._params)
+ >>> torch.equal(out[0], out2[0]), torch.equal(out[1], out2[1]), torch.equal(lab[1], lab2[1])
+ (True, True, True)
"""
def __init__(
@@ -72,118 +70,159 @@ class ImageSequential(nn.Sequential):
keepdim: Optional[bool] = None,
random_apply: Union[int, bool, Tuple[int, int]] = False,
) -> None:
- self.same_on_batch = same_on_batch
- self.return_transform = return_transform
- self.keepdim = keepdim
- # To name the modules properly
- _args = OrderedDict()
- for idx, arg in enumerate(args):
- if not isinstance(arg, nn.Module):
- raise NotImplementedError(f"Only nn.Module are supported at this moment. Got {arg}.")
- if isinstance(arg, _AugmentationBase):
- if same_on_batch is not None:
- arg.same_on_batch = same_on_batch
- if return_transform is not None:
- arg.return_transform = return_transform
- if keepdim is not None:
- arg.keepdim = keepdim
- _args.update({f"{arg.__class__.__name__}_{idx}": arg})
- super(ImageSequential, self).__init__(_args)
-
- self._params: List[Any] = []
- self.random_apply: Union[Tuple[int, int], bool]
- if random_apply:
- if isinstance(random_apply, (bool,)) and random_apply is True:
- self.random_apply = (len(args), len(args) + 1)
- elif isinstance(random_apply, (int,)):
- self.random_apply = (random_apply, random_apply + 1)
- elif (
+ super(ImageSequential, self).__init__(
+ *args, same_on_batch=same_on_batch, return_transform=return_transform, keepdim=keepdim
+ )
+
+ self.random_apply: Union[Tuple[int, int], bool] = self._read_random_apply(random_apply, len(args))
+ self.return_label: Optional[bool] = None
+
+ def _read_random_apply(
+ self, random_apply: Union[int, bool, Tuple[int, int]], max_length: int
+ ) -> Union[Tuple[int, int], bool]:
+ if isinstance(random_apply, (bool,)) and random_apply is False:
+ random_apply = False
+ elif isinstance(random_apply, (bool,)) and random_apply is True:
+ random_apply = (max_length, max_length + 1)
+ elif isinstance(random_apply, (int,)):
+ random_apply = (random_apply, random_apply + 1)
+ elif (
+ isinstance(random_apply, (tuple,))
+ and len(random_apply) == 2
+ and isinstance(random_apply[0], (int,))
+ and isinstance(random_apply[1], (int,))
+ ):
+ random_apply = (random_apply[0], random_apply[1] + 1)
+ elif isinstance(random_apply, (tuple,)) and len(random_apply) == 1 and isinstance(random_apply[0], (int,)):
+ random_apply = (random_apply[0], max_length + 1)
+ else:
+ raise ValueError(f"Non-readable random_apply. Got {random_apply}.")
+ if random_apply is not False:
+ assert (
isinstance(random_apply, (tuple,))
and len(random_apply) == 2
and isinstance(random_apply[0], (int,))
- and isinstance(random_apply[1], (int,))
- ):
- self.random_apply = (random_apply[0], random_apply[1] + 1)
- elif isinstance(random_apply, (tuple,)) and len(random_apply) == 1 and isinstance(random_apply[0], (int,)):
- self.random_apply = (random_apply[0], len(args) + 1)
- else:
- raise ValueError(f"Non-readable random_apply. Got {random_apply}.")
- assert (
- isinstance(self.random_apply, (tuple,))
- and len(self.random_apply) == 2
- and isinstance(self.random_apply[0], (int,))
- and isinstance(self.random_apply[0], (int,))
- ), f"Expect a tuple of (int, int). Got {self.random_apply}."
- else:
- self.random_apply = False
-
- def _get_child_sequence(self) -> Iterator[Tuple[str, nn.Module]]:
- if self.random_apply:
- # random_apply will not be boolean here.
- num_samples = int(torch.randint(*self.random_apply, (1,)).item()) # type: ignore
- indices = torch.multinomial(
- torch.ones((len(self),)), num_samples, replacement=True if num_samples > len(self) else False
- )
- return self._get_children_by_indices(indices)
- return self.named_children()
-
- def _get_children_by_indices(self, indices: torch.Tensor) -> Iterator[Tuple[str, nn.Module]]:
- modules = list(self.named_children())
- for idx in indices:
- yield modules[idx]
-
- def _get_children_by_module_names(self, names: List[str]) -> Iterator[Tuple[str, nn.Module]]:
- modules = list(self.named_children())
- for name in names:
- yield modules[list(dict(self.named_children()).keys()).index(name)]
+ and isinstance(random_apply[0], (int,))
+ ), f"Expect a tuple of (int, int). Got {random_apply}."
+ return random_apply
+
+ def get_random_forward_sequence(self, with_mix: bool = True) -> Tuple[Iterator[Tuple[str, nn.Module]], bool]:
+ num_samples = int(torch.randint(*self.random_apply, (1,)).item()) # type: ignore
+ multinomial_weights = torch.ones((len(self),))
+ # Mix augmentation can only be applied once per forward
+ mix_indices = self.get_mix_augmentation_indices(self.named_children())
+ # kick out the mix augmentations
+ multinomial_weights[mix_indices] = 0
+ indices = torch.multinomial(
+ multinomial_weights,
+ num_samples,
+ # enable replacement if non-mix augmentation is less than required
+ replacement=True if num_samples > multinomial_weights.sum() else False,
+ )
+
+ mix_added = False
+ if with_mix and len(mix_indices) != 0:
+ # Make the selection fair.
+ if (torch.rand(1) < ((len(mix_indices) + len(indices)) / len(self))).item():
+ indices[-1] = torch.multinomial((~multinomial_weights.bool()).float(), 1)
+ indices = indices[torch.randperm(len(indices))]
+ mix_added = True
+
+ return self.get_children_by_indices(indices), mix_added
+
+ def get_mix_augmentation_indices(self, named_modules: Iterator[Tuple[str, nn.Module]]) -> List[int]:
+ indices = []
+ for idx, (_, child) in enumerate(named_modules):
+ if isinstance(child, (MixAugmentationBase,)):
+ indices.append(idx)
+ return indices
def get_forward_sequence(self, params: Optional[List[ParamItem]] = None) -> Iterator[Tuple[str, nn.Module]]:
if params is None:
- named_modules = self._get_child_sequence()
- else:
- named_modules = self._get_children_by_module_names([p.name for p in params])
- return named_modules
+ # Mix augmentation can only be applied once per forward
+ mix_indices = self.get_mix_augmentation_indices(self.named_children())
+
+ if self.random_apply:
+ return self.get_random_forward_sequence()[0]
+
+ if len(mix_indices) > 1:
+ raise ValueError(
+ "Multiple mix augmentation is prohibited without enabling random_apply."
+ f"Detected {len(mix_indices)}."
+ )
+
+ return self.named_children()
+
+ return self.get_children_by_params(params)
def apply_to_input(
self,
- input: Union[torch.Tensor, Tuple[torch.Tensor, torch.Tensor]],
- module_name: str,
- module: Optional[nn.Module] = None,
- param: Optional[ParamItem] = None,
- ) -> Union[torch.Tensor, Tuple[torch.Tensor, torch.Tensor]]:
+ input: TensorWithTransformMat,
+ label: Optional[torch.Tensor],
+ module: Optional[nn.Module],
+ param: ParamItem,
+ ) -> Tuple[TensorWithTransformMat, Optional[torch.Tensor]]:
if module is None:
- # TODO (jian): double check why typing is crashing
- module = self.get_submodule(module_name) # type: ignore
- if param is not None:
- assert module_name == param.name
- _param = param.data
- else:
- _param = None # type: ignore
-
- if isinstance(module, (_AugmentationBase, ImageSequential)) and _param is None:
- input = module(input)
- self._params.append(ParamItem(module_name, module._params))
- elif isinstance(module, (_AugmentationBase, ImageSequential)) and _param is not None:
- input = module(input, params=_param)
- self._params.append(ParamItem(module_name, _param))
+ module = self.get_submodule(param.name)
+ if isinstance(module, (MixAugmentationBase,)):
+ input, label = module(input, label, params=param.data)
+ elif isinstance(module, (_AugmentationBase, ImageSequential)):
+ input = module(input, params=param.data)
else:
- assert (
- _param == {} or _param is None
- ), f"Non-augmentaion operation {module_name} require empty parameters. Got {module}."
+ assert param.data is None, f"Non-augmentaion operation {param.name} require empty parameters. Got {param}."
# In case of return_transform = True
if isinstance(input, (tuple, list)):
input = (module(input[0]), input[1])
else:
input = module(input)
- self._params.append(ParamItem(module_name, {}))
- return input
-
- def forward(
- self, input: Union[torch.Tensor, Tuple[torch.Tensor, torch.Tensor]], params: Optional[List[ParamItem]] = None
- ) -> Union[torch.Tensor, Tuple[torch.Tensor, torch.Tensor]]:
- self._params = []
- named_modules = self.get_forward_sequence(params)
- params = [] if params is None else params
- for (name, module), param in zip_longest(named_modules, params):
- input = self.apply_to_input(input, name, module, param=param) # type: ignore
- return input
+ return input, label
+
+ def forward_parameters(self, batch_shape: torch.Size) -> List[ParamItem]:
+ named_modules = self.get_forward_sequence()
+
+ params = []
+ for name, module in named_modules:
+ if isinstance(module, (_AugmentationBase, MixAugmentationBase)):
+ mod_param = module.forward_parameters(batch_shape)
+ param = ParamItem(name, mod_param)
+ else:
+ param = ParamItem(name, None)
+ params.append(param)
+ return params
+
+ def contains_label_operations(self, params: List[ParamItem]) -> bool:
+ for param in params:
+ if param.name.startswith("RandomMixUp") or param.name.startswith("RandomCutMix"):
+ return True
+ return False
+
+ def __packup_output__(
+ self, output: TensorWithTransformMat, label: Optional[torch.Tensor] = None
+ ) -> Union[TensorWithTransformMat, Tuple[TensorWithTransformMat, torch.Tensor]]:
+ if self.return_label:
+ return output, label # type: ignore
+ # Implicitly indicating the label cannot be optional since there is a mix aug
+ return output
+
+ def forward( # type: ignore
+ self,
+ input: TensorWithTransformMat,
+ label: Optional[torch.Tensor] = None,
+ params: Optional[List[ParamItem]] = None,
+ ) -> Union[TensorWithTransformMat, Tuple[TensorWithTransformMat, torch.Tensor]]:
+ self.clear_state()
+ if params is None:
+ if isinstance(input, (tuple, list)):
+ params = self.forward_parameters(input[0].shape)
+ else:
+ params = self.forward_parameters(input.shape)
+ self.return_label = label is not None or self.contains_label_operations(params)
+ for param in params:
+ module = self.get_submodule(param.name)
+ input, label = self.apply_to_input(input, label, module, param=param) # type: ignore
+ if isinstance(module, (_AugmentationBase, MixAugmentationBase, SequentialBase)):
+ param = ParamItem(param.name, module._params)
+ else:
+ param = ParamItem(param.name, None)
+ self.update_params(param)
+ return self.__packup_output__(input, label)
diff --git a/kornia/augmentation/container/patch.py b/kornia/augmentation/container/patch.py
index 889981c4c..a72d977a3 100644
--- a/kornia/augmentation/container/patch.py
+++ b/kornia/augmentation/container/patch.py
@@ -1,11 +1,16 @@
-from itertools import zip_longest
-from typing import cast, List, Optional, Tuple, Union
+from itertools import cycle, islice
+from typing import Iterator, List, NamedTuple, Optional, Tuple, Union
import torch
import torch.nn as nn
-from kornia.augmentation.augmentation import ColorJitter
-from kornia.augmentation.base import _AugmentationBase, IntensityAugmentationBase2D
+from kornia.augmentation.base import (
+ _AugmentationBase,
+ IntensityAugmentationBase2D,
+ MixAugmentationBase,
+ TensorWithTransformMat,
+)
+from kornia.augmentation.container.base import SequentialBase
from kornia.contrib.extract_patches import extract_tensor_patches
from .image import ImageSequential, ParamItem
@@ -13,6 +18,11 @@ from .image import ImageSequential, ParamItem
__all__ = ["PatchSequential"]
+class PatchParamItem(NamedTuple):
+ indices: List[int]
+ param: ParamItem
+
+
class PatchSequential(ImageSequential):
r"""Container for performing patch-level image processing.
@@ -39,10 +49,13 @@ class PatchSequential(ImageSequential):
If ``(a,)`` (batchwise mode only), x number of transformations (a <= x <= len(args)) will be selected.
If ``(a, b)`` (batchwise mode only), x number of transformations (a <= x <= b) will be selected.
If ``True``, the whole list of args will be processed in a random order.
- If ``False``, the whole list of args will be processed in original order.
+ If ``False`` and not ``patchwise_apply``, the whole list of args will be processed in original order.
+ If ``False`` and ``patchwise_apply``, the whole list of args will be processed in original order
+ location-wisely.
- Return:
- the tensor (, and the transformation matrix) has been sequentially modified by the args.
+ Note:
+ Transformation matrix returned only considers the transformation applied in ``kornia.augmentation`` module.
+ Those transformations in ``kornia.geometry`` will not be taken into account.
Examples:
>>> import kornia.augmentation as K
@@ -61,14 +74,14 @@ class PatchSequential(ImageSequential):
... ),
... K.RandomSolarize(0.1, 0.1, p=0.1),
... grid_size=(2,2),
- ... patchwise_apply=False,
+ ... patchwise_apply=True,
... same_on_batch=True,
- ... random_apply=True,
+ ... random_apply=False,
... )
>>> out = seq(input)
>>> out.shape
torch.Size([2, 3, 224, 224])
- >>> out1 = seq(input, seq._params)
+ >>> out1 = seq(input, params=seq._params)
>>> torch.equal(out, out1)
True
"""
@@ -80,16 +93,19 @@ class PatchSequential(ImageSequential):
padding: str = "same",
same_on_batch: Optional[bool] = None,
keepdim: Optional[bool] = None,
- patchwise_apply: bool = False,
+ patchwise_apply: bool = True,
random_apply: Union[int, bool, Tuple[int, int]] = False,
) -> None:
_random_apply: Optional[Union[int, Tuple[int, int]]]
+
if patchwise_apply and random_apply is True:
- _random_apply = (grid_size[0] * grid_size[1], grid_size[0] * grid_size[1])
+ # will only apply [1, 4] augmentations per patch
+ _random_apply = (1, 4)
elif patchwise_apply and random_apply is False:
assert len(args) == grid_size[0] * grid_size[1], (
"The number of processing modules must be equal with grid size."
- f"Got {len(args)} and {grid_size[0] * grid_size[1]}."
+ f"Got {len(args)} and {grid_size[0] * grid_size[1]}. "
+ "Please set random_apply = True or patchwise_apply = False."
)
_random_apply = random_apply
elif patchwise_apply and isinstance(random_apply, (int, tuple)):
@@ -118,17 +134,11 @@ class PatchSequential(ImageSequential):
return False
return True
- def __repeat_param_across_patches__(self, param: torch.Tensor, patch_num: int) -> torch.Tensor:
- """Repeat parameters across patches.
-
- The input is shaped as (B, ...), while to output (B * patch_num, ...), which
- to guarentee that the same transformation would happen for each patch index.
-
- (B1, B2, ..., Bn) => (B1, ... Bn, B1, ..., Bn, ..., B1, ..., Bn)
- | pt_size | | pt_size | ..., | pt_size |
- """
- repeated = torch.cat([param] * patch_num, dim=0)
- return repeated
+ def contains_label_operations(self, params: List[PatchParamItem]) -> bool: # type: ignore
+ for param in params:
+ if param.param.name.startswith("RandomMixUp") or param.param.name.startswith("RandomCutMix"):
+ return True
+ return False
def compute_padding(
self, input: torch.Tensor, padding: str, grid_size: Optional[Tuple[int, int]] = None
@@ -155,7 +165,7 @@ class PatchSequential(ImageSequential):
Example:
>>> import kornia.augmentation as K
- >>> pas = PatchSequential(K.ColorJitter(0.1, 0.1, 0.1, 0.1, p=1.0))
+ >>> pas = PatchSequential(K.ColorJitter(0.1, 0.1, 0.1, 0.1, p=1.0), patchwise_apply=False)
>>> pas.extract_patches(torch.arange(16).view(1, 1, 4, 4), grid_size=(2, 2))
tensor([[[[[ 0, 1],
[ 4, 5]]],
@@ -201,7 +211,7 @@ class PatchSequential(ImageSequential):
Example:
>>> import kornia.augmentation as K
- >>> pas = PatchSequential(K.ColorJitter(0.1, 0.1, 0.1, 0.1, p=1.0))
+ >>> pas = PatchSequential(K.ColorJitter(0.1, 0.1, 0.1, 0.1, p=1.0), patchwise_apply=False)
>>> out = pas.extract_patches(torch.arange(16).view(1, 1, 4, 4), grid_size=(2, 2))
>>> pas.restore_from_patches(out, grid_size=(2, 2))
tensor([[[[ 0, 1, 2, 3],
@@ -219,93 +229,171 @@ class PatchSequential(ImageSequential):
restored_tensor = torch.nn.functional.pad(restored_tensor, [-i for i in pad])
return restored_tensor
- def forward_patchwise(
- self, input: torch.Tensor, params: Optional[List[List[ParamItem]]] = None
- ) -> torch.Tensor: # NOTE: return_transform is always False here.
- if params is None:
- params = [[]] * input.size(1)
- auglist = [self.get_forward_sequence() for _ in range(input.size(1))]
+ def forward_parameters(self, batch_shape: torch.Size) -> List[PatchParamItem]: # type: ignore
+ out_param: List[PatchParamItem] = []
+ if not self.patchwise_apply:
+ params = self.generate_parameters(torch.Size([1, batch_shape[0] * batch_shape[1], *batch_shape[2:]]))
+ indices = torch.arange(0, batch_shape[0] * batch_shape[1])
+ [out_param.append(PatchParamItem(indices.tolist(), p)) for p, _ in params] # type: ignore
+ # "append" of "list" does not return a value
+ elif not self.same_on_batch:
+ params = self.generate_parameters(torch.Size([batch_shape[0] * batch_shape[1], 1, *batch_shape[2:]]))
+ [out_param.append(PatchParamItem([i], p)) for p, i in params] # type: ignore
+ # "append" of "list" does not return a value
else:
- auglist = [self.get_forward_sequence(p) for p in params]
- assert input.size(0) == len(auglist) == len(params)
-
- out = []
- self._params = []
- # TODO: This will need an optimization later.
- for inp, proc, param in zip(input, auglist, params):
- o = []
- p = []
- for inp_pat, (proc_name, proc_pat), _param in zip_longest(inp, proc, param):
- if isinstance(proc_pat, (_AugmentationBase, ImageSequential)):
- o.append(proc_pat(inp_pat[None], _param.data if _param is not None else None))
- p.append(ParamItem(proc_name, proc_pat._params))
+ params = self.generate_parameters(torch.Size([batch_shape[1], batch_shape[0], *batch_shape[2:]]))
+ indices = torch.arange(0, batch_shape[0] * batch_shape[1], step=batch_shape[1])
+ [out_param.append(PatchParamItem((indices + i).tolist(), p)) for p, i in params] # type: ignore
+ # "append" of "list" does not return a value
+ return out_param
+
+ def generate_parameters(self, batch_shape: torch.Size) -> Iterator[Tuple[ParamItem, int]]:
+ """Get mulitple forward sequence but maximumly one mix augmentation in between.
+
+ Args:
+ batch_shape: 5-dim shape arranged as :math:``(N, B, C, H, W)``, in which N represents
+ the number of sequence.
+ """
+ if not self.same_on_batch and self.random_apply:
+ # diff_on_batch and random_apply => patch-wise augmentation
+ with_mix = False
+ for i in range(batch_shape[0]):
+ seq, mix_added = self.get_random_forward_sequence(with_mix=with_mix)
+ with_mix = mix_added
+ for s in seq:
+ if isinstance(s[1], (_AugmentationBase, MixAugmentationBase, SequentialBase)):
+ yield ParamItem(s[0], s[1].forward_parameters(batch_shape[1:])), i
+ else:
+ yield ParamItem(s[0], None), i
+ elif not self.random_apply:
+ # same_on_batch + not random_apply => location-wise augmentation
+ for i, nchild in enumerate(islice(cycle(self.named_children()), batch_shape[0])):
+ if isinstance(nchild[1], (_AugmentationBase, MixAugmentationBase, SequentialBase)):
+ yield ParamItem(nchild[0], nchild[1].forward_parameters(batch_shape[1:])), i
else:
- o.append(proc_pat(inp_pat[None]))
- p.append(ParamItem(proc_name, {}))
- out.append(torch.cat(o, dim=0))
- self._params.append(p)
-
- input = torch.stack(out, dim=0)
- return input
-
- def forward_batchwise(
- self, input: torch.Tensor, params: Optional[List[ParamItem]] = None
- ) -> torch.Tensor: # NOTE: return_transform is always False here.
- if self.same_on_batch:
- batch_shape = (input.size(1), *input.shape[-3:])
- patch_num = input.size(0)
+ yield ParamItem(nchild[0], None), i
+ else:
+ # same_on_batch + random_apply => location-wise augmentation
+ with_mix = False
+ for i in range(batch_shape[0]):
+ seq, mix_added = self.get_random_forward_sequence(with_mix=with_mix)
+ with_mix = mix_added
+ for s in seq:
+ if isinstance(s[1], (_AugmentationBase, MixAugmentationBase, SequentialBase)):
+ yield ParamItem(s[0], s[1].forward_parameters(batch_shape[1:])), i
+ else:
+ yield ParamItem(s[0], None), i
+
+ def apply_by_param(
+ self, input: TensorWithTransformMat, label: Optional[torch.Tensor], params: PatchParamItem
+ ) -> Tuple[TensorWithTransformMat, Optional[torch.Tensor], PatchParamItem]:
+ _input: TensorWithTransformMat
+ if isinstance(input, (tuple,)):
+ in_shape = input[0].shape
+ _input = (input[0][params.indices], input[1][params.indices])
else:
- batch_shape = (input.size(0) * input.size(1), *input.shape[-3:])
+ in_shape = input.shape
+ _input = input[params.indices]
- if params is None:
- params = []
- for name, aug in self.get_forward_sequence():
- if isinstance(aug, _AugmentationBase):
- aug.same_on_batch = False
- param = aug.forward_parameters(batch_shape)
- if self.same_on_batch:
- for k, v in param.items():
- # TODO: revise colorjitter order param in the future to align the standard.
- if not (k == "order" and isinstance(aug, ColorJitter)):
- param.update({k: self.__repeat_param_across_patches__(v, patch_num)})
- aug.same_on_batch = True
- else:
- param = None
- params.append(ParamItem(name, param))
+ _label: Optional[torch.Tensor]
+ if label is not None:
+ _label = label[params.indices]
+ else:
+ _label = label
- input = super().forward(input.view(-1, *input.shape[-3:]), params) # type: ignore
+ module = self.get_submodule(params.param.name)
+ output, out_label = self.apply_to_input(_input, _label, module, params.param)
- return input
+ if isinstance(module, (_AugmentationBase, MixAugmentationBase, SequentialBase)):
+ out_param = ParamItem(params.param.name, module._params)
+ else:
+ out_param = ParamItem(params.param.name, None)
+
+ if isinstance(output, (tuple,)) and isinstance(input, (tuple,)):
+ input[0][params.indices] = output[0]
+ input[1][params.indices] = output[1]
+ elif isinstance(output, (tuple,)) and not isinstance(input, (tuple,)):
+ input[params.indices] = output[0]
+ input = (input, output[1])
+ elif not isinstance(output, (tuple,)) and isinstance(input, (tuple,)):
+ input[0][params.indices] = output
+ elif not isinstance(output, (tuple,)) and not isinstance(input, (tuple,)):
+ input[params.indices] = output
+
+ # TODO: this label handling is naive that may not be able to handle complex cases.
+ _label = None
+ if label is not None and out_label is not None:
+ if len(out_label.shape) == 1:
+ # Wierd the mypy error though it is as same as in the next block
+ _label = (
+ torch.ones( # type: ignore
+ in_shape[0] * in_shape[1], device=out_label.device, out_label=label.dtype
+ )
+ * -1
+ )
+ _label = label
+ else:
+ _label = (
+ torch.ones(in_shape[0], *out_label.shape[1:], device=out_label.device, dtype=out_label.dtype) * -1
+ )
+ _label[:, 0] = label
+ label[params.indices] = out_label
+ elif label is None and out_label is not None:
+ if len(out_label.shape) == 1:
+ _label = torch.ones(in_shape[0] * in_shape[1], device=out_label.device, dtype=out_label.dtype) * -1
+ else:
+ _label = (
+ torch.ones(in_shape[0], *out_label.shape[1:], device=out_label.device, dtype=out_label.dtype) * -1
+ )
+ _label[params.indices] = out_label
+
+ return input, label, PatchParamItem(params.indices, param=out_param)
+
+ def forward_by_params(
+ self, input: torch.Tensor, label: Optional[torch.Tensor], params: List[PatchParamItem]
+ ) -> Union[TensorWithTransformMat, Tuple[TensorWithTransformMat, Optional[torch.Tensor]]]:
+ _input: TensorWithTransformMat
+ in_shape = input.shape
+ _input = input.reshape(-1, *in_shape[-3:])
+
+ if label is not None:
+ label = torch.cat([label] * in_shape[1], dim=0)
+
+ self.clear_state()
+ for patch_param in params:
+ _input, label, out_param = self.apply_by_param(_input, label, params=patch_param)
+ self.update_params(out_param)
+ if isinstance(_input, (tuple,)):
+ _input = (_input[0].reshape(in_shape), _input[1])
+ else:
+ _input = _input.reshape(in_shape)
+ return _input, label
def forward( # type: ignore
- self,
- input: Union[torch.Tensor, Tuple[torch.Tensor, torch.Tensor]],
- params: Optional[Union[List[ParamItem], List[List[ParamItem]]]] = None,
- ) -> Union[torch.Tensor, Tuple[torch.Tensor, torch.Tensor]]: # NOTE: return_transform is always False here.
+ self, input: torch.Tensor, label: Optional[torch.Tensor] = None, params: Optional[List[PatchParamItem]] = None
+ ) -> Union[TensorWithTransformMat, Tuple[TensorWithTransformMat, torch.Tensor]]:
"""Input transformation will be returned if input is a tuple."""
# BCHW -> B(patch)CHW
if isinstance(input, (tuple,)):
- pad = self.compute_padding(input[0], self.padding)
- input = self.extract_patches(input[0], self.grid_size, pad), input[1]
- else:
- pad = self.compute_padding(input, self.padding)
- input = self.extract_patches(input, self.grid_size, pad)
+ raise ValueError("tuple input is not currently supported.")
+ _input: TensorWithTransformMat
+
+ pad = self.compute_padding(input, self.padding)
+ input = self.extract_patches(input, self.grid_size, pad)
+ if label is not None:
+ assert label.dim() == 1
+ # repeat label as the same number as input patches.
+ label = torch.stack([label] * self.grid_size[0] * self.grid_size[1]).reshape(-1)
+ if params is None:
+ params = self.forward_parameters(input.shape)
- if not self.patchwise_apply:
- params = cast(List[ParamItem], params)
- if isinstance(input, (tuple,)):
- input = self.forward_batchwise(input[0], params), input[1]
- else:
- input = self.forward_batchwise(input, params)
- else:
- params = cast(List[List[ParamItem]], params)
- if isinstance(input, (tuple,)):
- input = self.forward_patchwise(input[0], params), input[1]
- else:
- input = self.forward_patchwise(input, params)
+ _input, label = self.forward_by_params(input, label, params)
- if isinstance(input, (tuple,)):
- input = (self.restore_from_patches(input[0], self.grid_size, pad=pad), input[1])
+ if isinstance(_input, (tuple,)):
+ _input = (self.restore_from_patches(_input[0], self.grid_size, pad=pad), _input[1])
else:
- input = self.restore_from_patches(input, self.grid_size, pad=pad)
- return input
+ _input = self.restore_from_patches(_input, self.grid_size, pad=pad)
+
+ self.return_label = label is not None or self.contains_label_operations(params)
+
+ return self.__packup_output__(_input, label)
diff --git a/kornia/augmentation/container/video.py b/kornia/augmentation/container/video.py
index 06f477d77..9ba76b9df 100644
--- a/kornia/augmentation/container/video.py
+++ b/kornia/augmentation/container/video.py
@@ -1,18 +1,17 @@
-from itertools import zip_longest
from typing import cast, List, Optional, Tuple, Union
import torch
import torch.nn as nn
import kornia
-from kornia.augmentation.base import _AugmentationBase
+from kornia.augmentation.base import _AugmentationBase, MixAugmentationBase, TensorWithTransformMat
+from kornia.augmentation.container.base import SequentialBase
from .image import ImageSequential, ParamItem
__all__ = ["VideoSequential"]
-# TODO: Rewrite this to support inverse operation by having a generic AugmentationSequential.
class VideoSequential(ImageSequential):
r"""VideoSequential for processing 5-dim video data like (B, T, C, H, W) and (B, C, T, H, W).
@@ -32,11 +31,15 @@ class VideoSequential(ImageSequential):
If (a, b), x number of transformations (a <= x <= b) will be selected.
If None, the whole list of args will be processed as a sequence.
+ Note:
+ Transformation matrix returned only considers the transformation applied in ``kornia.augmentation`` module.
+ Those transformations in ``kornia.geometry`` will not be taken into account.
+
Example:
If set `same_on_frame` to True, we would expect the same augmentation has been applied to each
timeframe.
- >>> input = torch.randn(2, 3, 1, 5, 6).repeat(1, 1, 4, 1, 1)
+ >>> input, label = torch.randn(2, 3, 1, 5, 6).repeat(1, 1, 4, 1, 1), torch.tensor([0, 1])
>>> aug_list = VideoSequential(
... kornia.augmentation.ColorJitter(0.1, 0.1, 0.1, 0.1, p=1.0),
... kornia.color.BgrToRgb(),
@@ -57,16 +60,17 @@ class VideoSequential(ImageSequential):
>>> aug_list = VideoSequential(
... kornia.augmentation.ColorJitter(0.1, 0.1, 0.1, 0.1, p=1.0),
... kornia.augmentation.RandomAffine(360, p=1.0),
+ ... kornia.augmentation.RandomMixUp(p=1.0),
... data_format="BCTHW",
... same_on_frame=False)
- >>> output = aug_list(input)
- >>> output.shape
- torch.Size([2, 3, 4, 5, 6])
+ >>> output, lab = aug_list(input)
+ >>> output.shape, lab.shape
+ (torch.Size([2, 3, 4, 5, 6]), torch.Size([2, 4, 3]))
>>> (output[0, :, 0] == output[0, :, 1]).all()
tensor(False)
Reproduce with provided params.
- >>> out2 = aug_list(input, params=aug_list._params)
+ >>> out2, lab2 = aug_list(input, label, params=aug_list._params)
>>> torch.equal(output, out2)
True
"""
@@ -90,8 +94,7 @@ class VideoSequential(ImageSequential):
elif self.data_format == "BTCHW":
self._temporal_channel = 1
- def __infer_channel_exclusive_batch_shape__(self, input: torch.Tensor, chennel_index: int) -> torch.Size:
- batch_shape: torch.Size = input.shape
+ def __infer_channel_exclusive_batch_shape__(self, batch_shape: torch.Size, chennel_index: int) -> torch.Size:
# Fix mypy complains: error: Incompatible return value type (got "Tuple[int, ...]", expected "Size")
return cast(torch.Size, batch_shape[:chennel_index] + batch_shape[chennel_index + 1 :])
@@ -107,45 +110,61 @@ class VideoSequential(ImageSequential):
repeated = param[:, None, ...].repeat(1, frame_num, *([1] * len(param.shape[1:])))
return repeated.reshape(-1, *list(param.shape[1:])) # type: ignore
- def _input_shape_convert_in(self, input: torch.Tensor) -> torch.Tensor:
+ def _input_shape_convert_in(
+ self, input: torch.Tensor, label: Optional[torch.Tensor], frame_num: int
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor]]:
# Convert any shape to (B, T, C, H, W)
if self.data_format == "BCTHW":
# Convert (B, C, T, H, W) to (B, T, C, H, W)
input = input.transpose(1, 2)
if self.data_format == "BTCHW":
pass
- return input
- def _input_shape_convert_back(self, input: torch.Tensor, frame_num: int) -> torch.Tensor:
+ if label is not None:
+ if label.shape == input.shape[:2]:
+ # if label is provided as (B, T)
+ label = label.view(-1)
+ elif label.shape == input.shape[:1]:
+ label = label[..., None].repeat(1, frame_num).view(-1)
+ elif label.shape == torch.Size([input.shape[0] * input.shape[1]]):
+ # Skip the conversion if label is provided as (B * T,)
+ pass
+ else:
+ raise NotImplementedError(f"Invalid label shape of {label.shape}.")
+ input = input.reshape(-1, *input.shape[2:])
+ return input, label
+
+ def _input_shape_convert_back(
+ self, input: torch.Tensor, label: Optional[torch.Tensor], frame_num: int
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor]]:
input = input.view(-1, frame_num, *input.shape[1:])
if self.data_format == "BCTHW":
input = input.transpose(1, 2)
if self.data_format == "BTCHW":
pass
- return input
-
- def forward( # type: ignore
- self, input: torch.Tensor, params: Optional[List[ParamItem]] = None
- ) -> Union[torch.Tensor, Tuple[torch.Tensor, torch.Tensor]]:
- """Define the video computation performed."""
- assert len(input.shape) == 5, f"Input must be a 5-dim tensor. Got {input.shape}."
- self._params = []
- named_modules = self.get_forward_sequence(params)
- params = [] if params is None else params
+ if label is not None:
+ label = label.view(input.size(0), frame_num, -1)
+ return input, label
- # Size of T
- frame_num = input.size(self._temporal_channel)
+ def forward_parameters(self, batch_shape: torch.Size) -> List[ParamItem]:
+ frame_num = batch_shape[self._temporal_channel]
+ named_modules = self.get_forward_sequence()
# Got param generation shape to (B, C, H, W). Ignoring T.
- batch_shape = self.__infer_channel_exclusive_batch_shape__(input, self._temporal_channel)
- input = self._input_shape_convert_in(input)
- input = input.reshape(-1, *batch_shape[1:])
+ batch_shape = self.__infer_channel_exclusive_batch_shape__(batch_shape, self._temporal_channel)
+
if not self.same_on_frame:
# Overwrite param generation shape to (B * T, C, H, W).
- batch_shape = input.shape
+ batch_shape = torch.Size([batch_shape[0] * frame_num, *batch_shape[1:]])
- for (name, module), param in zip_longest(named_modules, params):
- if param is None and isinstance(module, _AugmentationBase):
+ params = []
+ for name, module in named_modules:
+ if isinstance(module, (SequentialBase,)):
+ seq_param = module.forward_parameters(batch_shape)
+ if self.same_on_frame:
+ raise ValueError("Sequential is currently unsupported for ``same_on_frame``.")
+ param = ParamItem(name, seq_param)
+ elif isinstance(module, (_AugmentationBase, MixAugmentationBase)):
mod_param = module.forward_parameters(batch_shape)
if self.same_on_frame:
for k, v in mod_param.items():
@@ -153,12 +172,34 @@ class VideoSequential(ImageSequential):
if not (k == "order" and isinstance(module, kornia.augmentation.ColorJitter)):
mod_param.update({k: self.__repeat_param_across_channels__(v, frame_num)})
param = ParamItem(name, mod_param)
+ else:
+ param = ParamItem(name, None)
+ params.append(param)
+ return params
- input = self.apply_to_input(input, name, module, param=param) # type: ignore
+ def forward( # type: ignore
+ self, input: torch.Tensor, label: Optional[torch.Tensor] = None, params: Optional[List[ParamItem]] = None
+ ) -> Union[TensorWithTransformMat, Tuple[TensorWithTransformMat, torch.Tensor]]:
+ """Define the video computation performed."""
+ assert len(input.shape) == 5, f"Input must be a 5-dim tensor. Got {input.shape}."
+
+ if params is None:
+ params = self.forward_parameters(input.shape)
+
+ # Size of T
+ frame_num = input.size(self._temporal_channel)
+ input, label = self._input_shape_convert_in(input, label, frame_num)
+
+ out = super().forward(input, label, params) # type: ignore
+ if self.return_label:
+ output, label = cast(Tuple[TensorWithTransformMat, torch.Tensor], out)
+ else:
+ output = cast(TensorWithTransformMat, out)
- if isinstance(input, (tuple, list)):
- input[0] = self._input_shape_convert_back(input[0], frame_num)
+ if isinstance(output, (tuple, list)):
+ _out, label = self._input_shape_convert_back(output[0], label, frame_num)
+ output = (_out, output[1])
else:
- input = self._input_shape_convert_back(input, frame_num)
+ output, label = self._input_shape_convert_back(output, label, frame_num)
- return input
+ return self.__packup_output__(output, label)
diff --git a/kornia/augmentation/mix_augmentation.py b/kornia/augmentation/mix_augmentation.py
index aed741467..42200f704 100644
--- a/kornia/augmentation/mix_augmentation.py
+++ b/kornia/augmentation/mix_augmentation.py
@@ -104,7 +104,7 @@ class RandomMixUp(MixAugmentationBase):
return rg.random_mixup_generator(batch_shape[0], self.p, lambda_val, same_on_batch=self.same_on_batch)
def apply_transform( # type: ignore
- self, input: torch.Tensor, label: torch.Tensor, params: Dict[str, torch.Tensor] # type: ignore
+ self, input: torch.Tensor, label: torch.Tensor, params: Dict[str, torch.Tensor]
) -> Tuple[torch.Tensor, torch.Tensor]:
input_permute = input.index_select(dim=0, index=params['mixup_pairs'].to(input.device))
labels_permute = label.index_select(dim=0, index=params['mixup_pairs'].to(label.device))
diff --git a/test/augmentation/test_container.py b/test/augmentation/test_container.py
index 6920291ce..42c946818 100644
--- a/test/augmentation/test_container.py
+++ b/test/augmentation/test_container.py
@@ -3,6 +3,7 @@ import torch
import kornia
import kornia.augmentation as K
+from kornia.augmentation.base import MixAugmentationBase
from kornia.constants import BorderType
from kornia.geometry.bbox import bbox_to_mask
from kornia.testing import assert_close
@@ -80,6 +81,7 @@ class TestVideoSequential:
[K.ColorJitter(0.1, 0.1, 0.1, 0.1, p=0.0), K.RandomAffine(360, p=0.0)],
[K.ColorJitter(0.1, 0.1, 0.1, 0.1, p=0.0)],
[K.RandomAffine(360, p=0.0)],
+ [K.ColorJitter(0.1, 0.1, 0.1, 0.1, p=1.0), K.RandomAffine(360, p=1.0), K.RandomMixUp(p=1.0)],
],
)
@pytest.mark.parametrize('data_format', ["BCTHW", "BTCHW"])
@@ -92,19 +94,28 @@ class TestVideoSequential:
if data_format == 'BCTHW':
input = torch.randn(2, 3, 1, 5, 6, device=device, dtype=dtype).repeat(1, 1, 4, 1, 1)
output = aug_list(input)
+ if aug_list.return_label:
+ output, label = output
assert (output[:, :, 0] == output[:, :, 1]).all()
assert (output[:, :, 1] == output[:, :, 2]).all()
assert (output[:, :, 2] == output[:, :, 3]).all()
if data_format == 'BTCHW':
input = torch.randn(2, 1, 3, 5, 6, device=device, dtype=dtype).repeat(1, 4, 1, 1, 1)
output = aug_list(input)
+ if aug_list.return_label:
+ output, label = output
assert (output[:, 0] == output[:, 1]).all()
assert (output[:, 1] == output[:, 2]).all()
assert (output[:, 2] == output[:, 3]).all()
reproducibility_test(input, aug_list)
@pytest.mark.parametrize(
- 'augmentations', [[K.RandomAffine(360, p=1.0)], [K.ColorJitter(0.1, 0.1, 0.1, 0.1, p=1.0)]]
+ 'augmentations',
+ [
+ [K.RandomAffine(360, p=1.0)],
+ [K.ColorJitter(0.1, 0.1, 0.1, 0.1, p=1.0)],
+ [K.RandomAffine(360, p=0.0), K.ImageSequential(K.RandomAffine(360, p=0.0))],
+ ],
)
@pytest.mark.parametrize('data_format', ["BCTHW", "BTCHW"])
def test_against_sequential(self, augmentations, data_format, device, dtype):
@@ -142,16 +153,30 @@ class TestSequential:
@pytest.mark.parametrize('same_on_batch', [True, False, None])
@pytest.mark.parametrize("return_transform", [True, False, None])
@pytest.mark.parametrize("keepdim", [True, False, None])
- @pytest.mark.parametrize('random_apply', [1, (2, 2), (1, 2), (2,), 10, True, False])
+ @pytest.mark.parametrize('random_apply', [1, (2, 2), (1, 2), (2,), 20, True, False])
def test_construction(self, same_on_batch, return_transform, keepdim, random_apply):
- K.ImageSequential(
+ aug = K.ImageSequential(
K.ColorJitter(0.1, 0.1, 0.1, 0.1, p=1.0),
K.RandomAffine(360, p=1.0),
+ K.RandomMixUp(p=1.0),
same_on_batch=same_on_batch,
return_transform=return_transform,
keepdim=keepdim,
random_apply=random_apply,
)
+ c = 0
+ for a in aug.get_forward_sequence():
+ if isinstance(a, (MixAugmentationBase,)):
+ c += 1
+ assert c < 2
+ aug.same_on_batch = True
+ aug.return_transform = True
+ aug.keepdim = True
+ for m in aug.children():
+ assert m.same_on_batch is True, m.same_on_batch
+ if not isinstance(m, (MixAugmentationBase,)):
+ assert m.return_transform is True, m.return_transform
+ assert m.keepdim is True, m.keepdim
@pytest.mark.parametrize("return_transform", [True, False, None])
@pytest.mark.parametrize('random_apply', [1, (2, 2), (1, 2), (2,), 10, True, False])
@@ -162,10 +187,13 @@ class TestSequential:
kornia.filters.MedianBlur((3, 3)),
K.ColorJitter(0.1, 0.1, 0.1, 0.1, p=1.0, return_transform=True),
K.RandomAffine(360, p=1.0),
+ K.RandomMixUp(p=1.0),
return_transform=return_transform,
random_apply=random_apply,
)
out = aug(inp)
+ if aug.return_label:
+ out, label = out
if isinstance(out, (tuple,)):
assert out[0].shape == inp.shape
else:
@@ -182,8 +210,29 @@ class TestAugmentationSequential:
with pytest.raises(Exception): # AssertError and NotImplementedError
K.AugmentationSequential(augmentation_list, data_keys=data_keys)
+ @pytest.mark.parametrize('return_transform', [True, False])
+ @pytest.mark.parametrize('random_apply', [1, (2, 2), (1, 2), (2,), 10, True, False])
+ def test_mixup(self, return_transform, random_apply, device, dtype):
+ inp = torch.randn(1, 3, 1000, 500, device=device, dtype=dtype)
+ aug = K.AugmentationSequential(
+ K.ColorJitter(0.1, 0.1, 0.1, 0.1, p=1.0),
+ K.RandomAffine(360, p=1.0),
+ K.RandomMixUp(p=1.0),
+ data_keys=["input"],
+ random_apply=random_apply,
+ return_transform=return_transform,
+ )
+ out = aug(inp)
+ if aug.return_label:
+ out, label = out
+ if return_transform and isinstance(out, (tuple, list)):
+ out = out[0]
+ assert out.shape == inp.shape
+ reproducibility_test(inp, aug)
+
@pytest.mark.parametrize('random_apply', [1, (2, 2), (1, 2), (2,), 10, True, False])
- def test_forward_and_inverse(self, random_apply, device, dtype):
+ @pytest.mark.parametrize('return_transform', [True, False])
+ def test_forward_and_inverse(self, random_apply, return_transform, device, dtype):
inp = torch.randn(1, 3, 1000, 500, device=device, dtype=dtype)
bbox = torch.tensor([[[355, 10], [660, 10], [660, 250], [355, 250]]], device=device, dtype=dtype)
keypoints = torch.tensor([[[465, 115], [545, 116]]], device=device, dtype=dtype)
@@ -195,9 +244,13 @@ class TestAugmentationSequential:
K.RandomAffine(360, p=1.0),
data_keys=["input", "mask", "bbox", "keypoints"],
random_apply=random_apply,
+ return_transform=return_transform,
)
out = aug(inp, mask, bbox, keypoints)
- assert out[0].shape == inp.shape
+ if return_transform and isinstance(out, (tuple, list)):
+ assert out[0][0].shape == inp.shape
+ else:
+ assert out[0].shape == inp.shape
assert out[1].shape == mask.shape
assert out[2].shape == bbox.shape
assert out[3].shape == keypoints.shape
@@ -226,15 +279,11 @@ class TestAugmentationSequential:
assert aug(inp, data_keys=['input'])[0].shape == inp.shape
aug = K.AugmentationSequential(K.RandomAffine(360, p=1.0, return_transform=False))
assert aug(inp, data_keys=['input']).shape == inp.shape
- assert aug(mask, data_keys=['mask']).shape == mask.shape
+ assert aug(mask, data_keys=['mask'], params=aug._params).shape == mask.shape
- aug = K.AugmentationSequential(K.RandomAffine(360, p=1.0, return_transform=True))
assert aug.inverse(inp, data_keys=['input']).shape == inp.shape
- aug = K.AugmentationSequential(K.RandomAffine(360, p=1.0, return_transform=True))
assert aug.inverse(bbox, data_keys=['bbox']).shape == bbox.shape
- aug = K.AugmentationSequential(K.RandomAffine(360, p=1.0, return_transform=True))
assert aug.inverse(keypoints, data_keys=['keypoints']).shape == keypoints.shape
- aug = K.AugmentationSequential(K.RandomAffine(360, p=1.0, return_transform=True))
assert aug.inverse(mask, data_keys=['mask']).shape == mask.shape
@pytest.mark.parametrize('random_apply', [2, (1, 1), (2,), 10, True, False])
@@ -279,12 +328,8 @@ class TestAugmentationSequential:
data_keys=["input", "mask", "bbox", "keypoints"],
random_apply=random_apply,
)
-
- out_inv = aug.inverse(inp, mask, bbox, keypoints)
- assert out_inv[0].shape == inp.shape
- assert out_inv[1].shape == mask.shape
- assert out_inv[2].shape == bbox.shape
- assert out_inv[3].shape == keypoints.shape
+ with pytest.raises(Exception): # No parameters avaliable for inversing.
+ aug.inverse(inp, mask, bbox, keypoints)
out = aug(inp, mask, bbox, keypoints)
assert out[0][0].shape == inp.shape
@@ -340,20 +385,17 @@ class TestPatchSequential:
@pytest.mark.parametrize('keepdim', [True, False, None])
@pytest.mark.parametrize('random_apply', [1, (2, 2), (1, 2), (2,), 10, True, False])
def test_forward(self, shape, padding, patchwise_apply, same_on_batch, keepdim, random_apply, device, dtype):
+ torch.manual_seed(11)
try: # skip wrong param settings.
seq = K.PatchSequential(
- K.ImageSequential(
- K.ColorJitter(0.1, 0.1, 0.1, 0.1, p=0.5),
- K.RandomPerspective(0.2, p=0.5),
- K.RandomSolarize(0.1, 0.1, p=0.5),
- ),
+ kornia.color.RgbToBgr(),
K.ColorJitter(0.1, 0.1, 0.1, 0.1),
K.ImageSequential(
K.ColorJitter(0.1, 0.1, 0.1, 0.1, p=0.5),
K.RandomPerspective(0.2, p=0.5),
K.RandomSolarize(0.1, 0.1, p=0.5),
),
- K.ColorJitter(0.1, 0.1, 0.1, 0.1),
+ K.RandomMixUp(p=1.0),
grid_size=(2, 2),
padding=padding,
patchwise_apply=patchwise_apply,
@@ -365,14 +407,11 @@ class TestPatchSequential:
return
input = torch.randn(*shape, device=device, dtype=dtype)
- trans = torch.randn(shape[0], 3, 3, device=device, dtype=dtype)
out = seq(input)
+ if seq.return_label:
+ out, label = out
assert out.shape[-3:] == input.shape[-3:]
- out = seq((input, trans))
- assert out[0].shape[-3:] == input.shape[-3:]
- assert out[1].shape == trans.shape
-
reproducibility_test(input, seq)
def test_intensity_only(self):