π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
fix(augmentation): keep own-compile intensity augmentations picklable (#4849)
RitiGrover9feecbf281f6
diff --git a/changelog.d/4849.fixed.md b/changelog.d/4849.fixed.mdnew file mode 100644index 000000000..00c292b82--- /dev/null+++ b/changelog.d/4849.fixed.md@@ -0,0 +1,2 @@+`ColorJitter`, `RandomGaussianBlur` and `RandomGaussianIllumination` now pickle and pass through `torch.save`+after their own `compile()`. Unpickling compiles the restored module again with the same arguments. (#4849)diff --git a/kornia/augmentation/_2d/intensity/base.py b/kornia/augmentation/_2d/intensity/base.pyindex efd967921..c832ff142 100644--- a/kornia/augmentation/_2d/intensity/base.py+++ b/kornia/augmentation/_2d/intensity/base.py@@ -15,7 +15,7 @@# limitations under the License.#-from typing import Any, Dict, Optional+from typing import Any, Dict, Optional, Sequencefrom torch import Tensor@@ -24,6 +24,34 @@ from kornia.geometry.boxes import Boxesfrom kornia.geometry.keypoints import Keypoints+class _PicklableCompileMixin:+ """Keep a module picklable after its own ``compile()`` replaced callables with ``torch.compile``d ones.++ ``compile()`` calls :meth:`_record_compile` before compiling. Pickling (and ``copy.deepcopy``) then stores+ the uncompiled callables, which pickle, and unpickling compiles them again with the same arguments.+ """++ def _record_compile(self, names: Sequence[str], compile_kwargs: Dict[str, Any]) -> None:+ # Keep the first, uncompiled callables if compile() is called more than once.+ if self.__dict__.get("_uncompiled_fns") is None:+ self._uncompiled_fns = {name: getattr(self, name) for name in names}+ self._compile_kwargs = compile_kwargs++ def __getstate__(self) -> Dict[str, Any]:+ state = super().__getstate__() # type: ignore[misc]+ uncompiled = state.get("_uncompiled_fns")+ if uncompiled is not None:+ state.update(uncompiled)+ return state++ def __setstate__(self, state: Dict[str, Any]) -> None:+ super().__setstate__(state) # type: ignore[misc]+ compile_kwargs = state.get("_compile_kwargs")+ if compile_kwargs is not None:+ self._uncompiled_fns = None+ self.compile(**compile_kwargs) # type: ignore[attr-defined]++class IntensityAugmentationBase2D(RigidAffineAugmentationBase2D):r"""IntensityAugmentationBase2D base class for customized intensity augmentation implementations.diff --git a/kornia/augmentation/_2d/intensity/color_jitter.py b/kornia/augmentation/_2d/intensity/color_jitter.pyindex 876548280..0790130b6 100644--- a/kornia/augmentation/_2d/intensity/color_jitter.py+++ b/kornia/augmentation/_2d/intensity/color_jitter.py@@ -21,7 +21,7 @@ from typing import Any, Dict, List, Optional, Tuple, Unionimport torchfrom kornia.augmentation import random_generator as rg-from kornia.augmentation._2d.intensity.base import IntensityAugmentationBase2D+from kornia.augmentation._2d.intensity.base import IntensityAugmentationBase2D, _PicklableCompileMixinfrom kornia.augmentation._2d.intensity.color_jiggle import (_adjust_hue,_apply_order_cond,@@ -59,7 +59,7 @@ def _apply_cond(order: Tuple[int, ...], input: torch.Tensor, factors: Tuple[torcreturn _apply_order_cond(_BRANCHES, _NEUTRAL, order, input, factors)-class ColorJitter(IntensityAugmentationBase2D):+class ColorJitter(_PicklableCompileMixin, IntensityAugmentationBase2D):r"""Apply a random transformation to the brightness, contrast, saturation and hue of a torch.Tensor image.The four steps are torchvision's formulas -- brightness multiplies the image by the factor, contrast blends it@@ -105,10 +105,6 @@ class ColorJitter(IntensityAugmentationBase2D):out-of-range input. Tracked in`#4785 <https://github.com/kornia/kornia/issues/4785>`_.- .. warning::- After this class's own ``.compile()`` the module no longer pickles or passes through ``torch.save``.- Tracked in `#4807 <https://github.com/kornia/kornia/issues/4807>`_.-.. warning::Because the brightness, contrast and saturation steps clamp, an all-negative input can come back as anall-zero image, depending on the draw and the order. Tracked in@@ -213,6 +209,17 @@ class ColorJitter(IntensityAugmentationBase2D):options: Optional[Dict[Any, Any]] = None,disable: bool = False,) -> "ColorJitter":+ self._record_compile(+ ["_cond_fn", "_brightness_fn", "_contrast_fn", "_saturation_fn", "_hue_fn"],+ {+ "fullgraph": fullgraph,+ "dynamic": dynamic,+ "backend": backend,+ "mode": mode,+ "options": options,+ "disable": disable,+ },+ )# A fixed order on an RGB input runs every step through the torch.cond dispatcher, which is compiled# as one graph; the four helpers serve the random order and non-RGB inputs.if self._cond_fn is not None:diff --git a/kornia/augmentation/_2d/intensity/gaussian_blur.py b/kornia/augmentation/_2d/intensity/gaussian_blur.pyindex 61e0b1815..4fc23913f 100644--- a/kornia/augmentation/_2d/intensity/gaussian_blur.py+++ b/kornia/augmentation/_2d/intensity/gaussian_blur.py@@ -21,14 +21,14 @@ import torchfrom torch import Tensorfrom kornia.augmentation import random_generator as rg-from kornia.augmentation._2d.intensity.base import IntensityAugmentationBase2D+from kornia.augmentation._2d.intensity.base import IntensityAugmentationBase2D, _PicklableCompileMixinfrom kornia.augmentation.utils import _check_filter_min_sizefrom kornia.constants import BorderTypefrom kornia.filters import gaussian_blur2dfrom kornia.filters.kernels import _check_kernel_size, _unpack_2d_ks-class RandomGaussianBlur(IntensityAugmentationBase2D):+class RandomGaussianBlur(_PicklableCompileMixin, IntensityAugmentationBase2D):r"""Apply gaussian blur given tensor image or a batch of tensor images randomly.The standard deviation is sampled for each instance.@@ -69,10 +69,6 @@ class RandomGaussianBlur(IntensityAugmentationBase2D):``ValueError`` naming the class, the kernel and the input shape. ``"constant"`` and ``"replicate"`` rundown to a single pixel.- .. warning::- After this class's own ``.compile()`` the module no longer pickles or passes through ``torch.save``.- Tracked in `#4807 <https://github.com/kornia/kornia/issues/4807>`_.-.. note::This function internally uses :func:`kornia.filters.gaussian_blur2d`.@@ -156,6 +152,17 @@ class RandomGaussianBlur(IntensityAugmentationBase2D):options: Optional[Dict[Any, Any]] = None,disable: bool = False,) -> "RandomGaussianBlur":+ self._record_compile(+ ["_gaussian_blur2d_fn"],+ {+ "fullgraph": fullgraph,+ "dynamic": dynamic,+ "backend": backend,+ "mode": mode,+ "options": options,+ "disable": disable,+ },+ )self._gaussian_blur2d_fn = torch.compile(self._gaussian_blur2d_fn,fullgraph=fullgraph,diff --git a/kornia/augmentation/_2d/intensity/gaussian_illumination.py b/kornia/augmentation/_2d/intensity/gaussian_illumination.pyindex eb0192af7..09cd6a1bb 100644--- a/kornia/augmentation/_2d/intensity/gaussian_illumination.py+++ b/kornia/augmentation/_2d/intensity/gaussian_illumination.py@@ -21,7 +21,7 @@ from typing import Any, Dict, Optional, Tuple, Unionimport torch-from kornia.augmentation._2d.intensity.base import IntensityAugmentationBase2D+from kornia.augmentation._2d.intensity.base import IntensityAugmentationBase2D, _PicklableCompileMixinfrom kornia.augmentation.random_generator._2d import GaussianIlluminationGeneratorfrom kornia.core.check import KORNIA_CHECK@@ -42,7 +42,7 @@ def _apply_gaussian_illumination(return input.add(gradient).clamp_(0, 1)-class RandomGaussianIllumination(IntensityAugmentationBase2D):+class RandomGaussianIllumination(_PicklableCompileMixin, IntensityAugmentationBase2D):r"""Applies random 2D Gaussian illumination patterns to a batch of images... image:: _static/img/RandomGaussianIllumination.png@@ -81,10 +81,6 @@ class RandomGaussianIllumination(IntensityAugmentationBase2D):a pixel past the pixel-centre position ``center * L - 0.5``: ``center=0.5`` lands on column ``4`` of a7-pixel-wide image. Tracked in `#4811 <https://github.com/kornia/kornia/issues/4811>`_.- .. warning::- After this class's own ``.compile()`` the module no longer pickles or passes through ``torch.save``.- Tracked in `#4807 <https://github.com/kornia/kornia/issues/4807>`_.-.. warning::An all-negative input can come back as an all-zero image, depending on the sampled gradient. Tracked in`#4430 <https://github.com/kornia/kornia/issues/4430>`_.@@ -225,6 +221,17 @@ class RandomGaussianIllumination(IntensityAugmentationBase2D):options: Optional[Dict[Any, Any]] = None,disable: bool = False,) -> RandomGaussianIllumination:+ self._record_compile(+ ["_fn"],+ {+ "fullgraph": fullgraph,+ "dynamic": dynamic,+ "backend": backend,+ "mode": mode,+ "options": options,+ "disable": disable,+ },+ )self._fn = torch.compile(self._fn,fullgraph=fullgraph,diff --git a/tests/augmentation/test_conventions_intensity_ops.py b/tests/augmentation/test_conventions_intensity_ops.pyindex 0ecbcd9f5..83ca5e0dc 100644--- a/tests/augmentation/test_conventions_intensity_ops.py+++ b/tests/augmentation/test_conventions_intensity_ops.py@@ -1262,9 +1262,9 @@ class TestIlluminationAndNormalizeConventions(BaseTester):torch.manual_seed(_FORWARD_SEED)assert bool(K.RandomGaussianIllumination(p=1.0)(image).isfinite().all())- # Issue #4807: the classes with their own ``.compile()`` store a compiled callable and then no longer- # pickle or pass through torch.save, though they still deep-copy; the linear illumination classes, which- # use torch's ``Module.compile``, keep pickling. A fix makes the first three pickle and flips it.+ # Issue #4807: the classes with their own ``.compile()`` store compiled callables. Pickling stores the+ # uncompiled ones and unpickling compiles them again, so like the linear illumination classes (torch's+ # ``Module.compile``) they pickle, pass through torch.save and still run after the round trip.# "compile" in the name is load-bearing: conftest deselects it unless KORNIA_TEST_OPTIMIZER is set, which# keeps ``torch.compile``'s process-wide side effects (it disables Distribution argument validation) out# of the ordinary CPU legs.@@ -1280,7 +1280,7 @@ class TestIlluminationAndNormalizeConventions(BaseTester):],)@pytest.mark.device_agnostic- def test_wart_compiled_intensity_augmentation_does_not_pickle_4807(self, name, own_compile):+ def test_compiled_intensity_augmentation_pickles(self, name, own_compile):if name == "RandomGaussianBlur":compiled = K.RandomGaussianBlur((3, 3), (1.0, 1.0), p=1.0)elif name == "ColorJitter":@@ -1297,13 +1297,61 @@ class TestIlluminationAndNormalizeConventions(BaseTester):cloned = copy.deepcopy(compiled)assert isinstance(cloned, type(compiled))assert cloned(constant).shape == constant.shape+ torch.save(compiled, io.BytesIO())+ try:+ restored = pickle.loads(pickle.dumps(compiled)) # noqa: S301+ finally:+ Distribution.set_default_validate_args(validate_args)+ assert isinstance(restored, type(compiled))+ assert restored(constant).shape == constant.shapeif own_compile:- with pytest.raises(pickle.PicklingError):- pickle.dumps(compiled)- with pytest.raises(pickle.PicklingError):- torch.save(compiled, io.BytesIO())+ # Compiled again on load, with the arguments of the original compile() call.+ assert restored._compile_kwargs == compiled._compile_kwargs++ # Issue #4807: unpickling passes each uncompiled callable to ``torch.compile`` again, with the arguments of+ # the last ``compile()`` call; a second ``compile()`` keeps the first, uncompiled callables for pickling, and a+ # fixed ColorJitter order also compiles (and so must restore) the torch.cond dispatcher.+ @pytest.mark.skipif(not dynamo_is_available(), reason=DYNAMO_UNAVAILABLE_REASON)+ @pytest.mark.parametrize(+ "name", ["RandomGaussianIllumination", "RandomGaussianBlur", "ColorJitter", "ColorJitterFixedOrder"]+ )+ @pytest.mark.device_agnostic+ def test_unpickled_own_compile_recompiles_with_same_arguments(self, name, monkeypatch):+ if name == "RandomGaussianBlur":+ module = K.RandomGaussianBlur((3, 3), (0.5, 1.5), p=1.0)+ elif name == "ColorJitter":+ module = K.ColorJitter(0.1, 0.1, 0.1, 0.1, p=1.0)+ elif name == "ColorJitterFixedOrder":+ module = K.ColorJitter(0.1, 0.1, 0.1, 0.1, p=1.0, order=(3, 2, 1, 0))else:- assert len(pickle.dumps(compiled)) > 0+ module = K.RandomGaussianIllumination(p=1.0)+ eager_fns = {key: fn for key, fn in vars(module).items() if key.endswith("_fn") and fn is not None}+ expected = {"fullgraph": True, "dynamic": True, "backend": "eager", "mode": None, "options": None}+ expected["disable"] = False+ calls = []+ torch_compile = torch.compile++ def spy(fn, **kwargs):+ calls.append((fn, kwargs))+ return torch_compile(fn, **kwargs)++ validate_args = Distribution._validate_args+ try:+ module.compile(backend="eager")+ module.compile(fullgraph=True, dynamic=True, backend="eager")+ payload = pickle.dumps(module)+ monkeypatch.setattr(torch, "compile", spy)+ restored = pickle.loads(payload) # noqa: S301+ finally:+ Distribution.set_default_validate_args(validate_args)+ assert len(calls) == len(eager_fns)+ assert {fn for fn, _ in calls} == set(eager_fns.values())+ assert all(kwargs == expected for _, kwargs in calls)+ image = torch.linspace(0.0, 1.0, 2 * 3 * 7 * 9).reshape(2, 3, 7, 9)+ torch.manual_seed(_FORWARD_SEED)+ expected_out = module(image)+ torch.manual_seed(_FORWARD_SEED)+ self.assert_close(restored(image), expected_out, rtol=0.0, atol=0.0)# The RandomPlasma* classes clamp into [0, 1] and record the fractal as ``_params["plasma"]``, so a# replay with ``params=`` reproduces the output bitwise. The replay runs on a non-constant image,