Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

[feat] Added random_apply to augmentaton containers (#1125)

Jian Shia42750f735bc
diff --git a/kornia/augmentation/container/augment.py b/kornia/augmentation/container/augment.py
index 3a0527b80..307489988 100644
--- a/kornia/augmentation/container/augment.py
+++ b/kornia/augmentation/container/augment.py
@@ -1,4 +1,5 @@
import warnings
+from itertools import zip_longest
from typing import cast, Dict, List, Optional, Tuple, Union
import torch
@@ -8,9 +9,11 @@ from kornia.augmentation.base import _AugmentationBase, GeometricAugmentationBas
from kornia.constants import DataKey
from kornia.geometry import transform_boxes, transform_points
-from .image import ImageSequential
+from .image import ImageSequential, ParamItem
from .patch import PatchSequential
+__all__ = ["AugmentationSequential"]
+
class AugmentationSequential(ImageSequential):
r"""AugmentationSequential for handling multiple input types like inputs, masks, keypoints at once.
@@ -20,15 +23,22 @@ class AugmentationSequential(ImageSequential):
.. image:: https://kornia-tutorials.readthedocs.io/en/latest/_images/data_augmentation_sequential_7_2.png
Args:
- *args (_AugmentationBase): a list of kornia augmentation modules.
- data_keys (List[str]): the input type sequential for applying augmentations.
+ *args: a list of kornia augmentation modules.
+ data_keys: the input type sequential for applying augmentations.
Accepts "input", "mask", "bbox", "bbox_xyxy", "bbox_xywh", "keypoints".
- same_on_batch (bool, optional): apply the same transformation across the batch.
- If None, it will not overwrite the function-wise settings. Default: None.
- return_transform (bool, optional): if ``True`` return the matrix describing the transformation
- applied to each. If None, it will not overwrite the function-wise settings. Default: None.
- keepdim (bool, optional): 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. Default: None.
+ 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.
+ random_apply: randomly select a sublist (order agnostic) of args to
+ apply transformation.
+ If int, a fixed number of transformations will be selected.
+ If (a,), x number of transformations (a <= x <= len(args)) will be selected.
+ If (a, b), x number of transformations (a <= x <= b) will be selected.
+ 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:
List[Union[torch.Tensor, Tuple[torch.Tensor, torch.Tensor]]]: the tensor (, and the transformation matrix)
@@ -50,6 +60,7 @@ class AugmentationSequential(ImageSequential):
... data_keys=["input", "mask", "bbox", "keypoints"],
... return_transform=False,
... same_on_batch=False,
+ ... random_apply=10,
... )
>>> out = aug_list(input, input, bbox, points)
>>> [o.shape for o in out]
@@ -66,9 +77,14 @@ class AugmentationSequential(ImageSequential):
same_on_batch: Optional[bool] = None,
return_transform: Optional[bool] = None,
keepdim: Optional[bool] = None,
+ random_apply: Union[int, bool, Tuple[int, int]] = False,
) -> None:
super(AugmentationSequential, self).__init__(
- *args, same_on_batch=same_on_batch, return_transform=return_transform, keepdim=keepdim
+ *args,
+ same_on_batch=same_on_batch,
+ return_transform=return_transform,
+ keepdim=keepdim,
+ random_apply=random_apply,
)
self.data_keys = [DataKey.get(inp) for inp in data_keys]
@@ -84,39 +100,48 @@ class AugmentationSequential(ImageSequential):
if isinstance(arg, PatchSequential) and not arg.is_intensity_only():
warnings.warn("Geometric transformation detected in PatchSeqeuntial, which would break bbox, mask.")
- def apply_to_mask(
- self, input: torch.Tensor, module: nn.Module, param: Optional[Dict[str, torch.Tensor]] = None
- ) -> torch.Tensor:
- if isinstance(module, GeometricAugmentationBase2D) and param is None:
+ def apply_to_mask(self, input: torch.Tensor, module: nn.Module, param: Optional[ParamItem] = None) -> torch.Tensor:
+ if param is not None:
+ _param = cast(Dict[str, torch.Tensor], param.data)
+ else:
+ _param = None # type: ignore
+
+ if isinstance(module, GeometricAugmentationBase2D) and _param is None:
input = module(input, return_transform=False)
- elif isinstance(module, GeometricAugmentationBase2D) and param is not None:
- input = module(input, param, return_transform=False)
+ elif isinstance(module, GeometricAugmentationBase2D) and _param is not None:
+ input = module(input, _param, return_transform=False)
else:
pass # No need to update anything
return input
def apply_to_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) and param is None:
+ if param is not None:
+ _param = cast(Dict[str, torch.Tensor], param.data)
+ else:
+ _param = None # type: ignore
+
+ if isinstance(module, GeometricAugmentationBase2D) and _param is None:
raise ValueError(f"Transformation matrix for {module} has not been computed.")
- if isinstance(module, GeometricAugmentationBase2D) and param is not None:
- input = transform_boxes(module.get_transformation_matrix(input, param), input, mode)
+ if isinstance(module, GeometricAugmentationBase2D) and _param is not None:
+ input = transform_boxes(module.get_transformation_matrix(input, _param), input, mode)
else:
pass # No need to update anything
return input
def apply_to_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) and param is None:
+ if param is not None:
+ _param = cast(Dict[str, torch.Tensor], param.data)
+ else:
+ _param = None # type: ignore
+
+ if isinstance(module, GeometricAugmentationBase2D) and _param is None:
raise ValueError(f"Transformation matrix for {module} has not been computed.")
- if isinstance(module, GeometricAugmentationBase2D) and param is not None:
- input = transform_points(module.get_transformation_matrix(input, param), input)
+ if isinstance(module, GeometricAugmentationBase2D) and _param is not None:
+ input = transform_points(module.get_transformation_matrix(input, _param), input)
else:
pass # No need to update anything
return input
@@ -124,12 +149,17 @@ class AugmentationSequential(ImageSequential):
def apply_by_key(
self,
input: Union[torch.Tensor, Tuple[torch.Tensor, torch.Tensor]],
- module: nn.Module,
- param: Optional[Dict[str, torch.Tensor]] = None,
+ module_name: str,
+ module: Optional[nn.Module] = None,
+ param: Optional[ParamItem] = None,
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
+ if module is None:
+ module = self.get_submodule(module_name)
if DataKey.get(dcate) in [DataKey.INPUT]:
- return self.apply_to_input(input, module, param)
+ return self.apply_to_input(input, module_name, module, param)
if DataKey.get(dcate) in [DataKey.MASK]:
if isinstance(input, (tuple,)):
return (self.apply_to_mask(input[0], module, param), *input[1:])
@@ -199,7 +229,7 @@ class AugmentationSequential(ImageSequential):
def inverse(
self,
*args: torch.Tensor,
- params: Optional[Dict[str, Dict[str, torch.Tensor]]] = None,
+ params: Optional[List[ParamItem]] = None,
data_keys: Optional[List[Union[str, int, DataKey]]] = None,
) -> Union[torch.Tensor, List[torch.Tensor]]:
"""Reverse the transformation applied.
@@ -212,18 +242,21 @@ 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)}."
)
- self._params = {}
- params = params if params is not None else {}
+ if params is None and self._params is None:
+ raise ValueError("No parameters avaliable for inversing.")
+ else:
+ params = self._params
outputs = []
for input, dcate in zip(args, data_keys):
- for module in list(self.children())[::-1]:
+ if dcate == DataKey.INPUT and isinstance(input, (tuple, list)):
+ 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):
- func_name = module.__class__.__name__
# Check if a param recorded
- param = self._params[func_name] if func_name in self._params else None
+ 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[func_name] if func_name in params else param
+ param = params[name] if name in params else param
else:
param = None
if isinstance(module, GeometricAugmentationBase2D) and dcate in DataKey:
@@ -245,38 +278,30 @@ class AugmentationSequential(ImageSequential):
def forward( # type: ignore
self,
*args: Union[torch.Tensor, Tuple[torch.Tensor, torch.Tensor]],
- params: Optional[Dict[str, Dict[str, 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]]]
]:
"""Compute multiple tensors simultaneously according to ``self.data_keys``."""
if data_keys is None:
- self._params = {}
data_keys = cast(List[Union[str, int, DataKey]], self.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)}."
- params = params if params is not None else {}
outputs = []
+ self._params = []
+ named_modules = list(self.get_forward_sequence(params))
for input, dcate in zip(args, data_keys):
- for module in self.children():
- if isinstance(module, (ImageSequential,)):
- # Avoid same naming for sequential
- func_name = f"{module.__class__.__name__}-{hex(id(module))}"
- else:
- func_name = module.__class__.__name__
- # Check if a param recorded
- param = self._params[func_name] if func_name in self._params else None
- # Check if a param provided. If provided, it will overwrite the recorded ones.
- param = params[func_name] if func_name in params else param
-
+ # 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 dcate == DataKey.INPUT:
- input = self.apply_to_input(input, module, param)
+ input = self.apply_to_input(input, name, module, param)
elif isinstance(module, GeometricAugmentationBase2D) and dcate in DataKey:
- input = self.apply_by_key(input, module, param, dcate)
+ input = self.apply_by_key(input, name, 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:
diff --git a/kornia/augmentation/container/image.py b/kornia/augmentation/container/image.py
index a064ce06a..43ba35a29 100644
--- a/kornia/augmentation/container/image.py
+++ b/kornia/augmentation/container/image.py
@@ -1,22 +1,38 @@
-from typing import Dict, Optional, Tuple, Union
+from collections import OrderedDict
+from itertools import zip_longest
+from typing import Any, Iterator, List, NamedTuple, Optional, Tuple, Union
import torch
import torch.nn as nn
from kornia.augmentation.base import _AugmentationBase
+__all__ = ["ImageSequential"]
+
+
+class ParamItem(NamedTuple):
+ name: str
+ data: Union[dict, list]
+
class ImageSequential(nn.Sequential):
r"""Sequential for creating kornia image processing pipeline.
Args:
- *args (nn.Module): a list of kornia augmentation and image operation modules.
- same_on_batch (bool, optional): apply the same transformation across the batch.
- If None, it will not overwrite the function-wise settings. Default: None.
- return_transform (bool, optional): if ``True`` return the matrix describing the transformation
- applied to each. If None, it will not overwrite the function-wise settings. Default: None.
- keepdim (bool, optional): 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. Default: None.
+ *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.
+ random_apply: randomly select a sublist (order agnostic) of args to
+ apply transformation.
+ If int, a fixed number of transformations will be selected.
+ If (a,), x number of transformations (a <= x <= len(args)) will be selected.
+ If (a, b), x number of transformations (a <= x <= b) will be selected.
+ 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:
Union[torch.Tensor, Tuple[torch.Tensor, torch.Tensor]]: the tensor (, and the transformation matrix)
@@ -33,6 +49,7 @@ class ImageSequential(nn.Sequential):
... kornia.enhance.Invert(),
... return_transform=True,
... same_on_batch=True,
+ ... random_apply=10,
... )
>>> out = aug_list(input)
>>> out[0].shape, out[1].shape
@@ -54,12 +71,14 @@ class ImageSequential(nn.Sequential):
same_on_batch: Optional[bool] = None,
return_transform: Optional[bool] = None,
keepdim: Optional[bool] = None,
+ random_apply: Union[int, bool, Tuple[int, int]] = False,
) -> None:
- super(ImageSequential, self).__init__(*args)
self.same_on_batch = same_on_batch
self.return_transform = return_transform
self.keepdim = keepdim
- for arg in args:
+ # 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):
@@ -69,39 +88,102 @@ class ImageSequential(nn.Sequential):
arg.return_transform = return_transform
if keepdim is not None:
arg.keepdim = keepdim
- self._params: Dict[str, Dict[str, torch.Tensor]] = {}
+ _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 (
+ 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)]
+
+ 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
def apply_to_input(
self,
input: Union[torch.Tensor, Tuple[torch.Tensor, torch.Tensor]],
- module: nn.Module,
- param: Optional[Dict[str, torch.Tensor]] = None,
+ module_name: str,
+ module: Optional[nn.Module] = None,
+ param: Optional[ParamItem] = None,
) -> Union[torch.Tensor, Tuple[torch.Tensor, torch.Tensor]]:
- func_name = module.__class__.__name__
- if isinstance(module, _AugmentationBase) and param is None:
+ if module is None:
+ module = self.get_submodule(module_name)
+ 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.update({func_name: module._params})
- elif isinstance(module, _AugmentationBase) and param is not None:
- input = module(input, param)
- self._params.update({func_name: param})
+ 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))
else:
+ assert (
+ _param == {} or _param is None
+ ), f"Non-augmentaion operation {module_name} require empty parameters. Got {module}."
# 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[Dict[str, Dict[str, torch.Tensor]]] = None,
+ self, input: Union[torch.Tensor, Tuple[torch.Tensor, torch.Tensor]], params: Optional[List[ParamItem]] = None
) -> Union[torch.Tensor, Tuple[torch.Tensor, torch.Tensor]]:
- if params is None:
- params = {}
- self._params = {}
- for module in self.children():
- func_name = module.__class__.__name__
- param = params[func_name] if func_name in params else None
- input = self.apply_to_input(input, module, param) # type: ignore
+ 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
diff --git a/kornia/augmentation/container/patch.py b/kornia/augmentation/container/patch.py
index 67ba5f6a1..eeceabb24 100644
--- a/kornia/augmentation/container/patch.py
+++ b/kornia/augmentation/container/patch.py
@@ -1,4 +1,5 @@
-from typing import Dict, List, Optional, Tuple, Union
+from itertools import zip_longest
+from typing import cast, List, Optional, Tuple, Union
import torch
import torch.nn as nn
@@ -7,7 +8,9 @@ from kornia.augmentation.augmentation import ColorJitter
from kornia.augmentation.base import _AugmentationBase, IntensityAugmentationBase2D
from kornia.contrib.extract_patches import extract_tensor_patches
-from .image import ImageSequential
+from .image import ImageSequential, ParamItem
+
+__all__ = ["PatchSequential"]
class PatchSequential(ImageSequential):
@@ -19,14 +22,24 @@ class PatchSequential(ImageSequential):
afterwards. Different image processing and augmentation methods will be performed on each patch region.
Args:
- *args (nn.Module): a list of processing modules.
- same_on_batch (bool, optional): apply the same transformation across the batch.
- If None, it will not overwrite the function-wise settings. Default: None.
- keepdim (bool, optional): 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. Default: None.
- patchwise_apply (bool, optional): apply image processing args will be applied patch-wisely.
+ *args: a list of processing modules.
+ grid_size: controls the grid board seperation.
+ padding: same or valid padding. If same padding, it will pad to include all pixels if the input
+ tensor cannot be divisible by grid_size. If valid padding, the redundent border will be removed.
+ same_on_batch: apply the same transformation across the batch.
+ 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.
+ patchwise_apply: apply image processing args will be applied patch-wisely.
if ``True``, the number of args must be equal to grid number.
- if ``False``, the image processing args will be applied as a whole to all patches. Default: False.
+ if ``False``, the image processing args will be applied as a sequence to all patches. Default: False.
+ random_apply: randomly select a sublist (order agnostic) of args to
+ apply transformation.
+ If ``int`` (batchwise mode only), a fixed number of transformations will be selected.
+ 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.
Return:
List[Union[torch.Tensor, Tuple[torch.Tensor, torch.Tensor]]]: the tensor (, and the transformation matrix)
@@ -51,9 +64,14 @@ class PatchSequential(ImageSequential):
... grid_size=(2,2),
... patchwise_apply=False,
... same_on_batch=True,
+ ... random_apply=True,
... )
- >>> seq(input).shape
+ >>> out = seq(input)
+ >>> out.shape
torch.Size([2, 3, 224, 224])
+ >>> out1 = seq(input, seq._params)
+ >>> torch.equal(out, out1)
+ True
"""
def __init__(
@@ -64,19 +82,28 @@ class PatchSequential(ImageSequential):
same_on_batch: Optional[bool] = None,
keepdim: Optional[bool] = None,
patchwise_apply: bool = False,
+ 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])
+ 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]}."
+ )
+ _random_apply = random_apply
+ elif patchwise_apply and isinstance(random_apply, (int, tuple)):
+ raise ValueError(f"Only boolean value allowed when `patchwise_apply` is set to True. Got {random_apply}.")
+ else:
+ _random_apply = random_apply
super(PatchSequential, self).__init__(
- *args, same_on_batch=same_on_batch, return_transform=False, keepdim=keepdim
+ *args, same_on_batch=same_on_batch, return_transform=False, keepdim=keepdim, random_apply=_random_apply
)
assert padding in ["same", "valid"], f"`padding` must be either `same` or `valid`. Got {padding}."
self.grid_size = grid_size
self.padding = padding
self.patchwise_apply = patchwise_apply
- if patchwise_apply:
- 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]}."
- )
def is_intensity_only(self) -> bool:
"""Check if all transformations are intensity-based.
@@ -194,21 +221,36 @@ class PatchSequential(ImageSequential):
return restored_tensor
def forward_patchwise(
- self, input: torch.Tensor, params: Optional[List[Optional[Dict[str, Dict[str, torch.Tensor]]]]] = None
+ self, input: torch.Tensor, params: Optional[List[List[ParamItem]]] = None
) -> torch.Tensor: # NOTE: return_transform is always False here.
if params is None:
- assert input.size(1) == len(list(self.children()))
- params = [None] * input.size(1)
+ params = [[]] * input.size(1)
+ auglist = [self.get_forward_sequence() for _ in range(input.size(1))]
else:
- assert input.size(1) == len(list(self.children())) == len(params)
- out = [
- proc(inp, param) for inp, proc, param in zip(input.permute(1, 0, 2, 3, 4), list(self.children()), params)
- ]
- input = torch.stack(out, dim=1)
+ 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))
+ 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[Dict[str, Dict[str, torch.Tensor]]] = None
+ 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:])
@@ -217,9 +259,8 @@ class PatchSequential(ImageSequential):
batch_shape = (input.size(0) * input.size(1), *input.shape[-3:])
if params is None:
- params = {}
- for aug in self.children():
- func_name = aug.__class__.__name__
+ params = []
+ for name, aug in self.get_forward_sequence():
if isinstance(aug, _AugmentationBase):
aug.same_on_batch = False
param = aug.forward_parameters(batch_shape)
@@ -231,7 +272,7 @@ class PatchSequential(ImageSequential):
aug.same_on_batch = True
else:
param = None
- params.update({func_name: param})
+ params.append(ParamItem(name, param))
input = super().forward(input.view(-1, *input.shape[-3:]), params) # type: ignore
@@ -240,9 +281,10 @@ class PatchSequential(ImageSequential):
def forward( # type: ignore
self,
input: Union[torch.Tensor, Tuple[torch.Tensor, torch.Tensor]],
- params: Optional[Dict[str, Dict[str, torch.Tensor]]] = None,
+ params: Optional[Union[List[ParamItem], List[List[ParamItem]]]] = None,
) -> Union[torch.Tensor, Tuple[torch.Tensor, torch.Tensor]]: # NOTE: return_transform is always False here.
"""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]
@@ -251,16 +293,17 @@ class PatchSequential(ImageSequential):
input = self.extract_patches(input, self.grid_size, pad)
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:
- assert params is None, "Passing params to patchwise forward is currently not supported."
+ params = cast(List[List[ParamItem]], params)
if isinstance(input, (tuple,)):
- input = self.forward_patchwise(input[0]), input[1]
+ input = self.forward_patchwise(input[0], params), input[1]
else:
- input = self.forward_patchwise(input)
+ input = self.forward_patchwise(input, params)
if isinstance(input, (tuple,)):
input = (self.restore_from_patches(input[0], self.grid_size, pad=pad), input[1])
diff --git a/kornia/augmentation/container/video.py b/kornia/augmentation/container/video.py
index ffe9a3c47..06f477d77 100644
--- a/kornia/augmentation/container/video.py
+++ b/kornia/augmentation/container/video.py
@@ -1,4 +1,5 @@
-from typing import cast, Tuple, Union
+from itertools import zip_longest
+from typing import cast, List, Optional, Tuple, Union
import torch
import torch.nn as nn
@@ -6,7 +7,9 @@ import torch.nn as nn
import kornia
from kornia.augmentation.base import _AugmentationBase
-from .image import ImageSequential
+from .image import ImageSequential, ParamItem
+
+__all__ = ["VideoSequential"]
# TODO: Rewrite this to support inverse operation by having a generic AugmentationSequential.
@@ -19,9 +22,15 @@ class VideoSequential(ImageSequential):
settings on `same_on_batch`, etc.
Args:
- *args (_AugmentationBase): a list of augmentation module.
- data_format (str): only BCTHW and BTCHW are supported. Default: BTCHW.
- same_on_frame (bool): apply the same transformation across the channel per frame. Default: True.
+ *args: a list of augmentation module.
+ data_format: only BCTHW and BTCHW are supported.
+ same_on_frame: apply the same transformation across the channel per frame.
+ random_apply: randomly select a sublist (order agnostic) of args to
+ apply transformation.
+ If int, a fixed number of transformations will be selected.
+ If (a,), x number of transformations (a <= x <= len(args)) will be selected.
+ 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.
Example:
If set `same_on_frame` to True, we would expect the same augmentation has been applied to each
@@ -32,6 +41,7 @@ class VideoSequential(ImageSequential):
... kornia.augmentation.ColorJitter(0.1, 0.1, 0.1, 0.1, p=1.0),
... kornia.color.BgrToRgb(),
... kornia.augmentation.RandomAffine(360, p=1.0),
+ ... random_apply=10,
... data_format="BCTHW",
... same_on_frame=True)
>>> output = aug_list(input)
@@ -54,10 +64,23 @@ class VideoSequential(ImageSequential):
torch.Size([2, 3, 4, 5, 6])
>>> (output[0, :, 0] == output[0, :, 1]).all()
tensor(False)
+
+ Reproduce with provided params.
+ >>> out2 = aug_list(input, params=aug_list._params)
+ >>> torch.equal(output, out2)
+ True
"""
- def __init__(self, *args: nn.Module, data_format="BTCHW", same_on_frame: bool = True) -> None:
- super(VideoSequential, self).__init__(*args, same_on_batch=None, return_transform=None, keepdim=None)
+ def __init__(
+ self,
+ *args: nn.Module,
+ data_format: str = "BTCHW",
+ same_on_frame: bool = True,
+ random_apply: Union[int, bool, Tuple[int, int]] = False,
+ ) -> None:
+ super(VideoSequential, self).__init__(
+ *args, same_on_batch=None, return_transform=None, keepdim=None, random_apply=random_apply
+ )
self.same_on_frame = same_on_frame
self.data_format = data_format.upper()
assert self.data_format in ["BCTHW", "BTCHW"], f"Only `BCTHW` and `BTCHW` are supported. Got `{data_format}`."
@@ -101,9 +124,16 @@ class VideoSequential(ImageSequential):
pass
return input
- def forward(self, input: torch.Tensor) -> Union[torch.Tensor, Tuple[torch.Tensor, torch.Tensor]]: # type: ignore
+ 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
+
# Size of T
frame_num = input.size(self._temporal_channel)
# Got param generation shape to (B, C, H, W). Ignoring T.
@@ -113,18 +143,18 @@ class VideoSequential(ImageSequential):
if not self.same_on_frame:
# Overwrite param generation shape to (B * T, C, H, W).
batch_shape = input.shape
- for aug in self.children():
- if isinstance(aug, _AugmentationBase):
- param = aug.forward_parameters(batch_shape)
+
+ for (name, module), param in zip_longest(named_modules, params):
+ if param is None and isinstance(module, _AugmentationBase):
+ mod_param = module.forward_parameters(batch_shape)
if self.same_on_frame:
- for k, v in param.items():
+ for k, v in mod_param.items():
# TODO: revise colorjitter order param in the future to align the standard.
- if not (k == "order" and isinstance(aug, kornia.augmentation.ColorJitter)):
- param.update({k: self.__repeat_param_across_channels__(v, frame_num)})
- else:
- param = None
+ 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)
- input = self.apply_to_input(input, aug, param=param) # type: ignore
+ input = self.apply_to_input(input, name, module, param=param) # type: ignore
if isinstance(input, (tuple, list)):
input[0] = self._input_shape_convert_back(input[0], frame_num)
diff --git a/test/augmentation/test_container.py b/test/augmentation/test_container.py
index ca72bb148..8d48806a1 100644
--- a/test/augmentation/test_container.py
+++ b/test/augmentation/test_container.py
@@ -8,6 +8,30 @@ from kornia.constants import BorderType
from kornia.geometry.transform import bbox_to_mask
+def reproducibility_test(input, seq):
+ if isinstance(input, (tuple, list)):
+ output_1 = seq(*input)
+ output_2 = seq(*input, params=seq._params)
+ else:
+ output_1 = seq(input)
+ output_2 = seq(input, params=seq._params)
+
+ if isinstance(output_1, (tuple, list)) and isinstance(output_2, (tuple, list)):
+ [
+ assert_allclose(o1, o2)
+ for o1, o2 in zip(output_1, output_2)
+ if isinstance(o1, (torch.Tensor,)) and isinstance(o2, (torch.Tensor,))
+ ]
+ elif isinstance(output_1, (tuple, list)) and isinstance(output_2, (torch.Tensor,)):
+ assert_allclose(output_1[0], output_2)
+ elif isinstance(output_2, (tuple, list)) and isinstance(output_1, (torch.Tensor,)):
+ assert_allclose(output_1, output_2[0])
+ elif isinstance(output_2, (torch.Tensor,)) and isinstance(output_1, (torch.Tensor,)):
+ assert_allclose(output_1, output_2, msg=f"{seq._params}")
+ else:
+ assert False, ("cannot compare", type(output_1), type(output_2))
+
+
class TestVideoSequential:
@pytest.mark.parametrize('shape', [(3, 4), (2, 3, 4), (2, 3, 5, 6), (2, 3, 4, 5, 6, 7)])
@pytest.mark.parametrize('data_format', ["BCTHW", "BTCHW"])
@@ -45,24 +69,13 @@ class TestVideoSequential:
input = torch.randint(255, (1, 3, 3, 5, 6), device=device, dtype=dtype).repeat(2, 1, 1, 1, 1) / 255.0
torch.manual_seed(21)
aug_list = K.VideoSequential(augmentation, data_format=data_format, same_on_frame=True)
- output = aug_list(input)
-
- @pytest.mark.parametrize('augmentations', [[K.ColorJitter(0.1, 0.1, 0.1, 0.1, p=0.5), K.RandomAffine(360, p=0.5)]])
- @pytest.mark.parametrize('data_format', ["BCTHW", "BTCHW"])
- def test_p_half(self, augmentations, data_format, device, dtype):
- input = torch.randn(1, 3, 3, 5, 6, device=device, dtype=dtype).repeat(2, 1, 1, 1, 1)
- torch.manual_seed(21)
- aug_list = K.VideoSequential(*augmentations, data_format=data_format, same_on_frame=True)
- output = aug_list(input)
-
- assert not (output[0] == input[0]).all()
- assert (output[1] == input[1]).all()
+ reproducibility_test(input, aug_list)
@pytest.mark.parametrize(
'augmentations',
[
[K.ColorJitter(0.1, 0.1, 0.1, 0.1, p=1.0), K.RandomAffine(360, p=1.0)],
- [K.ColorJitter(0.1, 0.1, 0.1, 0.1, p=1.0)],
+ [K.ColorJitter(0.1, 0.1, 0.1, 0.1, p=1.0), K.ColorJitter(0.1, 0.1, 0.1, 0.1, p=1.0)],
[K.RandomAffine(360, p=1.0), kornia.color.BgrToRgb()],
[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)],
@@ -70,8 +83,11 @@ class TestVideoSequential:
],
)
@pytest.mark.parametrize('data_format', ["BCTHW", "BTCHW"])
- def test_same_on_frame(self, augmentations, data_format, device, dtype):
- aug_list = K.VideoSequential(*augmentations, data_format=data_format, same_on_frame=True)
+ @pytest.mark.parametrize('random_apply', [1, (1, 1), (1,), 10, True, False])
+ def test_same_on_frame(self, augmentations, data_format, random_apply, device, dtype):
+ aug_list = K.VideoSequential(
+ *augmentations, data_format=data_format, same_on_frame=True, random_apply=random_apply
+ )
if data_format == 'BCTHW':
input = torch.randn(2, 3, 1, 5, 6, device=device, dtype=dtype).repeat(1, 1, 4, 1, 1)
@@ -85,6 +101,7 @@ class TestVideoSequential:
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)]]
@@ -101,17 +118,15 @@ class TestVideoSequential:
torch.manual_seed(0)
output_1 = aug_list_1(input)
- param_1 = list(aug_list_1.children())[0]._params
torch.manual_seed(0)
if data_format == 'BCTHW':
input = input.transpose(1, 2)
output_2 = aug_list_2(input.reshape(-1, 3, 5, 6))
- param_2 = list(aug_list_2.children())[0]._params
output_2 = output_2.view(2, 4, 3, 5, 6)
if data_format == 'BCTHW':
output_2 = output_2.transpose(1, 2)
- assert (output_1 == output_2).all()
+ assert (output_1 == output_2).all(), dict(aug_list_1._params)
@pytest.mark.jit
@pytest.mark.skip(reason="turn off due to Union Type")
@@ -127,17 +142,20 @@ 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])
- def test_construction(self, same_on_batch, return_transform, keepdim):
+ @pytest.mark.parametrize('random_apply', [1, (2, 2), (1, 2), (2,), 10, True, False])
+ def test_construction(self, same_on_batch, return_transform, keepdim, random_apply):
K.ImageSequential(
K.ColorJitter(0.1, 0.1, 0.1, 0.1, p=1.0),
K.RandomAffine(360, p=1.0),
same_on_batch=same_on_batch,
return_transform=return_transform,
keepdim=keepdim,
+ random_apply=random_apply,
)
@pytest.mark.parametrize("return_transform", [True, False, None])
- def test_forward(self, return_transform, device, dtype):
+ @pytest.mark.parametrize('random_apply', [1, (2, 2), (1, 2), (2,), 10, True, False])
+ def test_forward(self, return_transform, random_apply, device, dtype):
inp = torch.randn(1, 3, 30, 30, device=device, dtype=dtype)
aug = K.ImageSequential(
K.ColorJitter(0.1, 0.1, 0.1, 0.1, p=1.0),
@@ -145,12 +163,14 @@ class TestSequential:
K.ColorJitter(0.1, 0.1, 0.1, 0.1, p=1.0, return_transform=True),
K.RandomAffine(360, p=1.0),
return_transform=return_transform,
+ random_apply=random_apply,
)
out = aug(inp)
if isinstance(out, (tuple,)):
assert out[0].shape == inp.shape
else:
assert out.shape == inp.shape
+ reproducibility_test(inp, aug)
class TestAugmentationSequential:
@@ -162,7 +182,8 @@ class TestAugmentationSequential:
with pytest.raises(Exception): # AssertError and NotImplementedError
K.AugmentationSequential(augmentation_list, data_keys=data_keys)
- def test_forward_and_inverse(self, device, dtype):
+ @pytest.mark.parametrize('random_apply', [1, (2, 2), (1, 2), (2,), 10, True, False])
+ def test_forward_and_inverse(self, random_apply, 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)
@@ -173,12 +194,14 @@ class TestAugmentationSequential:
K.ColorJitter(0.1, 0.1, 0.1, 0.1, p=1.0),
K.RandomAffine(360, p=1.0),
data_keys=["input", "mask", "bbox", "keypoints"],
+ random_apply=random_apply,
)
out = aug(inp, mask, bbox, keypoints)
assert out[0].shape == inp.shape
assert out[1].shape == mask.shape
assert out[2].shape == bbox.shape
assert out[3].shape == keypoints.shape
+ reproducibility_test((inp, mask, bbox, keypoints), aug)
out_inv = aug.inverse(*out)
assert out_inv[0].shape == inp.shape
@@ -194,13 +217,16 @@ class TestAugmentationSequential:
torch.tensor([[[155, 0], [900, 0], [900, 400], [155, 400]]], device=device, dtype=dtype), 1000, 500
)[:, None].float()
+ aug = K.AugmentationSequential(
+ K.RandomAffine(360, p=1.0, return_transform=False), data_keys=['input', 'mask', 'bbox', 'keypoints']
+ )
+ reproducibility_test((inp, mask, bbox, keypoints), aug)
+
aug = K.AugmentationSequential(K.RandomAffine(360, p=1.0, return_transform=True))
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(bbox, data_keys=['bbox']).shape == bbox.shape
- assert aug(keypoints, data_keys=['keypoints']).shape == keypoints.shape
aug = K.AugmentationSequential(K.RandomAffine(360, p=1.0, return_transform=True))
assert aug.inverse(inp, data_keys=['input']).shape == inp.shape
@@ -211,7 +237,8 @@ class TestAugmentationSequential:
aug = K.AugmentationSequential(K.RandomAffine(360, p=1.0, return_transform=True))
assert aug.inverse(mask, data_keys=['mask']).shape == mask.shape
- def test_forward_and_inverse_return_transform(self, device, dtype):
+ @pytest.mark.parametrize('random_apply', [2, (1, 1), (2,), 10, True, False])
+ def test_forward_and_inverse_return_transform(self, random_apply, 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)
@@ -222,6 +249,7 @@ class TestAugmentationSequential:
K.ColorJitter(0.1, 0.1, 0.1, 0.1, p=1.0, return_transform=True),
K.RandomAffine(360, p=1.0, return_transform=True),
data_keys=["input", "mask", "bbox", "keypoints"],
+ random_apply=random_apply,
)
out = aug(inp, mask, bbox, keypoints)
assert out[0][0].shape == inp.shape
@@ -229,13 +257,16 @@ class TestAugmentationSequential:
assert out[2].shape == bbox.shape
assert out[3].shape == keypoints.shape
+ reproducibility_test((inp, mask, bbox, keypoints), aug)
+
out_inv = aug.inverse(*out)
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
- def test_inverse_and_forward_return_transform(self, device, dtype):
+ @pytest.mark.parametrize('random_apply', [1, (2, 2), (1, 2), (2,), 10, True, False])
+ def test_inverse_and_forward_return_transform(self, random_apply, 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)
@@ -246,6 +277,7 @@ class TestAugmentationSequential:
K.ColorJitter(0.1, 0.1, 0.1, 0.1, p=1.0, return_transform=True),
K.RandomAffine(360, p=1.0, return_transform=True),
data_keys=["input", "mask", "bbox", "keypoints"],
+ random_apply=random_apply,
)
out_inv = aug.inverse(inp, mask, bbox, keypoints)
@@ -260,6 +292,8 @@ class TestAugmentationSequential:
assert out[2].shape == bbox.shape
assert out[3].shape == keypoints.shape
+ reproducibility_test((inp, mask, bbox, keypoints), aug)
+
@pytest.mark.jit
@pytest.mark.skip(reason="turn off due to Union Type")
def test_jit(self, device, dtype):
@@ -273,31 +307,63 @@ class TestAugmentationSequential:
class TestPatchSequential:
+ @pytest.mark.parametrize(
+ 'error_param',
+ [
+ {"random_apply": False, "patchwise_apply": True, "grid_size": (2, 3)},
+ {"random_apply": 2, "patchwise_apply": True},
+ {"random_apply": (2, 3), "patchwise_apply": True},
+ ],
+ )
+ def test_exception(self, error_param):
+ with pytest.raises(Exception): # AssertError and NotImplementedError
+ 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),
+ ),
+ 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),
+ **error_param,
+ )
+
@pytest.mark.parametrize('shape', [(2, 3, 24, 24)])
@pytest.mark.parametrize('padding', ["same", "valid"])
@pytest.mark.parametrize('patchwise_apply', [True, False])
@pytest.mark.parametrize('same_on_batch', [True, False, None])
@pytest.mark.parametrize('keepdim', [True, False, None])
- def test_forward(self, shape, padding, patchwise_apply, same_on_batch, keepdim, device, dtype):
- 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),
- ),
- 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),
- grid_size=(2, 2),
- padding=padding,
- patchwise_apply=patchwise_apply,
- same_on_batch=same_on_batch,
- keepdim=keepdim,
- )
+ @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):
+ 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),
+ ),
+ 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),
+ grid_size=(2, 2),
+ padding=padding,
+ patchwise_apply=patchwise_apply,
+ same_on_batch=same_on_batch,
+ keepdim=keepdim,
+ random_apply=random_apply,
+ )
+ except:
+ return
+
input = torch.randn(*shape, device=device, dtype=dtype)
trans = torch.randn(shape[0], 3, 3, device=device, dtype=dtype)
out = seq(input)
@@ -307,6 +373,8 @@ class TestPatchSequential:
assert out[0].shape[-3:] == input.shape[-3:]
assert out[1].shape == trans.shape
+ reproducibility_test(input, seq)
+
def test_intensity_only(self):
seq = K.PatchSequential(
K.ImageSequential(