Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

Fix auto augmentation transformation matrix (#2355)

Jian Shi11328cfcd9f7
diff --git a/kornia/augmentation/auto/autoaugment/autoaugment.py b/kornia/augmentation/auto/autoaugment/autoaugment.py
index 253d6bada..ce302156c 100644
--- a/kornia/augmentation/auto/autoaugment/autoaugment.py
+++ b/kornia/augmentation/auto/autoaugment/autoaugment.py
@@ -101,6 +101,13 @@ class AutoAugment(PolicyAugmentBase):
Args:
policy: a customized policy config or presets of "imagenet", "cifar10", and "svhn".
+ transformation_matrix_mode: computation mode for the chained transformation matrix, via `.transform_matrix`
+ attribute.
+ If `silent`, transformation matrix will be computed silently and the non-rigid
+ modules will be ignored as identity transformations.
+ If `rigid`, transformation matrix will be computed silently and the non-rigid
+ modules will trigger errors.
+ If `skip`, transformation matrix will be totally ignored.
Examples:
>>> import torch
@@ -111,7 +118,9 @@ class AutoAugment(PolicyAugmentBase):
torch.Size([5, 3, 30, 30])
"""
- def __init__(self, policy: Union[str, List[SUBPLOLICY_CONFIG]] = "imagenet") -> None:
+ def __init__(
+ self, policy: Union[str, List[SUBPLOLICY_CONFIG]] = "imagenet", transformation_matrix_mode: str = "silent"
+ ) -> None:
if policy == "imagenet":
_policy = imagenet_policy
elif policy == "cifar10":
@@ -123,7 +132,7 @@ class AutoAugment(PolicyAugmentBase):
else:
raise NotImplementedError(f"Invalid policy `{policy}`.")
- super().__init__(_policy)
+ super().__init__(_policy, transformation_matrix_mode=transformation_matrix_mode)
selection_weights = tensor([1.0 / len(self)] * len(self))
self.rand_selector = Categorical(selection_weights)
diff --git a/kornia/augmentation/auto/base.py b/kornia/augmentation/auto/base.py
index 593e637de..b9f74a2dd 100644
--- a/kornia/augmentation/auto/base.py
+++ b/kornia/augmentation/auto/base.py
@@ -4,7 +4,8 @@ import torch
from kornia.augmentation.auto.operations.base import OperationBase
from kornia.augmentation.auto.operations.policy import PolicySequential
-from kornia.augmentation.container.base import ImageSequentialBase
+from kornia.augmentation.container.base import ImageSequentialBase, TransformMatrixMinIn
+from kornia.augmentation.container.ops import InputSequentialOps
from kornia.augmentation.container.params import ParamItem
from kornia.core import Module, Tensor
from kornia.utils import eye_like
@@ -14,12 +15,21 @@ OP_CONFIG = Tuple[str, NUMBER, Optional[NUMBER]]
SUBPLOLICY_CONFIG = List[OP_CONFIG]
-class PolicyAugmentBase(ImageSequentialBase):
+class PolicyAugmentBase(TransformMatrixMinIn, ImageSequentialBase):
"""Policy-based image augmentation."""
- def __init__(self, policy: List[SUBPLOLICY_CONFIG]) -> None:
+ def __init__(self, policy: List[SUBPLOLICY_CONFIG], transformation_matrix_mode: str = "silence") -> None:
policies = self.compose_policy(policy)
super().__init__(*policies)
+ self._parse_transformation_matrix_mode(transformation_matrix_mode)
+ self._valid_ops_for_transform_computation: Tuple[Any, ...] = (PolicySequential,)
+
+ def _update_transform_matrix_for_valid_op(self, module: PolicySequential) -> None: # type: ignore
+ self._transform_matrices.append(module.transform_matrix)
+
+ def clear_state(self) -> None:
+ self._reset_transform_matrix_state()
+ return super().clear_state()
def compose_policy(self, policy: List[SUBPLOLICY_CONFIG]) -> List[PolicySequential]:
"""Compose policy by the provided policy config."""
@@ -80,3 +90,10 @@ class PolicyAugmentBase(ImageSequentialBase):
param = ParamItem(name, mod_param)
params.append(param)
return params
+
+ def transform_inputs(self, input: Tensor, params: List[ParamItem], extra_args: Dict[str, Any] = {}) -> Tensor:
+ for param in params:
+ module = self.get_submodule(param.name)
+ input = InputSequentialOps.transform(input, module=module, param=param, extra_args=extra_args)
+ self._update_transform_matrix_by_module(module)
+ return input
diff --git a/kornia/augmentation/auto/operations/base.py b/kornia/augmentation/auto/operations/base.py
index 225b77ce4..a1299f15e 100644
--- a/kornia/augmentation/auto/operations/base.py
+++ b/kornia/augmentation/auto/operations/base.py
@@ -156,6 +156,12 @@ class OperationBase(Module):
return self._gradient_estimator.apply(self.magnitude, output)
return batch_prob * self.op(input, params=params) + (1 - batch_prob) * input
+ @property
+ def transform_matrix(self) -> Optional[Tensor]:
+ if hasattr(self.op, "transform_matrix"):
+ return self.op.transform_matrix # type:ignore
+ return None
+
@property
def magnitude(self) -> Optional[Tensor]:
if self._magnitude is None:
diff --git a/kornia/augmentation/auto/operations/ops.py b/kornia/augmentation/auto/operations/ops.py
index eb625f05e..20a7dc190 100644
--- a/kornia/augmentation/auto/operations/ops.py
+++ b/kornia/augmentation/auto/operations/ops.py
@@ -451,7 +451,7 @@ class ShearX(OperationBase):
f"The lower bound must above 0. Got {magnitude_range[0]}."
)
super().__init__(
- K.RandomShear(magnitude_range, same_on_batch=False, p=initial_probability),
+ K.RandomShear(magnitude_range, same_on_batch=False, p=initial_probability, align_corners=True),
initial_magnitude=[("shear_x", initial_magnitude)],
temperature=temperature,
symmetric_megnitude=symmetric_megnitude,
@@ -491,7 +491,10 @@ class ShearY(OperationBase):
)
super().__init__(
K.RandomShear(
- (0.0, 0.0, magnitude_range[0], magnitude_range[1]), same_on_batch=False, p=initial_probability
+ (0.0, 0.0, magnitude_range[0], magnitude_range[1]),
+ same_on_batch=False,
+ p=initial_probability,
+ align_corners=True,
),
initial_magnitude=[("shear_y", initial_magnitude)],
temperature=temperature,
@@ -526,7 +529,7 @@ class TranslateX(OperationBase):
f"The lower bound must above 0. Got {magnitude_range[0]}."
)
super().__init__(
- K.RandomTranslate(magnitude_range, same_on_batch=False, p=initial_probability),
+ K.RandomTranslate(magnitude_range, same_on_batch=False, p=initial_probability, align_corners=True),
initial_magnitude=[("translate_x", initial_magnitude)],
temperature=temperature,
symmetric_megnitude=symmetric_megnitude,
@@ -559,7 +562,7 @@ class TranslateY(OperationBase):
f"The lower bound must above 0. Got {magnitude_range[0]}."
)
super().__init__(
- K.RandomTranslate(None, magnitude_range, same_on_batch=False, p=initial_probability),
+ K.RandomTranslate(None, magnitude_range, same_on_batch=False, p=initial_probability, align_corners=True),
initial_magnitude=[("translate_y", initial_magnitude)],
temperature=temperature,
symmetric_megnitude=symmetric_megnitude,
diff --git a/kornia/augmentation/auto/operations/policy.py b/kornia/augmentation/auto/operations/policy.py
index 01a1eda66..20b00f47a 100644
--- a/kornia/augmentation/auto/operations/policy.py
+++ b/kornia/augmentation/auto/operations/policy.py
@@ -4,14 +4,15 @@ from torch import Size
import kornia.augmentation as K
from kornia.augmentation.auto.operations import OperationBase
-from kornia.augmentation.container.base import ImageSequentialBase
+from kornia.augmentation.container.base import ImageSequentialBase, TransformMatrixMinIn
+from kornia.augmentation.container.ops import InputSequentialOps
from kornia.augmentation.container.params import ParamItem
from kornia.augmentation.utils import _transform_input, override_parameters
from kornia.core import Module, Tensor, as_tensor
from kornia.utils import eye_like
-class PolicySequential(ImageSequentialBase):
+class PolicySequential(TransformMatrixMinIn, ImageSequentialBase):
"""Policy tuple for applying multiple operations.
Args:
@@ -21,6 +22,14 @@ class PolicySequential(ImageSequentialBase):
def __init__(self, *operations: OperationBase) -> None:
self.validate_operations(*operations)
super().__init__(*operations)
+ self._valid_ops_for_transform_computation: Tuple[Any, ...] = (OperationBase,)
+
+ def _update_transform_matrix_for_valid_op(self, module: Module) -> None:
+ self._transform_matrices.append(module.transform_matrix) # type: ignore
+
+ def clear_state(self) -> None:
+ self._reset_transform_matrix_state()
+ return super().clear_state()
def validate_operations(self, *operations: OperationBase) -> None:
invalid_ops: List[OperationBase] = []
@@ -97,3 +106,10 @@ class PolicySequential(ImageSequentialBase):
param = ParamItem(name, mod_param)
params.append(param)
return params
+
+ def transform_inputs(self, input: Tensor, params: List[ParamItem], extra_args: Dict[str, Any] = {}) -> Tensor:
+ for param in params:
+ module = self.get_submodule(param.name)
+ input = InputSequentialOps.transform(input, module=module, param=param, extra_args=extra_args)
+ self._update_transform_matrix_by_module(module)
+ return input
diff --git a/kornia/augmentation/auto/rand_augment/rand_augment.py b/kornia/augmentation/auto/rand_augment/rand_augment.py
index 0e27734e1..7b4332be8 100644
--- a/kornia/augmentation/auto/rand_augment/rand_augment.py
+++ b/kornia/augmentation/auto/rand_augment/rand_augment.py
@@ -38,6 +38,13 @@ class RandAugment(PolicyAugmentBase):
n: the number of augmentations to apply sequentially.
m: magnitude for all the augmentations, ranged from [0, 30].
policy: candidate transformations. If None, a default candidate list will be used.
+ transformation_matrix_mode: computation mode for the chained transformation matrix, via `.transform_matrix`
+ attribute.
+ If `silent`, transformation matrix will be computed silently and the non-rigid
+ modules will be ignored as identity transformations.
+ If `rigid`, transformation matrix will be computed silently and the non-rigid
+ modules will trigger errors.
+ If `skip`, transformation matrix will be totally ignored.
Examples:
>>> import kornia.augmentation as K
@@ -47,7 +54,13 @@ class RandAugment(PolicyAugmentBase):
torch.Size([5, 3, 30, 30])
"""
- def __init__(self, n: int, m: int, policy: Optional[List[SUBPLOLICY_CONFIG]] = None) -> None:
+ def __init__(
+ self,
+ n: int,
+ m: int,
+ policy: Optional[List[SUBPLOLICY_CONFIG]] = None,
+ transformation_matrix_mode: str = "silent",
+ ) -> None:
if m <= 0 or m >= 30:
raise ValueError(f"Expect `m` in [0, 30]. Got {m}.")
@@ -56,7 +69,7 @@ class RandAugment(PolicyAugmentBase):
else:
_policy = policy
- super().__init__(_policy)
+ super().__init__(_policy, transformation_matrix_mode=transformation_matrix_mode)
selection_weights = torch.tensor([1.0 / len(self)] * len(self))
self.rand_selector = Categorical(selection_weights)
self.n = n
@@ -64,7 +77,7 @@ class RandAugment(PolicyAugmentBase):
def compose_subpolicy_sequential(self, subpolicy: SUBPLOLICY_CONFIG) -> PolicySequential:
if len(subpolicy) != 1:
- raise RuntimeError(f"Each policy must have only one operation for TrivialAugment. Got {len(subpolicy)}.")
+ raise RuntimeError(f"Each policy must have only one operation for RandAugment. Got {len(subpolicy)}.")
name, low, high = subpolicy[0]
return PolicySequential(*[getattr(ops, name)(low, high)])
diff --git a/kornia/augmentation/auto/trivial_augment/trivial_augment.py b/kornia/augmentation/auto/trivial_augment/trivial_augment.py
index 849fc2b15..06dd5450f 100644
--- a/kornia/augmentation/auto/trivial_augment/trivial_augment.py
+++ b/kornia/augmentation/auto/trivial_augment/trivial_augment.py
@@ -32,6 +32,13 @@ class TrivialAugment(PolicyAugmentBase):
Args:
policy: candidate transformations. If None, a default candidate list will be used.
+ transformation_matrix_mode: computation mode for the chained transformation matrix, via `.transform_matrix`
+ attribute.
+ If `silent`, transformation matrix will be computed silently and the non-rigid
+ modules will be ignored as identity transformations.
+ If `rigid`, transformation matrix will be computed silently and the non-rigid
+ modules will trigger errors.
+ If `skip`, transformation matrix will be totally ignored.
Examples:
>>> import kornia.augmentation as K
@@ -41,13 +48,15 @@ class TrivialAugment(PolicyAugmentBase):
torch.Size([5, 3, 30, 30])
"""
- def __init__(self, policy: Optional[List[SUBPLOLICY_CONFIG]] = None) -> None:
+ def __init__(
+ self, policy: Optional[List[SUBPLOLICY_CONFIG]] = None, transformation_matrix_mode: str = "silent"
+ ) -> None:
if policy is None:
_policy = default_policy
else:
_policy = policy
- super().__init__(_policy)
+ super().__init__(_policy, transformation_matrix_mode=transformation_matrix_mode)
selection_weights = torch.tensor([1.0 / len(self)] * len(self))
self.rand_selector = Categorical(selection_weights)
diff --git a/kornia/augmentation/container/augment.py b/kornia/augmentation/container/augment.py
index a68448829..ed8f2d0d3 100644
--- a/kornia/augmentation/container/augment.py
+++ b/kornia/augmentation/container/augment.py
@@ -1,7 +1,8 @@
import warnings
from typing import Any, Dict, List, Optional, Tuple, Union, cast
-import kornia.augmentation as K
+from kornia.augmentation._2d.base import RigidAffineAugmentationBase2D
+from kornia.augmentation._3d.base import AugmentationBase3D, RigidAffineAugmentationBase3D
from kornia.augmentation.base import _AugmentationBase
from kornia.constants import DataKey, Resample
from kornia.core import Module, Tensor
@@ -9,6 +10,7 @@ from kornia.geometry.boxes import Boxes, VideoBoxes
from kornia.geometry.keypoints import Keypoints, VideoKeypoints
from kornia.utils import eye_like, is_autocast_enabled
+from .base import TransformMatrixMinIn
from .image import ImageSequential
from .ops import AugmentationSequentialOps, DataType
from .params import ParamItem
@@ -22,7 +24,7 @@ _KEYPOINTS_OPTIONS = {DataKey.KEYPOINTS}
_IMG_MSK_OPTIONS = {DataKey.INPUT, DataKey.MASK}
-class AugmentationSequential(ImageSequential):
+class AugmentationSequential(TransformMatrixMinIn, ImageSequential):
r"""AugmentationSequential for handling multiple input types like inputs, masks, keypoints at once.
.. image:: _static/img/AugmentationSequential.png
@@ -46,13 +48,13 @@ 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.
- transformation_matrix: computation mode for the chained transformation matrix, via `.transform_matrix`
- attribute.
- If `silence`, transformation matrix will be computed silently and the non-rigid modules
- will be ignored as identity transformations.
- If `rigid`, transformation matrix will be computed silently and the non-rigid modules
- will trigger errors.
- If `skip`, transformation matrix will be totally ignored.
+ transformation_matrix_mode: computation mode for the chained transformation matrix, via `.transform_matrix`
+ attribute.
+ If `silent`, transformation matrix will be computed silently and the non-rigid
+ modules will be ignored as identity transformations.
+ If `rigid`, transformation matrix will be computed silently and the non-rigid
+ modules will trigger errors.
+ If `skip`, transformation matrix will be totally ignored.
extra_args: to control the behaviour for each datakeys. By default, masks are handled by nearest interpolation
strategies.
@@ -155,13 +157,13 @@ class AugmentationSequential(ImageSequential):
keepdim: Optional[bool] = None,
random_apply: Union[int, bool, Tuple[int, int]] = False,
random_apply_weights: Optional[List[float]] = None,
- transformation_matrix: str = "silence",
+ transformation_matrix_mode: str = "silent",
extra_args: Dict[DataKey, Dict[str, Any]] = {
DataKey.MASK: {"resample": Resample.NEAREST, "align_corners": None}
},
) -> None:
self._transform_matrix: Optional[Tensor]
- self._transform_matrices: List[Tensor] = []
+ self._transform_matrices: List[Optional[Tensor]] = []
super().__init__(
*args,
@@ -171,6 +173,14 @@ class AugmentationSequential(ImageSequential):
random_apply_weights=random_apply_weights,
)
+ self._parse_transformation_matrix_mode(transformation_matrix_mode)
+
+ self._valid_ops_for_transform_computation: Tuple[Any, ...] = (
+ RigidAffineAugmentationBase2D,
+ RigidAffineAugmentationBase3D,
+ AugmentationSequential,
+ )
+
self.data_keys = [DataKey.get(inp) for inp in data_keys]
if not all(in_type in DataKey for in_type in self.data_keys):
@@ -181,14 +191,6 @@ class AugmentationSequential(ImageSequential):
self.transform_op = AugmentationSequentialOps(self.data_keys)
- _valid_transformation_matrix_args = ["silence", "rigid", "skip"]
- if transformation_matrix not in _valid_transformation_matrix_args:
- raise ValueError(
- f"`transformation_matrix` has to be one of {_valid_transformation_matrix_args}. "
- f"Got {transformation_matrix}."
- )
- self._transformation_matrix_arg = transformation_matrix
-
self.contains_video_sequential: bool = False
self.contains_3d_augmentation: bool = False
for arg in args:
@@ -197,45 +199,17 @@ class AugmentationSequential(ImageSequential):
if isinstance(arg, VideoSequential):
self.contains_video_sequential = True
# NOTE: only for images are supported for 3D.
- if isinstance(arg, K.AugmentationBase3D):
+ if isinstance(arg, AugmentationBase3D):
self.contains_3d_augmentation = True
self._transform_matrix = None
self.extra_args = extra_args
def clear_state(self) -> None:
- self._transform_matrix = None
- self._transform_matrices = []
+ self._reset_transform_matrix_state()
return super().clear_state()
- @property
- def transform_matrix(self) -> Optional[Tensor]:
- # In AugmentationSequential, the parent class is accessed first.
- # So that it was None in the beginning. We hereby use lazy computation here.
- if self._transform_matrix is None and len(self._transform_matrices) != 0:
- self._transform_matrix = self._transform_matrices[0]
- for mat in self._transform_matrices[1:]:
- self._update_transform_matrix(mat)
- return self._transform_matrix
-
- def _update_transform_matrix_by_module(self, module: Module) -> None:
- if self._transformation_matrix_arg == "skip":
- return
- if isinstance(
- module, (K.RigidAffineAugmentationBase2D, K.RigidAffineAugmentationBase3D, AugmentationSequential)
- ):
- # Passed in pointer, allows lazy transformation matrix computation
- self._transform_matrices.append(module.transform_matrix) # type: ignore
- elif self._transformation_matrix_arg == "rigid":
- raise RuntimeError(
- f"Non-rigid module `{module}` is not supported under `rigid` computation mode. "
- "Please either update the module or change the `transformation_matrix` argument."
- )
-
- def _update_transform_matrix(self, transform_matrix: Tensor) -> None:
- if self._transform_matrix is None:
- self._transform_matrix = transform_matrix
- else:
- self._transform_matrix = transform_matrix @ self._transform_matrix
+ def _update_transform_matrix_for_valid_op(self, module: Module) -> None:
+ self._transform_matrices.append(module.transform_matrix) # type: ignore
def identity_matrix(self, input: Tensor) -> Tensor:
"""Return identity matrix."""
diff --git a/kornia/augmentation/container/base.py b/kornia/augmentation/container/base.py
index 8cc81e0c5..11e044a6b 100644
--- a/kornia/augmentation/container/base.py
+++ b/kornia/augmentation/container/base.py
@@ -274,3 +274,58 @@ class ImageSequentialBase(SequentialBase):
self._params = params
return input
+
+
+class TransformMatrixMinIn:
+ """Enables computation matrix computation."""
+
+ _valid_ops_for_transform_computation: Tuple[Any, ...] = ()
+ _transformation_matrix_arg: str = "silent"
+
+ def __init__(self, *args, **kwargs) -> None: # type:ignore
+ super().__init__(*args, **kwargs)
+ self._transform_matrix: Optional[Tensor] = None
+ self._transform_matrices: List[Optional[Tensor]] = []
+
+ def _parse_transformation_matrix_mode(self, transformation_matrix_mode: str) -> None:
+ _valid_transformation_matrix_args = {"silence", "silent", "rigid", "skip"}
+ if transformation_matrix_mode not in _valid_transformation_matrix_args:
+ raise ValueError(
+ f"`transformation_matrix` has to be one of {_valid_transformation_matrix_args}. "
+ f"Got {transformation_matrix_mode}."
+ )
+ self._transformation_matrix_arg = transformation_matrix_mode
+
+ @property
+ def transform_matrix(self) -> Optional[Tensor]:
+ # In AugmentationSequential, the parent class is accessed first.
+ # So that it was None in the beginning. We hereby use lazy computation here.
+ if self._transform_matrix is None and len(self._transform_matrices) != 0:
+ self._transform_matrix = self._transform_matrices[0]
+ for mat in self._transform_matrices[1:]:
+ self._update_transform_matrix(mat)
+ return self._transform_matrix
+
+ def _update_transform_matrix_for_valid_op(self, module: Module) -> None:
+ raise NotImplementedError(module)
+
+ def _update_transform_matrix_by_module(self, module: Module) -> None:
+ if self._transformation_matrix_arg == "skip":
+ return
+ if isinstance(module, self._valid_ops_for_transform_computation):
+ self._update_transform_matrix_for_valid_op(module)
+ elif self._transformation_matrix_arg == "rigid":
+ raise RuntimeError(
+ f"Non-rigid module `{module}` is not supported under `rigid` computation mode. "
+ "Please either update the module or change the `transformation_matrix` argument."
+ )
+
+ def _update_transform_matrix(self, transform_matrix: Optional[Tensor]) -> None:
+ if self._transform_matrix is None:
+ self._transform_matrix = transform_matrix
+ else:
+ self._transform_matrix = transform_matrix @ self._transform_matrix
+
+ def _reset_transform_matrix_state(self) -> None:
+ self._transform_matrix = None
+ self._transform_matrices = []
diff --git a/test/augmentation/test_auto_operation.py b/test/augmentation/test_auto_operation.py
index 72d51bc1b..d3751790a 100644
--- a/test/augmentation/test_auto_operation.py
+++ b/test/augmentation/test_auto_operation.py
@@ -74,21 +74,22 @@ class TestOperations:
class TestAutoAugment:
@pytest.mark.parametrize("policy", ["imagenet", "cifar10", "svhn", [[("shear_x", 0.9, 4), ("invert", 0.2, None)]]])
- def test_smoke(self, policy):
+ def test_smoke(self, policy, device, dtype):
aug = AutoAugment(policy)
- in_tensor = torch.rand(10, 3, 50, 50, requires_grad=True)
+ in_tensor = torch.rand(10, 3, 50, 50, device=device, dtype=dtype, requires_grad=True)
aug(in_tensor)
aug.is_intensity_only()
- def test_transform_mat(self):
- aug = AutoAugment([[("shear_x", 0.9, 4), ("invert", 0.2, None)]])
- in_tensor = torch.rand(10, 3, 50, 50, requires_grad=True)
+ def test_transform_mat(self, device, dtype):
+ aug = AutoAugment([[("shear_x", 0.9, 4), ("invert", 0.2, None)]], transformation_matrix_mode="silence")
+ in_tensor = torch.rand(10, 3, 50, 50, device=device, dtype=dtype, requires_grad=True)
aug(in_tensor)
- aug.get_transformation_matrix(in_tensor, params=aug._params)
+ trans = aug.get_transformation_matrix(in_tensor, params=aug._params)
+ assert_close(trans, aug.transform_matrix)
- def test_reproduce(self):
+ def test_reproduce(self, device, dtype):
aug = AutoAugment()
- in_tensor = torch.rand(10, 3, 50, 50, requires_grad=True)
+ in_tensor = torch.rand(10, 3, 50, 50, device=device, dtype=dtype, requires_grad=True)
out_tensor = aug(in_tensor)
out_tensor_2 = aug(in_tensor, params=aug._params)
assert_close(out_tensor, out_tensor_2)
@@ -108,9 +109,16 @@ class TestRandAugment:
in_tensor = torch.rand(10, 3, 50, 50, requires_grad=True)
aug(in_tensor)
- def test_reproduce(self):
+ def test_transform_mat(self, device, dtype):
aug = RandAugment(n=3, m=15)
- in_tensor = torch.rand(10, 3, 50, 50, requires_grad=True)
+ in_tensor = torch.rand(10, 3, 50, 50, device=device, dtype=dtype, requires_grad=True)
+ aug(in_tensor)
+ trans = aug.get_transformation_matrix(in_tensor, params=aug._params)
+ assert_close(trans, aug.transform_matrix)
+
+ def test_reproduce(self, device, dtype):
+ aug = RandAugment(n=3, m=15)
+ in_tensor = torch.rand(10, 3, 50, 50, device=device, dtype=dtype, requires_grad=True)
out_tensor = aug(in_tensor)
out_tensor_2 = aug(in_tensor, params=aug._params)
assert_close(out_tensor, out_tensor_2)
@@ -126,9 +134,17 @@ class TestTrivialAugment:
in_tensor = torch.rand(10, 3, 50, 50, requires_grad=True)
aug(in_tensor)
- def test_reproduce(self):
+ def test_transform_mat(self, device, dtype):
aug = TrivialAugment()
- in_tensor = torch.rand(10, 3, 50, 50, requires_grad=True)
+ in_tensor = torch.rand(10, 3, 50, 50, device=device, dtype=dtype, requires_grad=True)
+ aug(in_tensor)
+ aug(in_tensor)
+ trans = aug.get_transformation_matrix(in_tensor, params=aug._params)
+ assert_close(trans, aug.transform_matrix)
+
+ def test_reproduce(self, device, dtype):
+ aug = TrivialAugment()
+ in_tensor = torch.rand(10, 3, 50, 50, device=device, dtype=dtype, requires_grad=True)
out_tensor = aug(in_tensor)
out_tensor_2 = aug(in_tensor, params=aug._params)
assert_close(out_tensor, out_tensor_2)