Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

Fix stale transform matrices in repeated auto augmentation policies (#4171)

Dmytro Mishkin1ffceef30323
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 82de68a58..01c238f96 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -129,6 +129,14 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
### Bug fixes
+* Reset an automatic augmentation policy's cached transformation matrix before applying it again, both for a
+ sub-policy inside `TrivialAugment`, `RandAugment` and `AutoAugment` and for those policies nested inside
+ `AugmentationSequential`. Consecutive calls that selected the same geometric policy could transform the input with
+ the latest parameters while exposing the previous call's matrix through `transform_matrix`, the sub-policy
+ accumulated one matrix per call for the lifetime of the module, and a nested policy never recorded its parameters
+ or matrix at all. `transform_matrix` on a policy that has not run yet now returns `None` instead of raising
+ `AttributeError` (#4171).
+
* `MultiResolutionDetector.detect` apportions `num_features` across pyramid levels with largest-remainder
(Hamilton) apportionment instead of flooring each level's fractional share independently (#4101). The floors
used to discard every fractional part, so a small `num_features` could round the whole apportionment down: with
diff --git a/kornia/augmentation/auto/base.py b/kornia/augmentation/auto/base.py
index 3487dac10..0330caae2 100644
--- a/kornia/augmentation/auto/base.py
+++ b/kornia/augmentation/auto/base.py
@@ -26,6 +26,7 @@ from kornia.augmentation.container.base import ImageSequentialBase, TransformMat
from kornia.augmentation.container.ops import InputSequentialOps
from kornia.augmentation.container.params import ParamItem
from kornia.core.ops import eye_like
+from kornia.core.utils import is_exporting
NUMBER = Union[float, int]
OP_CONFIG = Tuple[str, NUMBER, Optional[NUMBER]]
@@ -38,6 +39,9 @@ class PolicyAugmentBase(ImageSequentialBase, TransformMatrixMinIn):
def __init__(self, policy: List[SUBPOLICY_CONFIG], transformation_matrix_mode: str = "silence") -> None:
policies = self.compose_policy(policy)
super().__init__(*policies)
+ # ``TransformMatrixMinIn`` sits after ``nn.Module`` in the MRO, so its ``__init__`` never runs.
+ self._transform_matrix: Optional[torch.Tensor] = None
+ self._transform_matrices: List[Optional[torch.Tensor]] = []
self._parse_transformation_matrix_mode(transformation_matrix_mode)
self._valid_ops_for_transform_computation: Tuple[Any, ...] = (PolicySequential,)
@@ -140,6 +144,9 @@ class PolicyAugmentBase(ImageSequentialBase, TransformMatrixMinIn):
) -> torch.Tensor:
"""Apply a prepared parameter list to the input tensor.
+ Resets the cached parameters and transformation matrix first, so a policy nested inside another
+ container ends up in the same state as after :meth:`forward` with these ``params``.
+
Args:
input: Input tensor.
params: Parameters produced by :meth:`forward_parameters`.
@@ -148,9 +155,13 @@ class PolicyAugmentBase(ImageSequentialBase, TransformMatrixMinIn):
Returns:
Transformed tensor.
"""
+ self.clear_state()
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)
+ if not is_exporting():
+ self._params = params
return input
def forward(
@@ -167,17 +178,8 @@ class PolicyAugmentBase(ImageSequentialBase, TransformMatrixMinIn):
Returns:
Augmented tensor.
"""
- self.clear_state()
-
if params is None:
- inp = input
- _, out_shape = self.autofill_dim(inp, dim_range=(2, 4))
+ _, out_shape = self.autofill_dim(input, dim_range=(2, 4))
params = self.forward_parameters(out_shape)
- 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)
-
- self._params = params
- return input
+ return self.transform_inputs(input, params=params, extra_args=extra_args)
diff --git a/kornia/augmentation/auto/operations/policy.py b/kornia/augmentation/auto/operations/policy.py
index bc1bc9134..b95cd8f2c 100644
--- a/kornia/augmentation/auto/operations/policy.py
+++ b/kornia/augmentation/auto/operations/policy.py
@@ -27,6 +27,7 @@ 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.ops import eye_like
+from kornia.core.utils import is_exporting
class PolicySequential(TransformMatrixMinIn, ImageSequentialBase):
@@ -163,6 +164,10 @@ class PolicySequential(TransformMatrixMinIn, ImageSequentialBase):
) -> torch.Tensor:
"""Apply all operations using a prepared parameter list.
+ Leaves the policy in the same state as :meth:`forward` with these ``params``: the cached
+ transformation matrix is rebuilt from this call and ``_params`` records ``params``. This is the
+ entry point used when the policy is nested inside another container.
+
Args:
input: Input tensor.
params: Parameters for each operation in this policy.
@@ -171,8 +176,11 @@ class PolicySequential(TransformMatrixMinIn, ImageSequentialBase):
Returns:
Transformed tensor.
"""
+ self._reset_transform_matrix_state()
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)
+ if not is_exporting():
+ self._params = params
return input
diff --git a/tests/augmentation/test_auto_operation.py b/tests/augmentation/test_auto_operation.py
index 22f68c14d..bc4436883 100644
--- a/tests/augmentation/test_auto_operation.py
+++ b/tests/augmentation/test_auto_operation.py
@@ -15,6 +15,7 @@
# limitations under the License.
#
+import copy
import inspect
from typing import List
@@ -107,6 +108,14 @@ class TestRandAugment(BaseTester):
trans = aug.get_transformation_matrix(in_tensor, params=aug._params)
self.assert_close(trans, aug.transform_matrix)
+ def test_transform_mat_repeated_policy(self, device, dtype):
+ aug = RandAugment(n=2, m=10, policy=[[("translate_y", -0.5, 0.5)], [("translate_x", -0.5, 0.5)]])
+ in_tensor = torch.ones(2, 3, 10, 10, device=device, dtype=dtype)
+ for _ in range(3):
+ aug(in_tensor)
+ expected = aug.get_transformation_matrix(in_tensor, params=aug._params, recompute=True)
+ self.assert_close(aug.transform_matrix, expected)
+
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)
@@ -133,6 +142,41 @@ class TestTrivialAugment(BaseTester):
trans = aug.get_transformation_matrix(in_tensor, params=aug._params)
self.assert_close(trans, aug.transform_matrix)
+ def test_transform_mat_repeated_policy(self, device, dtype):
+ aug = TrivialAugment(policy=[[("translate_y", -0.5, 0.5)]])
+ in_tensor = torch.ones(2, 3, 10, 10, device=device, dtype=dtype)
+ params_1 = aug.forward_parameters(in_tensor.shape)
+ params_2 = copy.deepcopy(params_1)
+ params_2[0].data[0].data["translate_y"] += 1.0
+ aug(in_tensor, params=params_1)
+ aug(in_tensor, params=params_2)
+ stale = aug.get_transformation_matrix(in_tensor, params=params_1, recompute=True)
+ expected = aug.get_transformation_matrix(in_tensor, params=params_2, recompute=True)
+ assert not torch.allclose(aug.transform_matrix, stale)
+ self.assert_close(aug.transform_matrix, expected)
+
+ def test_transform_mat_fresh_instance(self):
+ aug = TrivialAugment(policy=[[("translate_y", -0.5, 0.5)]])
+ assert aug.transform_matrix is None
+
+ def test_transform_mat_nested_sequential(self, device, dtype):
+ aug = TrivialAugment(policy=[[("translate_y", -0.5, 0.5)]])
+ seq = AugmentationSequential(aug, data_keys=["input"])
+ in_tensor = torch.ones(2, 3, 10, 10, device=device, dtype=dtype)
+ seq(in_tensor)
+ seq(in_tensor)
+ nested_params = seq._params[0].data
+ expected = aug.get_transformation_matrix(in_tensor, params=nested_params, recompute=True)
+ self.assert_close(aug.transform_matrix, expected)
+ assert aug._params is nested_params
+
+ def test_subpolicy_params_after_forward(self, device, dtype):
+ aug = TrivialAugment(policy=[[("translate_y", -0.5, 0.5)]])
+ subpolicy = next(iter(aug.children()))
+ in_tensor = torch.ones(2, 3, 10, 10, device=device, dtype=dtype)
+ aug(in_tensor)
+ assert subpolicy._params is aug._params[0].data
+
def test_reproduce(self, device, dtype):
aug = TrivialAugment()
in_tensor = torch.rand(10, 3, 50, 50, device=device, dtype=dtype, requires_grad=True)