Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

fix(augmentation): make Gaussian illumination serializable (#4457)

Zhenhuan Wang1ffd11fd4d6f
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 9d88e4b93..35c58deb9 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -407,6 +407,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
### Bug fixes
+* Made uncompiled `RandomGaussianIllumination` instances serializable with `pickle` and `torch.save`,
+ preserving parameter replay and the `compile()` execution path after restoring the module. (#4457)
* The `Args` blocks of `ColorJitter`, `RandomBrightness` and `RandomGaussianBlur` no longer document a
`silence_instantiation_warning` argument that none of them accepts, and `ColorJitter` now documents its
`order` argument: a fixed (sub)set of brightness/contrast/saturation/hue indices that makes the transform
diff --git a/docs/source/augmentation.base.rst b/docs/source/augmentation.base.rst
index 2bbdbb248..51d4a59b3 100644
--- a/docs/source/augmentation.base.rst
+++ b/docs/source/augmentation.base.rst
@@ -244,7 +244,7 @@ Several constructors accept ``nn.Parameter`` ranges and can propagate gradients
are not necessarily connected to cached samplers after ``load_state_dict``; reconstruct those configurations
to change their sampling ranges (`#4428 <https://github.com/kornia/kornia/issues/4428>`_).
-Pickle support is configuration-dependent (`#4435 <https://github.com/kornia/kornia/issues/4435>`_), and
-lazy matrix state can retain the last input batch in a pickle or deepcopy
+The ``kornia.augmentation.auto`` policies cannot be pickled (`#4469 <https://github.com/kornia/kornia/issues/4469>`_),
+and lazy matrix state can retain the last input batch in a pickle or deepcopy
(`#4482 <https://github.com/kornia/kornia/issues/4482>`_).
See :doc:`/get-started/conventions` for replay and serialization details.
diff --git a/docs/source/get-started/conventions.rst b/docs/source/get-started/conventions.rst
index ef7386a88..c9e480f26 100644
--- a/docs/source/get-started/conventions.rst
+++ b/docs/source/get-started/conventions.rst
@@ -346,9 +346,9 @@ Serializing an augmentation
reflect the loaded range. Reconstruct the augmentation to change what it
samples (`#4428 <https://github.com/kornia/kornia/issues/4428>`_).
- Pickle and deepcopy can retain recorded parameters and transform state,
- but support is configuration-dependent. ``RandomGaussianIllumination``
- cannot currently be pickled
- (`#4435 <https://github.com/kornia/kornia/issues/4435>`_). Lazy matrix state
+ but support is configuration-dependent. The ``kornia.augmentation.auto``
+ policies cannot currently be pickled
+ (`#4469 <https://github.com/kornia/kornia/issues/4469>`_). Lazy matrix state
can retain the last input batch, increasing serialized size until the
matrix is read (`#4482 <https://github.com/kornia/kornia/issues/4482>`_).
A normal forward draws fresh parameters; replay requires passing the
diff --git a/kornia/augmentation/_2d/base.py b/kornia/augmentation/_2d/base.py
index 7e6f2bb85..a74c78e62 100644
--- a/kornia/augmentation/_2d/base.py
+++ b/kornia/augmentation/_2d/base.py
@@ -78,8 +78,7 @@ class AugmentationBase2D(_AugmentationBase):
since it is drawn into ``_params``, except for :class:`RandomDissolving`, which samples VAE latents
during application; that draw is not stored and requires controlling the global seed too.
- range configuration and serialization behavior vary by generator. Some range buffers are inert after
- ``load_state_dict`` (tracked in `#4428 <https://github.com/kornia/kornia/issues/4428>`_), some
- augmentations are not picklable (`#4435 <https://github.com/kornia/kornia/issues/4435>`_), and saved
+ ``load_state_dict`` (tracked in `#4428 <https://github.com/kornia/kornia/issues/4428>`_), and saved
state can retain data from the last call (`#4482 <https://github.com/kornia/kornia/issues/4482>`_).
- an empty batch is an empty output on the classes that accept one, but it is not a package-wide
guarantee: a minority of the classes raise on ``B = 0``, in several unrelated exception families.
diff --git a/kornia/augmentation/_2d/intensity/gaussian_illumination.py b/kornia/augmentation/_2d/intensity/gaussian_illumination.py
index 663a7e85f..1b8a9832b 100644
--- a/kornia/augmentation/_2d/intensity/gaussian_illumination.py
+++ b/kornia/augmentation/_2d/intensity/gaussian_illumination.py
@@ -15,6 +15,8 @@
# limitations under the License.
#
+from __future__ import annotations
+
from typing import Any, Dict, Optional, Tuple, Union
import torch
@@ -24,6 +26,22 @@ from kornia.augmentation.random_generator._2d import GaussianIlluminationGenerat
from kornia.core.check import KORNIA_CHECK
+def _apply_gaussian_illumination(
+ input: torch.Tensor,
+ params: Dict[str, torch.Tensor],
+ flags: Dict[str, Any],
+ transform: Optional[torch.Tensor] = None,
+) -> torch.Tensor:
+ """Apply a sampled illumination pattern through a picklable, compilable callable."""
+ # The gradient comes from the generator on CPU.
+ # We must explicitly move it to the input's device before adding.
+ gradient = params["gradient"].to(input.device, input.dtype)
+
+ # Out-of-place add: in-place would mutate the caller's tensor and corrupt
+ # the non-transformed branch, which shares the same input.
+ return input.add(gradient).clamp_(0, 1)
+
+
class RandomGaussianIllumination(IntensityAugmentationBase2D):
r"""Applies random 2D Gaussian illumination patterns to a batch of images.
@@ -160,21 +178,7 @@ class RandomGaussianIllumination(IntensityAugmentationBase2D):
# Generator of random parameters and masks.
self._param_generator = GaussianIlluminationGenerator(gain, center, sigma, sign)
- def _apply_transform(
- input: torch.Tensor,
- params: Dict[str, torch.Tensor],
- flags: Dict[str, Any],
- transform: Optional[torch.Tensor] = None,
- ) -> torch.Tensor:
- # The gradient comes from the generator on CPU.
- # We must explicitly move it to the input's device before adding.
- gradient = params["gradient"].to(input.device, input.dtype)
-
- # Out-of-place add: in-place would mutate the caller's tensor and corrupt
- # the non-transformed branch, which shares the same input.
- return input.add(gradient).clamp_(0, 1)
-
- self._fn = _apply_transform
+ self._fn = _apply_gaussian_illumination
def apply_transform(
self,
@@ -195,7 +199,7 @@ class RandomGaussianIllumination(IntensityAugmentationBase2D):
mode: Optional[str] = None,
options: Optional[Dict[Any, Any]] = None,
disable: bool = False,
- ) -> "RandomGaussianIllumination":
+ ) -> RandomGaussianIllumination:
self._fn = torch.compile(
self._fn,
fullgraph=fullgraph,
diff --git a/tests/augmentation/test_augmentation.py b/tests/augmentation/test_augmentation.py
index 914eafa98..c42e34e84 100644
--- a/tests/augmentation/test_augmentation.py
+++ b/tests/augmentation/test_augmentation.py
@@ -15,7 +15,10 @@
# limitations under the License.
#
+import copy
+import io
import os
+import pickle
import sys
from typing import Any, Dict, Optional, Tuple, Type
from unittest.mock import patch
@@ -4255,6 +4258,92 @@ class TestRandomSaltAndPepperNoise(BaseTester):
class TestRandomGaussianIllumination(BaseTester):
+ def _roundtrip(self, aug, serializer):
+ if serializer == "pickle":
+ return pickle.loads(pickle.dumps(aug)) # noqa: S301
+ if serializer == "torch":
+ buffer = io.BytesIO()
+ torch.save(aug, buffer)
+ buffer.seek(0)
+ return torch.load(buffer, weights_only=False)
+ return copy.deepcopy(aug)
+
+ @pytest.mark.parametrize("serializer", ["pickle", "torch", "deepcopy"])
+ @pytest.mark.parametrize("after_forward", [False, True])
+ @pytest.mark.parametrize("shape,keepdim", [((2, 3, 6, 8), False), ((1, 6, 8), True)])
+ def test_serialization_roundtrip(self, device, dtype, serializer, after_forward, shape, keepdim):
+ input = torch.full(shape, 0.5, device=device, dtype=dtype)
+ original = input.clone()
+ aug = RandomGaussianIllumination(gain=0.25, sign=1.0, p=1.0, same_on_batch=True, keepdim=keepdim)
+ if after_forward:
+ aug(input)
+
+ restored = self._roundtrip(aug, serializer)
+ assert isinstance(restored, RandomGaussianIllumination)
+ assert repr(restored) == repr(aug)
+ assert restored.keepdim == aug.keepdim
+ assert restored._params.keys() == aug._params.keys()
+ for key in aug._params:
+ self.assert_close(restored._params[key], aug._params[key])
+
+ # Replay the restored state, rather than passing the original module's saved draw.
+ batch_shape = torch.Size(shape if len(shape) == 4 else (1, *shape))
+ params = copy.deepcopy(restored._params) if after_forward else aug.forward_parameters(batch_shape)
+ expected = aug(input, params=params)
+ actual = restored(input, params=params)
+ self.assert_close(actual, expected)
+ assert actual.shape == input.shape
+ assert actual.device == device
+ assert actual.dtype == dtype
+ assert not torch.equal(actual, input)
+ self.assert_close(input, original, rtol=0, atol=0)
+
+ @pytest.mark.parametrize("batch_prob", [[True, True], [False, True], [False, False]])
+ def test_input_preserved(self, device, dtype, batch_prob):
+ input = torch.tensor([0.1, 0.4, 0.7, 0.9], device=device, dtype=dtype).reshape(1, 1, 2, 2).repeat(2, 1, 1, 1)
+ original = input.clone()
+ aug = RandomGaussianIllumination(p=0.5)
+ params = aug.forward_parameters(input.shape)
+ # Deliberately keep generator output on CPU, including for accelerator inputs.
+ gradient = torch.tensor([-0.2, 0.2, 0.5, -0.3]).reshape(1, 1, 2, 2).repeat(2, 1, 1, 1)
+ params["gradient"] = gradient
+ params["batch_prob"] = torch.tensor(batch_prob)
+ expected = torch.where(
+ params["batch_prob"].to(device).view(2, 1, 1, 1),
+ (original + gradient.to(device=device, dtype=dtype)).clamp(0, 1),
+ original,
+ )
+ actual = aug(input, params=params)
+ self.assert_close(actual, expected)
+ self.assert_close(input, original, rtol=0, atol=0)
+
+ @pytest.mark.parametrize("serializer", ["pickle", "torch"])
+ def test_compile_after_serialization(self, device, dtype, serializer, torch_optimizer):
+ compiled_graphs = []
+ executions = []
+
+ def backend(graph_module, _example_inputs):
+ compiled_graphs.append(graph_module)
+
+ def execute(*args):
+ executions.append(True)
+ return graph_module.forward(*args)
+
+ return execute
+
+ input = torch.full((2, 3, 6, 8), 0.5, device=device, dtype=dtype)
+ original = input.clone()
+ aug = RandomGaussianIllumination(gain=0.25, sign=1.0, p=1.0)
+ expected = aug(input)
+ restored = self._roundtrip(aug, serializer)
+ params = copy.deepcopy(restored._params)
+ assert restored.compile(fullgraph=True, backend=backend) is restored
+ for _ in range(2):
+ self.assert_close(restored(input, params=params), expected)
+ assert len(compiled_graphs) == 1
+ assert len(executions) == 2
+ self.assert_close(input, original, rtol=0, atol=0)
+
def _get_expected(self, device, dtype):
return torch.tensor(
[
@@ -4335,9 +4424,11 @@ class TestRandomGaussianIllumination(BaseTester):
def test_dynamo(self, device, dtype, torch_optimizer):
input_tensor = torch.ones(1, 3, 3, 3, device=device, dtype=dtype) * 0.5
aug = RandomGaussianIllumination(gain=0.5, p=1.0)
+ params = aug.forward_parameters(input_tensor.shape)
+ expected = aug(input_tensor, params=params)
aug = aug.compile(fullgraph=True)
- actual = aug(input_tensor)
- assert actual.shape == input_tensor.shape
+ actual = aug(input_tensor, params=params)
+ self.assert_close(actual, expected)
class TestRandomLinearIllumination(BaseTester):