🐍 Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
fix(augmentation): make auto policies picklable (#5651)
Rızgar Ozanbbf2175497ec
diff --git a/changelog.d/5651.fixed.md b/changelog.d/5651.fixed.mdnew file mode 100644index 000000000..ffbfaf991--- /dev/null+++ b/changelog.d/5651.fixed.md@@ -0,0 +1 @@+`RandAugment`, `AutoAugment` and `TrivialAugment` can now be pickled and saved with `torch.save`. The default magnitude mapping was a local function, so every policy failed to pickle. A restored policy replays the same draw under the same seed.diff --git a/docs/source/augmentation.base.rst b/docs/source/augmentation.base.rstindex 5e2f5939b..5edee0e78 100644--- a/docs/source/augmentation.base.rst+++ b/docs/source/augmentation.base.rst@@ -227,7 +227,7 @@ See :class:`AugmentationBase2D` for where parameters are sampled and what ``paraSerialization^^^^^^^^^^^^^- Several constructors that accept ``nn.Parameter`` ranges propagate gradients to them.-- The default ``kornia.augmentation.auto`` policies cannot be pickled- (`#4469 <https://github.com/kornia/kornia/issues/4469>`_).+- A ``kornia.augmentation.auto`` policy pickles when every operation wrapper in it does, and a wrapper does when+ its magnitude mapping is picklable; the built-in mappings are.- :class:`AugmentationBase2D` covers the range buffers in ``state_dict()``, and:class:`RigidAffineAugmentationBase2D` what a lazily built matrix keeps.diff --git a/docs/source/get-started/conventions.rst b/docs/source/get-started/conventions.rstindex a6da55c9b..1883a91ac 100644--- a/docs/source/get-started/conventions.rst+++ b/docs/source/get-started/conventions.rst@@ -507,11 +507,11 @@ Serializing an augmentation``_param_generator.*`` buffers that loading does not feed back into thesamplers (`#4428 <https://github.com/kornia/kornia/issues/4428>`_).- ``pickle`` and ``copy.deepcopy`` keep the configuration and the recorded- ``_params``, which replay on the same input. The default- ``kornia.augmentation.auto`` policies cannot be pickled (a policy can be- pickled only when every operation wrapper in it can), though they deep-copy- (`#4469 <https://github.com/kornia/kornia/issues/4469>`_). What lazily- computed matrices retain is described in :doc:`/augmentation.base`.+ ``_params``, which replay on the same input. This includes the+ ``kornia.augmentation.auto`` policies: a policy pickles when every operation+ wrapper in it does, and a wrapper does when its magnitude mapping is+ picklable (the built-in mappings are). What lazily computed matrices retain+ is described in :doc:`/augmentation.base`.Morphology----------diff --git a/kornia/augmentation/auto/operations/base.py b/kornia/augmentation/auto/operations/base.pyindex e009d2628..4b3c0d77c 100644--- a/kornia/augmentation/auto/operations/base.py+++ b/kornia/augmentation/auto/operations/base.py@@ -25,6 +25,23 @@ from kornia.augmentation.base import _AugmentationBaseT = TypeVar("T", bound="OperationBase")+def _identity(x: torch.Tensor) -> torch.Tensor:+ return x+++class _RandomSign:+ """Multiply the magnitude mapping by a random sign per row; a class rather than a closure, so wrappers pickle."""++ def __init__(self, fn: Callable[[torch.Tensor], torch.Tensor]) -> None:+ self.fn = fn++ def __call__(self, x: torch.Tensor) -> torch.Tensor:+ # a sign, not a mask: multiplying by the bool would zero half the+ # magnitudes instead of negating them+ sign = torch.where(torch.rand((x.shape[0],), device=x.device) > 0.5, 1.0, -1.0)+ return self.fn(x) * sign.to(x.dtype)++class OperationBase(nn.Module):"""Base class of differentiable augmentation operations.@@ -52,9 +69,8 @@ class OperationBase(nn.Module):- a symmetric magnitude applies the magnitude mapping first and then a random sign per row, so a mappingthat quantizes to zero stays zero (``Posterize`` maps ``0.5`` to ``0`` bits with ``magnitude_range=(0, 8)``).- the concrete classes in ``kornia.augmentation.auto.operations.ops`` wrap public 2D augmentations and- inherit their input, dtype, RNG and replay contracts. A wrapper pickles only with a named magnitude- mapping and ``symmetric_megnitude=False`` (with default arguments, only ``Posterize``); otherwise its- local closure blocks pickling (`#4469 <https://github.com/kornia/kornia/issues/4469>`_).+ inherit their input, dtype, RNG and replay contracts. A wrapper pickles, with either sign setting, when+ its magnitude mapping is picklable."""@@ -93,23 +109,11 @@ class OperationBase(nn.Module):def _init_magnitude_fn(self, magnitude_fn: Optional[Callable[[torch.Tensor], torch.Tensor]]) -> Callable[[torch.Tensor], torch.Tensor]:- def _identity(x: torch.Tensor) -> torch.Tensor:- return x-- def _random_flip(fn: Callable[[torch.Tensor], torch.Tensor]) -> Callable[[torch.Tensor], torch.Tensor]:- def f(x: torch.Tensor) -> torch.Tensor:- # a sign, not a mask: multiplying by the bool would zero half the- # magnitudes instead of negating them- sign = torch.where(torch.rand((x.shape[0],), device=x.device) > 0.5, 1.0, -1.0)- return fn(x) * sign.to(x.dtype)-- return f-if magnitude_fn is None:magnitude_fn = _identityif self.symmetric_megnitude:- return _random_flip(magnitude_fn)+ return _RandomSign(magnitude_fn)return magnitude_fndiff --git a/tests/augmentation/test_conventions_6d_serialization.py b/tests/augmentation/test_conventions_6d_serialization.pyindex bf34ecade..8ee239ab1 100644--- a/tests/augmentation/test_conventions_6d_serialization.py+++ b/tests/augmentation/test_conventions_6d_serialization.py@@ -111,8 +111,7 @@ class TestConventionMix3DSerialization(BaseTester):ids=["autoaugment-posterize", "randaugment-posterize", "trivialaugment-posterize", "autoaugment-empty"],)def test_convention_a_closure_free_policy_can_be_pickled(self, name, policy):- # A policy pickles when every wrapper in it does: Posterize has a named mapping and no sign flip, and an- # empty sub-policy has no wrapper at all.+ # A policy pickles when every wrapper in it does; an empty sub-policy has no wrapper at all.kwargs = {"n": 1, "m": 15} if name == "RandAugment" else {}augmentation = getattr(A, name)(policy=policy, **kwargs)image = torch.rand(2, 3, 4, 4)diff --git a/tests/augmentation/test_conventions_auto.py b/tests/augmentation/test_conventions_auto.pyindex 177e1ba81..b44c88591 100644--- a/tests/augmentation/test_conventions_auto.py+++ b/tests/augmentation/test_conventions_auto.py@@ -499,33 +499,39 @@ class TestAutoAugmentConventions(BaseTester):self.assert_close(mapped.abs(), torch.full_like(mapped, 0.29 * 180))@pytest.mark.device_agnostic- def test_wart_operation_wrappers_cannot_be_pickled_4469(self):+ def test_convention_operation_wrappers_pickle_and_replay_4469(self):+ import ioimport pickle- # Python 3.14 raises PicklingError for a local object where earlier versions raise AttributeError.- local_object_error = (AttributeError, pickle.PicklingError)- failed = set()+ x = torch.rand(2, 3, 16, 16)+ # every wrapper restores from a pickle and replays the same draw under the same seedfor name in ops.__all__:operation = getattr(ops, name)()- pickle.loads(pickle.dumps(operation.op)) # noqa: S301 - the wrapped augmentation always pickles- try:- pickle.loads(pickle.dumps(operation)) # noqa: S301- except local_object_error:- failed.add(name)- # With default arguments only Posterize avoids a local closure: it passes a named mapping and no sign flip.- assert failed == set(ops.__all__) - {"Posterize"}- # It is the configuration, not the class: ShearX / ShearY pass a named mapping too, and pickle without- # the sign flip, while the sign flip makes Posterize unpicklable.- for operation in (ops.ShearX(symmetric_megnitude=False), ops.ShearY(symmetric_megnitude=False)):+ restored = pickle.loads(pickle.dumps(operation)) # noqa: S301+ torch.manual_seed(0)+ expected = operation(x)+ torch.manual_seed(0)+ assert torch.equal(restored(x), expected), name+ for operation in (ops.ShearX(symmetric_megnitude=True), ops.Posterize(symmetric_megnitude=True)):pickle.loads(pickle.dumps(operation)) # noqa: S301- with pytest.raises(local_object_error):- pickle.dumps(ops.Posterize(symmetric_megnitude=True))- with pytest.raises(local_object_error):- pickle.dumps(ops.Rotate(symmetric_megnitude=False)) # no named mapping: the identity closure- # So the default policies, which hold such wrappers, do not pickle either.for policy in (AutoAugment(), RandAugment(n=2, m=15), TrivialAugment()):- with pytest.raises(local_object_error):- pickle.dumps(policy)+ restored = pickle.loads(pickle.dumps(policy)) # noqa: S301+ torch.manual_seed(0)+ expected = policy(x)+ torch.manual_seed(0)+ assert torch.equal(restored(x), expected)+ # torch.save/torch.load of a policy that has already run a forward pass; the buffer is written in-process here+ for policy in (AutoAugment(), RandAugment(n=2, m=15), TrivialAugment()):+ first = policy(x)+ buffer = io.BytesIO()+ torch.save(policy, buffer)+ buffer.seek(0)+ restored = torch.load(buffer, weights_only=False)+ assert torch.equal(restored(x, params=restored._params), first)+ torch.manual_seed(0)+ expected = policy(x)+ torch.manual_seed(0)+ assert torch.equal(restored(x), expected)@pytest.mark.device_agnosticdef test_convention_rigid_matrix_mode_accepts_intensity_operations(self):