Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

fix(augmentation): deep-copy and pickle augmentations with learnable ranges (#6541)

Dmytro Mishkin77c088e9a158
diff --git a/changelog.d/6541.fixed.md b/changelog.d/6541.fixed.md
new file mode 100644
index 000000000..fba9a7d16
--- /dev/null
+++ b/changelog.d/6541.fixed.md
@@ -0,0 +1 @@
+`copy.deepcopy`, pickle and `torch.save` of an augmentation whose range is an `nn.Parameter`, or of a container that holds one, now give a copy that owns its own parameter. `copy.deepcopy` no longer raises "Only Tensors created explicitly by the user (graph leaves) support the deepcopy protocol", and a pickled copy, whose parameter used to receive no gradient, now trains it. A copy draws like the original under the same seed, from the value the parameter had when it was copied, so `AveragedModel` can be built from such a module, but `update_parameters` does not reach its draws (#4428). `RandomBrightness`, `RandomContrast`, `RandomSaturation` and `RandomHue` now keep a parameter range as the parameter itself, on any device, in any dtype and as a 0-d half-width, instead of replacing it with a CPU copy, and still load their earlier checkpoints strictly. `RandomRGBShift` accepts a 0-d float64 limit.
diff --git a/docs/source/get-started/conventions.rst b/docs/source/get-started/conventions.rst
index a30056406..7440396e0 100644
--- a/docs/source/get-started/conventions.rst
+++ b/docs/source/get-started/conventions.rst
@@ -662,6 +662,14 @@ Serializing an augmentation
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`.
+- A copy made with ``copy.deepcopy``, ``pickle`` or ``torch.save`` of an
+ augmentation or container with an ``nn.Parameter`` range owns a copy of
+ that parameter, and its gradients reach that copy rather than the
+ original. It draws from the value the parameter had when it was copied: as
+ in the original, an in-place update such as an optimizer step or
+ ``AveragedModel.update_parameters`` does not reach the draws
+ (`#4428 <https://github.com/kornia/kornia/issues/4428>`_). The ``_params``
+ it inherits from the last call keep their values, detached.
Morphology
----------
diff --git a/kornia/augmentation/_2d/intensity/brightness.py b/kornia/augmentation/_2d/intensity/brightness.py
index 4e59ae0db..3e4b5dde2 100644
--- a/kornia/augmentation/_2d/intensity/brightness.py
+++ b/kornia/augmentation/_2d/intensity/brightness.py
@@ -21,7 +21,7 @@ import torch
from kornia.augmentation import random_generator as rg
from kornia.augmentation._2d.intensity.base import IntensityAugmentationBase2D, _clamp_unit_range
-from kornia.augmentation.utils import _range_bound
+from kornia.augmentation.utils.param_validation import _learnable_range_bound, _load_unowned_learnable_range
from kornia.core.utils import _to_device_nonblocking
from kornia.enhance.adjust import adjust_brightness
@@ -96,8 +96,10 @@ class RandomBrightness(IntensityAugmentationBase2D):
keepdim: bool = False,
) -> None:
super().__init__(p=p, same_on_batch=same_on_batch, keepdim=keepdim)
- self.brightness: torch.Tensor = _range_bound(brightness, "brightness", center=1.0, bounds=(0.0, 2.0))
- self._param_generator = rg.PlainUniformGenerator((self.brightness, "brightness_factor", None, None))
+ factor, center, bounds = _learnable_range_bound(brightness, "brightness", center=1.0, bounds=(0.0, 2.0))
+ self.brightness: torch.Tensor = factor
+ self._param_generator = rg.PlainUniformGenerator((self.brightness, "brightness_factor", center, bounds))
+ _load_unowned_learnable_range(self, "brightness", center)
self.clip_output = clip_output
diff --git a/kornia/augmentation/_2d/intensity/contrast.py b/kornia/augmentation/_2d/intensity/contrast.py
index 3afa3e39a..35db46f16 100644
--- a/kornia/augmentation/_2d/intensity/contrast.py
+++ b/kornia/augmentation/_2d/intensity/contrast.py
@@ -21,7 +21,7 @@ import torch
from kornia.augmentation import random_generator as rg
from kornia.augmentation._2d.intensity.base import IntensityAugmentationBase2D, _clamp_unit_range
-from kornia.augmentation.utils import _range_bound
+from kornia.augmentation.utils.param_validation import _learnable_range_bound, _load_unowned_learnable_range
from kornia.core.utils import _to_device_nonblocking
from kornia.enhance.adjust import adjust_contrast
@@ -96,8 +96,10 @@ class RandomContrast(IntensityAugmentationBase2D):
keepdim: bool = False,
) -> None:
super().__init__(p=p, same_on_batch=same_on_batch, keepdim=keepdim)
- self.contrast: torch.Tensor = _range_bound(contrast, "contrast", center=1.0)
- self._param_generator = rg.PlainUniformGenerator((self.contrast, "contrast_factor", None, None))
+ factor, center, bounds = _learnable_range_bound(contrast, "contrast", center=1.0)
+ self.contrast: torch.Tensor = factor
+ self._param_generator = rg.PlainUniformGenerator((self.contrast, "contrast_factor", center, bounds))
+ _load_unowned_learnable_range(self, "contrast", center)
self.clip_output = clip_output
diff --git a/kornia/augmentation/_2d/intensity/hue.py b/kornia/augmentation/_2d/intensity/hue.py
index a92ab1a8c..cb045ff96 100644
--- a/kornia/augmentation/_2d/intensity/hue.py
+++ b/kornia/augmentation/_2d/intensity/hue.py
@@ -22,7 +22,7 @@ import torch
from kornia.augmentation import random_generator as rg
from kornia.augmentation._2d.intensity.base import IntensityAugmentationBase2D, _clamp_unit_range
-from kornia.augmentation.utils import _range_bound
+from kornia.augmentation.utils.param_validation import _learnable_range_bound, _load_unowned_learnable_range
from kornia.core.utils import _to_device_nonblocking
from kornia.enhance.adjust import adjust_hue
@@ -92,8 +92,10 @@ class RandomHue(IntensityAugmentationBase2D):
self, hue: Tuple[float, float] = (0.0, 0.0), same_on_batch: bool = False, p: float = 1.0, keepdim: bool = False
) -> None:
super().__init__(p=p, same_on_batch=same_on_batch, keepdim=keepdim)
- self.hue: torch.Tensor = _range_bound(hue, "hue", bounds=(-0.5, 0.5))
- self._param_generator = rg.PlainUniformGenerator((self.hue, "hue_factor", None, None))
+ factor, center, bounds = _learnable_range_bound(hue, "hue", bounds=(-0.5, 0.5))
+ self.hue: torch.Tensor = factor
+ self._param_generator = rg.PlainUniformGenerator((self.hue, "hue_factor", center, bounds))
+ _load_unowned_learnable_range(self, "hue", center)
def apply_transform(
self,
diff --git a/kornia/augmentation/_2d/intensity/random_rgb_shift.py b/kornia/augmentation/_2d/intensity/random_rgb_shift.py
index b40246c4e..aec537d0f 100644
--- a/kornia/augmentation/_2d/intensity/random_rgb_shift.py
+++ b/kornia/augmentation/_2d/intensity/random_rgb_shift.py
@@ -25,9 +25,11 @@ from kornia.enhance import shift_rgb
def _shift_bounds(limit: Union[torch.Tensor, float, Tuple[float, float], List[float]]) -> Tuple[Any, Any]:
- # A number (or 0-d tensor) is a half-width, bounded by itself; a (low, high) pair -- a tuple, a list or a 1-D
- # tensor -- is the range and only needs to be finite and ordered.
- if isinstance(limit, (tuple, list)) or (isinstance(limit, torch.Tensor) and limit.dim() > 0):
+ # A number is a half-width, bounded by itself; a (low, high) pair -- a tuple, a list or a 1-D tensor -- is the
+ # range and only needs to be finite and ordered. A 0-d tensor is a half-width too, but bounds computed from a
+ # learnable one would carry its autograd graph into the generator, where no copy can take it. ``[-limit, limit]``
+ # is inside its own bounds by construction, so the tensor is left unbounded instead.
+ if isinstance(limit, (tuple, list, torch.Tensor)):
return (-float("inf"), float("inf"))
return (-limit, limit)
diff --git a/kornia/augmentation/_2d/intensity/saturation.py b/kornia/augmentation/_2d/intensity/saturation.py
index 26a475863..39263c206 100644
--- a/kornia/augmentation/_2d/intensity/saturation.py
+++ b/kornia/augmentation/_2d/intensity/saturation.py
@@ -21,7 +21,7 @@ import torch
from kornia.augmentation import random_generator as rg
from kornia.augmentation._2d.intensity.base import IntensityAugmentationBase2D, _clamp_unit_range
-from kornia.augmentation.utils import _range_bound
+from kornia.augmentation.utils.param_validation import _learnable_range_bound, _load_unowned_learnable_range
from kornia.core.utils import _to_device_nonblocking
from kornia.enhance.adjust import adjust_saturation
@@ -93,8 +93,10 @@ class RandomSaturation(IntensityAugmentationBase2D):
keepdim: bool = False,
) -> None:
super().__init__(p=p, same_on_batch=same_on_batch, keepdim=keepdim)
- self.saturation: torch.Tensor = _range_bound(saturation, "saturation", center=1.0)
- self._param_generator = rg.PlainUniformGenerator((self.saturation, "saturation_factor", None, None))
+ factor, center, bounds = _learnable_range_bound(saturation, "saturation", center=1.0)
+ self.saturation: torch.Tensor = factor
+ self._param_generator = rg.PlainUniformGenerator((self.saturation, "saturation_factor", center, bounds))
+ _load_unowned_learnable_range(self, "saturation", center)
def apply_transform(
self,
diff --git a/kornia/augmentation/base.py b/kornia/augmentation/base.py
index 86566fdfa..b32698b2a 100644
--- a/kornia/augmentation/base.py
+++ b/kornia/augmentation/base.py
@@ -29,7 +29,7 @@ from kornia.augmentation.utils import (
_transform_output_shape,
override_parameters,
)
-from kornia.augmentation.utils.helpers import _constant_tensor
+from kornia.augmentation.utils.helpers import _constant_tensor, _detach_recorded_graph_tensors
from kornia.core.utils import _to_device_nonblocking, is_autocast_enabled, is_exporting
from kornia.geometry.boxes import Boxes
from kornia.geometry.keypoints import Keypoints
@@ -159,6 +159,11 @@ class _BasicAugmentationBase(nn.Module):
self.set_rng_device_and_dtype(probe.device, dtype)
return out
+ def __getstate__(self) -> Dict[str, Any]:
+ # With a learnable range, ``_params`` and the matrix state recorded by the last call are part of its graph;
+ # a copy keeps their values, detached.
+ return _detach_recorded_graph_tensors(super().__getstate__())
+
def __repr__(self) -> str:
txt = f"p={self.p}, p_batch={self.p_batch}, same_on_batch={self.same_on_batch}"
if isinstance(self._param_generator, RandomGeneratorBase):
diff --git a/kornia/augmentation/container/base.py b/kornia/augmentation/container/base.py
index 56fdac526..050222127 100644
--- a/kornia/augmentation/container/base.py
+++ b/kornia/augmentation/container/base.py
@@ -24,7 +24,12 @@ from torch import nn
import kornia.augmentation as K
from kornia.augmentation.base import _AugmentationBase
-from kornia.augmentation.utils.helpers import _IMAGE_SHAPES, _VOLUME_SHAPES, _raise_input_rank_error
+from kornia.augmentation.utils.helpers import (
+ _IMAGE_SHAPES,
+ _VOLUME_SHAPES,
+ _detach_recorded_graph_tensors,
+ _raise_input_rank_error,
+)
from kornia.core.utils import is_exporting
from kornia.geometry.boxes import Boxes
from kornia.geometry.keypoints import Keypoints
@@ -53,6 +58,11 @@ class BasicSequentialBase(nn.Sequential):
super().__init__(_args)
self._params: Optional[List[ParamItem]] = None
+ def __getstate__(self) -> Dict[str, Any]:
+ # With a learnable range, ``_params`` and the matrix state recorded by the last call are part of its graph;
+ # a copy keeps their values, detached.
+ return _detach_recorded_graph_tensors(super().__getstate__())
+
def get_submodule(self, target: str) -> nn.Module:
"""Get submodule.
diff --git a/kornia/augmentation/random_generator/_2d/plain_uniform.py b/kornia/augmentation/random_generator/_2d/plain_uniform.py
index 204fe27f9..e81a8b53c 100644
--- a/kornia/augmentation/random_generator/_2d/plain_uniform.py
+++ b/kornia/augmentation/random_generator/_2d/plain_uniform.py
@@ -22,7 +22,7 @@ from torch.distributions import Distribution
from kornia.augmentation.random_generator.base import RandomGeneratorBase, UniformDistribution
from kornia.augmentation.utils import _adapted_rsampling, _common_param_check, _range_bound
-from kornia.core.utils import _extract_device_dtype
+from kornia.core.utils import _extract_device_dtype, _to_device_nonblocking
__all__ = ["ParameterBound", "PlainUniformGenerator"]
@@ -94,7 +94,9 @@ class PlainUniformGenerator(RandomGeneratorBase):
_common_param_check(batch_size, same_on_batch)
_device, _dtype = _extract_device_dtype([t for t, _, _, _ in self.samplers])
+ # The draws are made on the generator's device and returned on the device of the ranges. The two differ for a
+ # learnable range made on CUDA in a module left on the CPU; the copy to CUDA then does not wait for the GPU.
return {
- name: _adapted_rsampling((batch_size,), dist, same_on_batch).to(device=_device, dtype=_dtype)
+ name: _to_device_nonblocking(_adapted_rsampling((batch_size,), dist, same_on_batch), _device, _dtype)
for name, dist in self.sampler_dict.items()
}
diff --git a/kornia/augmentation/random_generator/base.py b/kornia/augmentation/random_generator/base.py
index c79828a23..f181bb44a 100644
--- a/kornia/augmentation/random_generator/base.py
+++ b/kornia/augmentation/random_generator/base.py
@@ -21,10 +21,12 @@ import torch
from torch import nn
from torch.distributions import Distribution, Uniform
-from kornia.augmentation.utils.helpers import MultiprocessWrapper
+from kornia.augmentation.utils.helpers import MultiprocessWrapper, _holds_graph_tensor
T = TypeVar("T")
+_UNSET = object()
+
class _PostInitInjectionMetaClass(type):
"""To inject the ``__post_init__`` function after the creation of each instance."""
@@ -61,10 +63,41 @@ class RandomGeneratorBase(nn.Module, metaclass=_PostInitInjectionMetaClass):
if device is None:
device = torch.device("cpu")
if self.device != device or self.dtype != dtype:
+ before = dict(self.__dict__)
self.make_samplers(device, dtype)
+ # What ``make_samplers`` assigns is derived from the ranges, device and dtype; ``__getstate__`` reads
+ # the names to know what it may leave out of a copy and have ``__setstate__`` rebuild.
+ made = {name for name, value in self.__dict__.items() if before.get(name, _UNSET) is not value}
+ self._sampler_attrs = tuple(sorted(made.union(self.__dict__.get("_sampler_attrs", ()))))
self.device = device
self.dtype = dtype
+ def __getstate__(self) -> Dict[str, Any]:
+ # A range that requires grad, such as a learnable ``nn.Parameter``, makes the samplers autograd views of it.
+ # ``copy.deepcopy`` refuses those, and pickle turns them into leaves that the copy's own range never reaches.
+ # Leave them out: ``__setstate__`` rebuilds them from the copy's range, so gradients from the copy reach the
+ # copy's parameter. Samplers without autograd history are copied as they are.
+ state = super().__getstate__()
+ dropped = [name for name in state.get("_sampler_attrs", ()) if _holds_graph_tensor(state.get(name))]
+ for name in dropped:
+ del state[name]
+ if dropped:
+ # ``torch.load(map_location=...)`` moves the tensors of the state but not ``self.device``. An empty tensor
+ # on that device moves with them and tells ``__setstate__`` where the samplers would have gone.
+ state["_sampler_device_probe"] = torch.empty(0, device=self.device)
+ return state
+
+ def __setstate__(self, state: Dict[str, Any]) -> None:
+ probe = state.pop("_sampler_device_probe", None)
+ super().__setstate__(state)
+ if any(name not in self.__dict__ for name in self.__dict__.get("_sampler_attrs", ())):
+ if probe is not None:
+ self.device = probe.device
+ # Only samplers with autograd history were left out, so they are rebuilt with it, whatever the grad mode
+ # of the copy: under ``torch.no_grad()`` the copy's range would otherwise never receive a gradient.
+ with torch.enable_grad():
+ self.make_samplers(self.device, self.dtype)
+
def to(self, *args: Any, **kwargs: Any) -> "RandomGeneratorBase":
"""Update sampler device and dtype using ``torch.nn.Module.to`` semantics.
@@ -89,6 +122,9 @@ class RandomGeneratorBase(nn.Module, metaclass=_PostInitInjectionMetaClass):
def make_samplers(self, device: torch.device, dtype: torch.dtype) -> None:
"""Create distribution samplers for the given device and dtype.
+ Assign the samplers to attributes of the generator, new or replaced, rather than writing them into an object
+ it already holds: a copy of the generator rebuilds the attributes this call assigns, and only those.
+
Args:
device: Target device.
dtype: Target floating-point dtype.
diff --git a/kornia/augmentation/utils/helpers.py b/kornia/augmentation/utils/helpers.py
index 49a8a7ec2..bff33adf4 100644
--- a/kornia/augmentation/utils/helpers.py
+++ b/kornia/augmentation/utils/helpers.py
@@ -579,6 +579,62 @@ class MultiprocessWrapper:
super().__init__(*args, **kwargs)
+def _holds_graph_tensor(value: Any) -> bool:
+ """Whether ``value`` holds a tensor with autograd history, directly, in a container or in a distribution.
+
+ ``copy.deepcopy`` refuses such a tensor, and pickle turns it into a leaf cut off from the graph.
+ """
+ if isinstance(value, torch.Tensor):
+ return not value.is_leaf
+ if isinstance(value, dict):
+ return any(_holds_graph_tensor(item) for item in value.values())
+ if isinstance(value, (list, tuple)):
+ return any(_holds_graph_tensor(item) for item in value)
+ if isinstance(value, torch.distributions.Distribution):
+ return any(_holds_graph_tensor(item) for item in vars(value).values())
+ return False
+
+
+def _detach_graph_tensors(value: Any, memo: Dict[int, Any]) -> Any:
+ """Return ``value`` with each tensor that has autograd history detached; ``memo`` keeps shared values shared.
+
+ Dicts, lists and tuples (named tuples included) on the way to such a tensor are rebuilt; anything else is
+ returned as it is.
+ """
+ if not _holds_graph_tensor(value):
+ return value
+ if id(value) in memo:
+ return memo[id(value)]
+ out: Any
+ if isinstance(value, torch.Tensor):
+ out = value.detach()
+ elif isinstance(value, dict):
+ out = type(value)((key, _detach_graph_tensors(item, memo)) for key, item in value.items())
+ elif isinstance(value, list):
+ out = [_detach_graph_tensors(item, memo) for item in value]
+ elif isinstance(value, tuple):
+ items = [_detach_graph_tensors(item, memo) for item in value]
+ out = type(value)(*items) if hasattr(value, "_fields") else tuple(items)
+ else:
+ out = value
+ memo[id(value)] = out
+ return out
+
+
+def _detach_recorded_graph_tensors(state: Dict[str, Any]) -> Dict[str, Any]:
+ """Detach the autograd history in a module state's plain attributes, for ``__getstate__``.
+
+ With a learnable range, what a forward records on the module (the drawn parameters, the transformation matrix)
+ is part of the autograd graph of that call. A copy cannot extend the original's graph, and ``copy.deepcopy``
+ refuses such tensors, so the copy keeps their values, detached. Parameters, buffers and submodules follow their
+ own copy protocol and are left alone.
+ """
+ memo: Dict[int, Any] = {}
+ for name in [name for name in state if name not in ("_parameters", "_buffers", "_modules")]:
+ state[name] = _detach_graph_tensors(state[name], memo)
+ return state
+
+
#: How small an image each padding mode can filter, given the kernel extent ``k`` along that axis.
#: ``filter2d`` and ``filter3d`` pad an even kernel asymmetrically -- ``(k - 1) // 2`` in front and
#: ``k // 2`` behind -- so the constraint is against the wider of the two, ``k // 2``, not against the
diff --git a/kornia/augmentation/utils/param_validation.py b/kornia/augmentation/utils/param_validation.py
index 874a36220..a2ee8a38f 100644
--- a/kornia/augmentation/utils/param_validation.py
+++ b/kornia/augmentation/utils/param_validation.py
@@ -15,7 +15,8 @@
# limitations under the License.
#
-from typing import Any, List, Optional, Tuple, Union
+from functools import partial
+from typing import Any, Dict, List, Optional, Tuple, Union
import torch
@@ -126,6 +127,58 @@ def _range_bound(
return factor_bound
+def _learnable_range_bound(
+ factor: Union[torch.Tensor, float, Tuple[float, float], List[float]],
+ name: str,
+ center: Optional[float] = 0.0,
+ bounds: Optional[Tuple[float, float]] = (0, float("inf")),
+) -> Tuple[torch.Tensor, Optional[float], Optional[Tuple[float, float]]]:
+ r"""Check a sampling range like :func:`_range_bound`, keeping a learnable one as the leaf that was passed.
+
+ Returns the range to keep on the module, then the ``center`` and ``bounds`` that ``PlainUniformGenerator`` still
+ has to apply when it builds its samplers. :func:`_range_bound` converts a range to the default device and dtype and
+ derives ``[center - factor, center + factor]`` from a number, which turns an ``nn.Parameter`` into a tensor that the
+ module does not own and a copy cannot take. A parameter is therefore checked on a detached copy and kept as it is:
+ a ``(2,)`` one is the range itself, and the range of a 0-d one is derived in ``make_samplers``, on the generator's
+ device and dtype, from the parameter of whichever module builds the samplers. Any other input returns the
+ :func:`_range_bound` result with no ``center`` or ``bounds`` left to apply.
+ """
+ if not isinstance(factor, torch.nn.Parameter):
+ return _range_bound(factor, name, center=center, bounds=bounds), None, None
+ _range_bound(factor.detach(), name, center=center, bounds=bounds)
+ if factor.dim() == 0:
+ return factor, center, bounds
+ return factor, None, None
+
+
+def _load_unowned_learnable_range(module: torch.nn.Module, name: str, center: Optional[float]) -> None:
+ r"""Let ``module`` strict-load a checkpoint saved when it did not own its learnable range ``name`` yet.
+
+ Use it after :func:`_learnable_range_bound`, with the ``center`` it returned. The colour augmentations used to keep
+ an ``nn.Parameter`` range only when it was a ``(2,)`` CPU tensor in the default dtype. Their other checkpoints hold
+ no ``name`` entry, only the generator's ``<name>_factor``: the range as a ``(2,)`` tensor, and for a 0-d parameter
+ the range derived from it, ``[max(center - f, low), center + f]``. A load pre-hook fills ``name`` from that entry,
+ and for a 0-d parameter recovers ``f`` as the upper end minus ``center``, because the upper end is never clamped.
+ Nothing is registered for a range that is not a parameter, whose checkpoint layout did not change.
+ """
+ if isinstance(module._parameters.get(name), torch.nn.Parameter):
+ module._register_load_state_dict_pre_hook(partial(_fill_unowned_learnable_range, name, center))
+
+
+def _fill_unowned_learnable_range(
+ name: str, center: Optional[float], state_dict: Dict[str, Any], prefix: str, *args: Any
+) -> None:
+ key, factor_key = prefix + name, f"{prefix}_param_generator.{name}_factor"
+ if key in state_dict or factor_key not in state_dict:
+ return
+ saved = state_dict[factor_key]
+ # ``center`` is only returned for a 0-d parameter; a (2,) entry for it is the range the old layout derived.
+ if center is not None and isinstance(saved, torch.Tensor) and saved.shape == (2,):
+ saved = saved.detach()[1] - center
+ state_dict[factor_key] = saved
+ state_dict[key] = saved
+
+
def _shear_bound(
shear: Union[torch.Tensor, float, Tuple[float, float], Tuple[float, float, float, float]],
device: torch.device,
diff --git a/tests/augmentation/test_base.py b/tests/augmentation/test_base.py
index dfff95f44..b2b69801d 100644
--- a/tests/augmentation/test_base.py
+++ b/tests/augmentation/test_base.py
@@ -15,7 +15,9 @@
# limitations under the License.
#
+import contextlib
import copy
+import io
import pickle
from types import SimpleNamespace
from unittest.mock import Mock, patch
@@ -1618,3 +1620,337 @@ class TestStaticProbabilityIgnoresHandMadeGate(BaseTester):
_, inv_mask, inv_boxes = aug.inverse(out, out_mask, out_boxes, params=aug._params)
self.assert_close(inv_mask, mask)
self.assert_close(inv_boxes, boxes)
+
+
+def _learnable(*values: float) -> torch.nn.Parameter:
+ return torch.nn.Parameter(torch.tensor(values if len(values) > 1 else values[0]))
+
+
+# name -> (constructor, volumetric input, range receives a gradient). One augmentation per generator family that builds
+# its samplers from a range tensor, plus RandomRGBShift (a 0-d half-width) and a mix augmentation. The ranges are made
+# on the CPU and move with the module, the way a model holding the augmentation is moved.
+_LEARNABLE_RANGES = {
+ "RandomBrightness": (lambda: K.RandomBrightness(_learnable(0.8, 1.2), p=1.0), False, True),
+ "RandomRGBShift": (lambda: K.RandomRGBShift(_learnable(0.1), _learnable(0.2), _learnable(0.3), p=1.0), False, True),
+ "ColorJiggle": (
+ lambda: K.ColorJiggle(_learnable(0.8, 1.2), _learnable(0.8, 1.2), _learnable(0.8, 1.2), _learnable(-0.1, 0.1)),
+ False,
+ True,
+ ),
+ "ColorJitter": (
+ lambda: K.ColorJitter(_learnable(0.8, 1.2), _learnable(0.8, 1.2), _learnable(0.8, 1.2), _learnable(-0.1, 0.1)),
+ False,
+ True,
+ ),
+ "RandomAffine": (
+ lambda: K.RandomAffine(
+ _learnable(-10.0, 10.0), _learnable(0.1, 0.1), _learnable(0.9, 1.1), _learnable(-5.0, 5.0), p=1.0
+ ),
+ False,
+ True,
+ ),
+ "RandomRotation": (lambda: K.RandomRotation(_learnable(10.0, 20.0), p=1.0), False, True),
+ "RandomShear": (lambda: K.RandomShear(_learnable(-5.0, 5.0), p=1.0), False, True),
+ "RandomTranslate": (lambda: K.RandomTranslate(_learnable(-0.1, 0.1), _learnable(-0.1, 0.1), p=1.0), False, True),
+ "RandomPerspective": (lambda: K.RandomPerspective(_learnable(0.5), p=1.0), False, True),
+ "RandomMotionBlur": (
+ lambda: K.RandomMotionBlur(3, _learnable(-30.0, 30.0), _learnable(-0.5, 0.5), p=1.0),
+ False,
+ True,
+ ),
+ "RandomResizedCrop": (
+ lambda: K.RandomResizedCrop((6, 6), scale=_learnable(0.5, 1.0), ratio=_learnable(0.75, 1.33), p=1.0),
+ False,
+ False,
+ ),
+ "RandomErasing": (lambda: K.RandomErasing(_learnable(0.02, 0.33), _learnable(0.3, 3.3), p=1.0), False, False),
+ "RandomMixUpV2": (lambda: K.RandomMixUpV2(_learnable(0.0, 1.0), p=1.0), False, False),
+ "RandomAffine3D": (
+ lambda: K.RandomAffine3D(
+ _learnable(-10.0, 10.0), _learnable(0.1, 0.1, 0.1), _learnable(0.9, 1.1), _learnable(-5.0, 5.0), p=1.0
+ ),
+ True,
+ True,
+ ),
+ "RandomRotation3D": (lambda: K.RandomRotation3D(_learnable(-10.0, 10.0), p=1.0), True, True),
+ "RandomPerspective3D": (lambda: K.RandomPerspective3D(_learnable(0.5), p=1.0), True, True),
+ "RandomMotionBlur3D": (
+ lambda: K.RandomMotionBlur3D(3, _learnable(-30.0, 30.0), _learnable(-0.5, 0.5), p=1.0),
+ True,
+ True,
+ ),
+}
+_DIFFERENTIABLE_RANGES = [name for name, (_, _, differentiable) in _LEARNABLE_RANGES.items() if differentiable]
+
+# name -> (constructor, (2,) range, 0-d half-width). Ranges made directly on the test device and dtype. The four colour
+# classes used to check theirs with ``_range_bound``, which kept a CPU float32 copy (or, for a half-width, a derived
+# range) that the module did not own; RandomAffine and ColorJitter check theirs in the generator and are controls.
+_RANGES_ON_DEVICE = {
+ "RandomBrightness": (lambda r: K.RandomBrightness(r, p=1.0), (0.8, 1.2), 0.2),
+ "RandomContrast": (lambda r: K.RandomContrast(r, p=1.0), (0.8, 1.2), 0.2),
+ "RandomSaturation": (lambda r: K.RandomSaturation(r, p=1.0), (0.8, 1.2), 0.2),
+ "RandomHue": (lambda r: K.RandomHue(r, p=1.0), (-0.1, 0.1), 0.1),
+ "RandomAffine": (lambda r: K.RandomAffine(r, p=1.0), (-10.0, 10.0), 10.0),
+ "ColorJitter": (lambda r: K.ColorJitter(r, p=1.0), (0.8, 1.2), 0.2),
+}
+
+# name -> (class, range name, (2,) range, 0-d half-width, the range a checkpoint holds for that half-width). Before the
+# four colour classes owned a learnable range, their checkpoints held one only as the generator's ``<name>_factor``, a
+# CPU float32 (2,) range, unless it was a CPU float32 (2,) parameter. For a 0-d half-width that is the range derived
+# from it, with the lower end floored at the domain: the saved ranges are what
+# ``RandomX(nn.Parameter(torch.tensor(half_width))).state_dict()`` gives at 0ee23ec52.
+_UNOWNED_RANGE_CHECKPOINTS = {
+ "RandomBrightness": (K.RandomBrightness, "brightness", (0.8, 1.2), 0.2, (0.8, 1.2)),
+ "RandomContrast": (K.RandomContrast, "contrast", (0.8, 1.2), 0.3, (0.7, 1.3)),
+ "RandomSaturation": (K.RandomSaturation, "saturation", (0.7, 1.2), 1.5, (0.0, 2.5)),
+ "RandomHue": (K.RandomHue, "hue", (-0.1, 0.2), 0.1, (-0.1, 0.1)),
+}
+
+
+def _torch_save_round_trip(module: torch.nn.Module) -> torch.nn.Module:
+ buffer = io.BytesIO()
+ torch.save(module, buffer)
+ buffer.seek(0)
+ return torch.load(buffer, weights_only=False)
+
+
+_COPIERS = {
+ "deepcopy": copy.deepcopy,
+ "pickle": lambda module: pickle.loads(pickle.dumps(module)), # noqa: S301
+ "torch.save": _torch_save_round_trip,
+}
+
+
+class TestLearnableRangeCopies(BaseTester):
+ """``copy.deepcopy``, pickle and ``torch.save`` of augmentations whose range is a learnable ``nn.Parameter``."""
+
+ @staticmethod
+ def _case(name, device, dtype):
+ make, volumetric, _ = _LEARNABLE_RANGES[name]
+ torch.manual_seed(0)
+ aug = make().to(device=device, dtype=dtype)
+ shape = (2, 3, 4, 8, 8) if volumetric else (2, 3, 8, 8)
+ return aug, torch.rand(shape, generator=torch.Generator().manual_seed(0)).to(device=device, dtype=dtype)
+
+ @staticmethod
+ def _draw(module, seed, *inputs):
+ torch.manual_seed(seed)
+ return module(*inputs)
+
+ @staticmethod
+ def _ranges(module):
+ # Read the dispatcher's parameters through its sequences, which it registers as child modules only since #6449.
+ members = module.augmentations if isinstance(module, K.ManyToOneAugmentationDispather) else [module]
+ return [p for member in members for p in member.parameters()]
+
+ @pytest.mark.parametrize("name", list(_LEARNABLE_RANGES))
+ def test_deepcopy_draws_like_the_original(self, name, device, dtype):
+ aug, x = self._case(name, device, dtype)
+ before = copy.deepcopy(aug)
+ self._draw(aug, 1, x)
+ after = copy.deepcopy(aug)
+ expected = self._draw(aug, 2, x)
+ for clone in (before, after):
+ assert all(q is not p for p, q in zip(aug.parameters(), clone.parameters()))
+ self.assert_close(self._draw(clone, 2, x), expected, rtol=0, atol=0)
+ _assert_params_equal(clone._params, aug._params)
+
+ @pytest.mark.parametrize("name", list(_LEARNABLE_RANGES))
+ def test_deepcopy_keeps_the_last_draw_detached(self, name, device, dtype):
+ aug, x = self._case(name, device, dtype)
+ self._draw(aug, 1, x)
+ clone = copy.deepcopy(aug)
+ _assert_params_equal(clone._params, aug._params)
+ assert all(value.grad_fn is None for value in clone._params.values() if isinstance(value, torch.Tensor))
+ if getattr(aug, "_transform_matrix_params", None) is aug._params:
+ # Records that share values in the original still share them in the copy.
+ assert clone._transform_matrix_params is clone._params
+
+ @pytest.mark.parametrize("grad_mode", ["enabled", "no_grad"])
+ @pytest.mark.parametrize("copier", list(_COPIERS))
+ @pytest.mark.parametrize("name", _DIFFERENTIABLE_RANGES)
+ def test_gradients_reach_the_range_of_the_copy(self, name, copier, grad_mode, device, dtype):
+ aug, x = self._case(name, device, dtype)
+ # A copy made under ``torch.no_grad()``, as an EMA or evaluation copy often is, trains like any other.
+ with torch.no_grad() if grad_mode == "no_grad" else contextlib.nullcontext():
+ clone = _COPIERS[copier](aug)
+ self._draw(aug, 3, x).sum().backward()
+ expected = [None if p.grad is None else p.grad.clone() for p in aug.parameters()]
+ assert any(grad is not None and bool(grad.ne(0).any()) for grad in expected)
+ aug.zero_grad(set_to_none=True)
+
+ self._draw(clone, 3, x).sum().backward()
+
+ assert all(p.grad is None for p in aug.parameters())
+ clone_ranges = list(clone.parameters())
+ assert len(clone_ranges) == len(expected)
+ for q, grad in zip(clone_ranges, expected):
+ if grad is None:
+ assert q.grad is None
+ else:
+ self.assert_close(q.grad, grad)
+
+ def test_copy_keeps_the_state_dict(self, device, dtype):
+ aug, x = self._case("RandomRotation", device, dtype)
+ self._draw(aug, 1, x)
+ clone = copy.deepcopy(aug)
+ assert list(clone.state_dict()) == list(aug.state_dict()) == ["_param_generator.degrees"]
+ for key, value in aug.state_dict().items():
+ self.assert_close(clone.state_dict()[key], value, rtol=0, atol=0)
+ target = _LEARNABLE_RANGES["RandomRotation"][0]().to(device=device, dtype=dtype)
+ target.load_state_dict(clone.state_dict())
+ self.assert_close(target._param_generator.degrees, aug._param_generator.degrees, rtol=0, atol=0)
+
+ def test_copy_follows_device_and_dtype_moves(self, device, dtype):
+ aug, x = self._case("RandomAffine", torch.device("cpu"), torch.float32)
+ clone = copy.deepcopy(aug)
+ aug.to(device=device, dtype=dtype)
+ clone.to(device=device, dtype=dtype)
+ x = x.to(device=device, dtype=dtype)
+ expected = self._draw(aug, 2, x)
+ actual = self._draw(clone, 2, x)
+ self.assert_close(actual, expected, rtol=0, atol=0)
+ actual.sum().backward()
+ for q in clone.parameters():
+ assert q.device == x.device
+ assert q.dtype == dtype
+ assert q.grad is not None
+
+ @pytest.mark.parametrize("container", ["AugmentationSequential", "ManyToOneAugmentationDispather"])
+ def test_container_copy_draws_and_trains_like_the_original(self, container, device, dtype):
+ def sequence():
+ return K.AugmentationSequential(
+ _LEARNABLE_RANGES["RandomBrightness"][0](),
+ _LEARNABLE_RANGES["RandomAffine"][0](),
+ data_keys=["input", "mask", "bbox_xyxy"],
+ ).to(device=device, dtype=dtype)
+
+ def outputs(out):
+ # AugmentationSequential returns [image, mask, boxes]; the dispatcher returns one such list per sequence.
+ return [out] if container == "AugmentationSequential" else out
+
+ torch.manual_seed(0)
+ module = (
+ sequence()
+ if container == "AugmentationSequential"
+ else K.ManyToOneAugmentationDispather(sequence(), sequence())
+ )
+ image = torch.rand(2, 3, 8, 8, generator=torch.Generator().manual_seed(0)).to(device=device, dtype=dtype)
+ mask = (image[:, :1] > 0.5).to(dtype)
+ boxes = torch.tensor([[[1.0, 1.0, 5.0, 6.0]]], device=device, dtype=dtype).repeat(2, 1, 1)
+ before = copy.deepcopy(module)
+ self._draw(module, 1, image, mask, boxes)
+ after = copy.deepcopy(module)
+ expected = outputs(self._draw(module, 2, image, mask, boxes))
+ sum(out[0].sum() for out in expected).backward()
+ expected_grads = [p.grad.clone() for p in self._ranges(module)]
+ for p in self._ranges(module):
+ p.grad = None
+
+ for clone in (before, after):
+ actual = outputs(self._draw(clone, 2, image, mask, boxes))
+ for actual_out, expected_out in zip(actual, expected):
+ for actual_value, expected_value in zip(actual_out, expected_out):
+ self.assert_close(actual_value, expected_value, rtol=0, atol=0)
+ sum(out[0].sum() for out in actual).backward()
+ assert all(p.grad is None for p in self._ranges(module))
+ clone_ranges = self._ranges(clone)
+ assert len(clone_ranges) == len(expected_grads) == 5 * len(expected)
+ for q, grad in zip(clone_ranges, expected_grads):
+ self.assert_close(q.grad, grad)
+
+ def test_averaged_model_of_a_learnable_range(self, device, dtype):
+ aug, x = self._case("RandomAffine", device, dtype)
+ averaged = torch.optim.swa_utils.AveragedModel(aug)
+ averaged.update_parameters(aug)
+ expected = self._draw(aug, 2, x)
+ self.assert_close(self._draw(averaged, 2, x), expected, rtol=0, atol=0)
+ for p, q in zip(aug.parameters(), averaged.module.parameters()):
+ assert q is not p
+ self.assert_close(q, p, rtol=0, atol=0)
+
+ @pytest.mark.parametrize("form", ["range", "half-width"])
+ @pytest.mark.parametrize("name", list(_RANGES_ON_DEVICE))
+ def test_range_made_on_the_device_is_owned_and_copied(self, name, form, device, dtype):
+ make, pair, half_width = _RANGES_ON_DEVICE[name]
+ param = torch.nn.Parameter(torch.tensor(pair if form == "range" else half_width, device=device, dtype=dtype))
+ torch.manual_seed(0)
+ aug = make(param)
+ owned = list(aug.parameters())
+ assert len(owned) == 1
+ assert owned[0] is param
+ x = torch.rand(2, 3, 8, 8, generator=torch.Generator().manual_seed(0)).to(device=device, dtype=dtype)
+ # The same draws as the same augmentation built from a plain tensor with these values.
+ expected = self._draw(make(param.detach().clone()), 2, x)
+ self.assert_close(self._draw(aug, 2, x), expected, rtol=0, atol=0)
+
+ before = copy.deepcopy(aug)
+ self._draw(aug, 1, x)
+ after = copy.deepcopy(aug)
+ self._draw(aug, 2, x).sum().backward()
+ grad = param.grad.clone()
+ assert bool(grad.ne(0).any())
+ param.grad = None
+ for clone in (before, after):
+ (clone_param,) = clone.parameters()
+ assert clone_param is not param
+ actual = self._draw(clone, 2, x)
+ self.assert_close(actual, expected, rtol=0, atol=0)
+ actual.sum().backward()
+ assert param.grad is None
+ self.assert_close(clone_param.grad, grad)
+
+ if device.type != "mps": # MPS has no float64 to move to
+ other = torch.float32 if dtype == torch.float64 else torch.float64
+ aug.to(dtype=other)
+ assert param.dtype == other
+
+ def test_rgb_shift_takes_a_half_width_tensor_in_any_dtype(self, device, dtype):
+ # A 0-d limit is a half-width. Its bounds are not computed from the tensor, so a value that rounds when the
+ # generator samples in float32 is not reported out of its own bounds.
+ limit = torch.tensor(0.3, device=device, dtype=dtype)
+ aug = K.RandomRGBShift(limit, limit, limit, p=1.0)
+ params = aug.forward_parameters((2, 3, 4, 4))
+ for key in ("r_shift", "g_shift", "b_shift"):
+ assert bool((params[key].abs() <= float(limit) * (1 + 1e-3)).all())
+
+ @pytest.mark.parametrize("name", ["RandomBrightness", "RandomAffine"])
+ def test_load_mapped_to_the_cpu_rebuilds_the_samplers_there(self, name, device, dtype):
+ if device.type == "cpu":
+ pytest.skip("needs a device to map from")
+ # ``torch.load(map_location=...)`` moves the tensors of a module but not its generator's ``device``. The
+ # samplers are rebuilt where the tensors went, so a module saved on an accelerator loads where there is none.
+ aug, x = self._case(name, device, dtype)
+ self._draw(aug, 1, x)
+ buffer = io.BytesIO()
+ torch.save(aug, buffer)
+ buffer.seek(0)
+ generator = torch.load(buffer, map_location="cpu", weights_only=False)._param_generator
+ moved = copy.deepcopy(aug).to("cpu")._param_generator
+ assert generator.device == moved.device == torch.device("cpu")
+ torch.manual_seed(2)
+ expected = moved(x.shape)
+ torch.manual_seed(2)
+ actual = generator(x.shape)
+ assert actual.keys() == expected.keys()
+ for key, value in expected.items():
+ self.assert_close(actual[key], value, rtol=0, atol=0)
+ sum(value.sum() for value in actual.values() if value.is_floating_point()).backward()
+ assert all(p.grad is not None and p.device.type == "cpu" for p in generator.parameters())
+
+ @pytest.mark.parametrize("form", ["range", "half-width"])
+ @pytest.mark.parametrize("name", list(_UNOWNED_RANGE_CHECKPOINTS))
+ def test_strict_load_of_a_checkpoint_without_the_range(self, name, form, device, dtype):
+ make, key, pair, half_width, saved_range = _UNOWNED_RANGE_CHECKPOINTS[name]
+ value = torch.tensor(pair if form == "range" else half_width, device=device, dtype=dtype)
+ checkpoint = {f"_param_generator.{key}_factor": torch.tensor(pair if form == "range" else saved_range)}
+ aug = make(torch.nn.Parameter(value.clone()), p=1.0)
+ for target in (aug, pickle.loads(pickle.dumps(aug))): # noqa: S301
+ (param,) = target.parameters()
+ with torch.no_grad():
+ param.zero_()
+ target.load_state_dict(checkpoint)
+ self.assert_close(param, value)
+ # A checkpoint of the module as it is now still loads, and its own layout is kept.
+ target.load_state_dict(make(torch.nn.Parameter(value.clone()), p=1.0).state_dict())
+ assert set(target.state_dict()) == {key, f"_param_generator.{key}_factor"}
diff --git a/tests/augmentation/test_host_sync.py b/tests/augmentation/test_host_sync.py
index 4e5205c73..87bb7d0e6 100644
--- a/tests/augmentation/test_host_sync.py
+++ b/tests/augmentation/test_host_sync.py
@@ -59,6 +59,15 @@ _EMPTY_BATCH_MIX = {
"RandomCutMixV2": lambda: K.RandomCutMixV2(p=1.0, use_correct_lambda=True),
"RandomMixUpV2": lambda: K.RandomMixUpV2(p=1.0),
}
+# Learnable ranges made on CUDA for an augmentation that stays on the CPU: ``PlainUniformGenerator`` samples on the CPU
+# and returns the draws on the device of the ranges.
+_RANGES_ON_CUDA = {
+ "RandomBrightness-range": lambda r: K.RandomBrightness(r(0.8, 1.2), p=1.0),
+ "RandomBrightness-half-width": lambda r: K.RandomBrightness(r(0.2), p=1.0),
+ "RandomHue-half-width": lambda r: K.RandomHue(r(0.1), p=1.0),
+ "RandomRotation": lambda r: K.RandomRotation(r(-10.0, 10.0), p=1.0),
+ "RandomGamma": lambda r: K.RandomGamma(r(0.8, 1.2), r(0.9, 1.1), p=1.0),
+}
# Host reads that only happen because the caller moved the parameters to CUDA: the crop window and the padding set
# the sizes of Python slices.
_REPLAY_DEVICE_READS = {
@@ -130,6 +139,25 @@ class TestAugmentationHostSync(BaseTester):
assert outputs[0].device == x.device
assert not set(sites) - INHERENT_SITES.keys(), dict(sites)
+ @pytest.mark.parametrize("name", sorted(_RANGES_ON_CUDA))
+ def test_learnable_range_on_cuda_with_the_module_on_the_cpu(self, name, device, dtype) -> None:
+ if device.type != "cuda":
+ pytest.skip("CUDA host synchronizations need a CUDA device")
+
+ def learnable(*values):
+ value = values if len(values) > 1 else values[0]
+ return torch.nn.Parameter(torch.tensor(value, device=device, dtype=dtype))
+
+ op = _RANGES_ON_CUDA[name](learnable)
+ x = torch.rand(4, 3, 16, 16, device=device, dtype=dtype)
+ op(x)
+ torch.cuda.synchronize()
+ outputs = []
+ sites = sync_sites(lambda: outputs.append(op(x)))
+ assert not set(sites) - INHERENT_SITES.keys(), dict(sites)
+ outputs[0].sum().backward()
+ assert all(p.grad is not None for p in op.parameters())
+
@pytest.mark.parametrize("same_on_batch", [False, True])
@pytest.mark.parametrize("p", [0.0, 0.5, 1.0])
@pytest.mark.parametrize("name", sorted(_GATED))
diff --git a/tests/core/test_onnx_mixin.py b/tests/core/test_onnx_mixin.py
index 71c87e9a1..ef195634d 100644
--- a/tests/core/test_onnx_mixin.py
+++ b/tests/core/test_onnx_mixin.py
@@ -131,7 +131,14 @@ _NOT_CALL_STATE = {
"the enclosing AugmentationSequential reads it right after this image call, in the same call",
),
"_BasicAugmentationBase.set_rng_device_and_dtype": (("device", "dtype"), "called by .to(), not by a call"),
- "RandomGeneratorBase.set_rng_device_and_dtype": (("device", "dtype"), "called by .to(), not by a call"),
+ "RandomGeneratorBase.set_rng_device_and_dtype": (
+ ("device", "dtype", "_sampler_attrs"),
+ "called by .to(), not by a call; _sampler_attrs names the samplers for __getstate__ and __setstate__",
+ ),
+ "RandomGeneratorBase.__setstate__": (
+ ("device",),
+ "unpickling; the samplers it rebuilds follow torch.load's map_location",
+ ),
"RandomTransplantation.params_from_input": (
("excluded_labels",),
"a constructor argument moved to the mask's device; its values never change",