π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
fix(augmentation): avoid retaining images for lazy transform matrices (#4484)
Zhenhuan Wangb5a3ef0e841f
diff --git a/changelog.d/4484.fixed.md b/changelog.d/4484.fixed.mdnew file mode 100644index 000000000..8f93bf011--- /dev/null+++ b/changelog.d/4484.fixed.md@@ -0,0 +1,5 @@+Built-in 2D augmentations with lazy transformation matrices retain input metadata instead of the+last image batch, preventing unnecessary tensor lifetime extension and image-sized pickle,+deepcopy and torch.save payloads. Custom matrix implementations that read pixels retain their+existing lazy behavior. Cached metadata remains compatible with non-strict torch.export and+ONNX export after an eager forward.diff --git a/docs/source/augmentation.base.rst b/docs/source/augmentation.base.rstindex 51d4a59b3..326745c62 100644--- a/docs/source/augmentation.base.rst+++ b/docs/source/augmentation.base.rst@@ -244,7 +244,20 @@ Several constructors accept ``nn.Parameter`` ranges and can propagate gradientsare not necessarily connected to cached samplers after ``load_state_dict``; reconstruct those configurationsto change their sampling ranges (`#4428 <https://github.com/kornia/kornia/issues/4428>`_).-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>`_).+The ``kornia.augmentation.auto`` policies cannot be pickled (`#4469 <https://github.com/kornia/kornia/issues/4469>`_).++The built-in 2D intensity augmentations, flips, ``Resize`` (including ``LongestMaxSize`` and+``SmallestMaxSize``), and slice-mode ``RandomResizedCrop`` compute their transformation matrix+only when it is requested. Their pending matrix state keeps the input's shape, dtype and device+alongside the transformation parameters, without retaining the image tensor itself. Consequently,+``pickle``, ``copy.deepcopy`` and ``torch.save`` of these modules do not carry the last image batch+merely because its matrix has not yet been read. Parameters remain available for replay, including+their existing gradient connections.++Custom lazy subclasses may use pixel values in ``transform_tensor``, ``generate_transformation_matrix``,+``compute_transformation`` or ``identity_matrix``. Overriding any of these four methods keeps the+original input-based lazy behavior, retaining the input until the matrix is read or another forward+replaces the pending state. Inheriting unchanged built-in implementations preserves their compact+metadata state; an override does not implicitly promise that it can operate without pixel data.+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.rstindex c9e480f26..d900d15df 100644--- a/docs/source/get-started/conventions.rst+++ b/docs/source/get-started/conventions.rst@@ -348,11 +348,16 @@ Serializing an augmentation- Pickle and deepcopy can retain recorded parameters and transform 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>`_).+ (`#4469 <https://github.com/kornia/kornia/issues/4469>`_).A normal forward draws fresh parameters; replay requires passing thesaved parameters and controlling any application-time randomness.+- Built-in lazy matrices keep only the input's shape, dtype and device+ alongside transformation parameters, so an unread matrix does not keep+ the image batch in the saved state. A lazy subclass overriding ``transform_tensor``,+ ``generate_transformation_matrix``, ``compute_transformation`` or+ ``identity_matrix`` retains the input until the matrix is read or another+ forward replaces the pending state. Unchanged inherited implementations+ keep the compact metadata state. See :doc:`/augmentation.base` for details.Pitfall checklist-----------------diff --git a/kornia/augmentation/_2d/base.py b/kornia/augmentation/_2d/base.pyindex a74c78e62..ee739a1bf 100644--- a/kornia/augmentation/_2d/base.py+++ b/kornia/augmentation/_2d/base.py@@ -15,7 +15,9 @@# limitations under the License.#-from typing import Any, Dict, Optional, Tuple+from __future__ import annotations++from typing import Any, Callable, Dict, NamedTuple, Optional, Tuple, TypeVar, Unionimport torchfrom torch import float16, float32, float64@@ -27,6 +29,33 @@ from kornia.core.utils import is_autocast_enabledfrom kornia.geometry.boxes import Boxesfrom kornia.geometry.keypoints import Keypoints+_F = TypeVar("_F", bound=Callable[..., torch.Tensor])+++def _input_metadata_only(method: _F) -> _F:+ """Mark an implementation that only reads the input's shape, dtype and device.++ Store the function itself, not a boolean: an override (including a wrapper that+ copies function attributes) must not inherit another implementation's promise.+ Overridable callees in the matrix path are checked separately.+ """+ method.__dict__["_kornia_input_metadata_only"] = method+ return method+++class _InputMetadata(NamedTuple):+ shape: Tuple[int, ...]+ dtype: torch.dtype+ device: torch.device++ def materialize(self) -> torch.Tensor:+ # These implementations never read pixels. Allocate one element only when+ # the matrix is requested, preserving the original shape without its storage.+ return torch.empty((), dtype=self.dtype, device=self.device).expand(self.shape)+++_LazyMatrixArgs = Tuple[Union[torch.Tensor, _InputMetadata], Dict[str, torch.Tensor], Dict[str, Any]]+class AugmentationBase2D(_AugmentationBase):r"""AugmentationBase2D base class for customized augmentation implementations.@@ -78,8 +107,11 @@ class AugmentationBase2D(_AugmentationBase):since it is drawn into ``_params``, except for :class:`RandomDissolving`, which samples VAE latentsduring 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>`_), and saved- state can retain data from the last call (`#4482 <https://github.com/kornia/kornia/issues/4482>`_).+ ``load_state_dict`` (tracked in `#4428 <https://github.com/kornia/kornia/issues/4428>`_). Built-in lazy+ matrix state keeps only the input's shape, dtype and device alongside the transformation parameters.+ Lazy subclasses overriding ``transform_tensor``, ``generate_transformation_matrix``,+ ``compute_transformation`` or ``identity_matrix`` retain the input until the matrix is read or another+ forward replaces the state.- an empty batch is an empty output on the classes that accept one, but it is not a package-wideguarantee: a minority of the classes raise on ``B = 0``, in several unrelated exception families.- rotation-like parameters are in degrees, and a positive angle turns the image counter-clockwise as@@ -126,6 +158,7 @@ class AugmentationBase2D(_AugmentationBase):if len(input.shape) != 4:raise RuntimeError(f"Expect (B, C, H, W). Got {input.shape}.")+ @_input_metadata_onlydef transform_tensor(self, input: torch.Tensor, *, shape: Optional[torch.Tensor] = None, match_channel: bool = True) -> torch.Tensor:@@ -162,8 +195,11 @@ class RigidAffineAugmentationBase2D(AugmentationBase2D):recognizes geometric children, so custom rigid subclasses need integration work of their own. See`#4481 <https://github.com/kornia/kornia/issues/4481>`_.- the matrix of the last call is readable as ``transform_matrix``. Subclasses opt into lazy construction- with ``_compute_matrix_lazily``; retained state has the serialization limitations in `#4482- <https://github.com/kornia/kornia/issues/4482>`_.+ with ``_compute_matrix_lazily``. Built-in lazy matrices keep only the input's shape, dtype and device+ alongside the transformation parameters. Lazy subclasses overriding ``transform_tensor``,+ ``generate_transformation_matrix``, ``compute_transformation`` or ``identity_matrix`` keep the input+ until the matrix is read or another forward replaces the state; unchanged inherited implementations+ keep the compact metadata state.- this base does not implement an inverse operation."""@@ -173,16 +209,18 @@ class RigidAffineAugmentationBase2D(AugmentationBase2D):# the image output never reads it, so building it every forward is pure overhead. When True,# ``apply_func`` defers the matrix and ``transform_matrix`` computes it on first access._compute_matrix_lazily: bool = False- _lazy_matrix_args: Optional[Tuple[torch.Tensor, Dict[str, torch.Tensor], Dict[str, Any]]] = None+ _lazy_matrix_args: Optional[_LazyMatrixArgs] = None@propertydef transform_matrix(self) -> Optional[torch.Tensor]:if self._transform_matrix is None and self._lazy_matrix_args is not None:- in_tensor, params, flags = self._lazy_matrix_args+ matrix_input, params, flags = self._lazy_matrix_args+ in_tensor = matrix_input.materialize() if isinstance(matrix_input, _InputMetadata) else matrix_inputself._transform_matrix = self.generate_transformation_matrix(in_tensor, params, flags)self._lazy_matrix_args = Nonereturn self._transform_matrix+ @_input_metadata_onlydef identity_matrix(self, input: torch.Tensor) -> torch.Tensor:"""Return 3x3 identity matrix."""return eye_like(3, input)@@ -192,6 +230,7 @@ class RigidAffineAugmentationBase2D(AugmentationBase2D):) -> torch.Tensor:raise NotImplementedError+ @_input_metadata_onlydef generate_transformation_matrix(self, input: torch.Tensor, params: Dict[str, torch.Tensor], flags: Dict[str, Any]) -> torch.Tensor:@@ -286,7 +325,21 @@ class RigidAffineAugmentationBase2D(AugmentationBase2D):# apply_transform ignores the matrix for these ops, so don't build it here; defer to# the first `.transform_matrix` access (e.g. AugmentationSequential propagating to# boxes/keypoints/masks). A standalone flip that never reads the matrix skips it.- self._commit_state(transform_matrix=None, lazy_matrix_args=(in_tensor, params, flags))+ matrix_input: Union[torch.Tensor, _InputMetadata] = in_tensor+ # Check the implementations, not the class: custom overrides may read+ # pixels even when they inherit the built-in's lazy-computation flag.+ if all(+ getattr(method, "_kornia_input_metadata_only", None) is getattr(method, "__func__", method)+ for method in (+ self.transform_tensor,+ self.generate_transformation_matrix,+ self.compute_transformation,+ self.identity_matrix,+ )+ ):+ # PyTorch 2.5 snapshots torch.Size as a tuple during non-strict export.+ matrix_input = _InputMetadata(tuple(in_tensor.shape), in_tensor.dtype, in_tensor.device)+ self._commit_state(transform_matrix=None, lazy_matrix_args=(matrix_input, params, flags))return self.transform_inputs(in_tensor, params, flags, None)trans_matrix = self.generate_transformation_matrix(in_tensor, params, flags)diff --git a/kornia/augmentation/_2d/geometric/horizontal_flip.py b/kornia/augmentation/_2d/geometric/horizontal_flip.pyindex 62d382b29..5fd118ca2 100644--- a/kornia/augmentation/_2d/geometric/horizontal_flip.py+++ b/kornia/augmentation/_2d/geometric/horizontal_flip.py@@ -20,6 +20,7 @@ from typing import Any, Dict, Optional, Tupleimport torch# from torch import Tensor (use torch.Tensor instead)+from kornia.augmentation._2d.base import _input_metadata_onlyfrom kornia.augmentation._2d.geometric.base import GeometricAugmentationBase2Dfrom kornia.geometry.transform import hflip@@ -77,6 +78,7 @@ class RandomHorizontalFlip(GeometricAugmentationBase2D):# it until `.transform_matrix` is read (see RigidAffineAugmentationBase2D)._compute_matrix_lazily = True+ @_input_metadata_onlydef compute_transformation(self, input: torch.Tensor, params: Dict[str, torch.Tensor], flags: Dict[str, Any]) -> torch.Tensor:diff --git a/kornia/augmentation/_2d/geometric/resize.py b/kornia/augmentation/_2d/geometric/resize.pyindex b19d3338a..7090038e1 100644--- a/kornia/augmentation/_2d/geometric/resize.py+++ b/kornia/augmentation/_2d/geometric/resize.py@@ -20,6 +20,7 @@ from typing import Any, Dict, Optional, Tuple, Unionimport torchfrom kornia.augmentation import random_generator as rg+from kornia.augmentation._2d.base import _input_metadata_onlyfrom kornia.augmentation._2d.geometric.base import GeometricAugmentationBase2Dfrom kornia.constants import Resamplefrom kornia.core.utils import is_exporting@@ -66,6 +67,7 @@ class Resize(GeometricAugmentationBase2D):# matrix build (which needs a linalg solve) until `.transform_matrix` is read._compute_matrix_lazily = True+ @_input_metadata_onlydef compute_transformation(self, input: torch.Tensor, params: Dict[str, torch.Tensor], flags: Dict[str, Any]) -> torch.Tensor:diff --git a/kornia/augmentation/_2d/geometric/resized_crop.py b/kornia/augmentation/_2d/geometric/resized_crop.pyindex 32c171d68..8557df054 100644--- a/kornia/augmentation/_2d/geometric/resized_crop.py+++ b/kornia/augmentation/_2d/geometric/resized_crop.py@@ -20,6 +20,7 @@ from typing import Any, Dict, Optional, Tuple, Unionimport torchfrom kornia.augmentation import random_generator as rg+from kornia.augmentation._2d.base import _input_metadata_onlyfrom kornia.augmentation._2d.geometric.base import GeometricAugmentationBase2Dfrom kornia.constants import Resamplefrom kornia.geometry.transform import crop_by_indices, crop_by_transform_mat, get_perspective_transform@@ -107,6 +108,7 @@ class RandomResizedCrop(GeometricAugmentationBase2D):# "resample" mode warps through the matrix, so it must be built eagerly.self._compute_matrix_lazily = cropping_mode == "slice"+ @_input_metadata_onlydef compute_transformation(self, input: torch.Tensor, params: Dict[str, torch.Tensor], flags: Dict[str, Any]) -> torch.Tensor:diff --git a/kornia/augmentation/_2d/geometric/vertical_flip.py b/kornia/augmentation/_2d/geometric/vertical_flip.pyindex 0de73f8ed..43d38c3c5 100644--- a/kornia/augmentation/_2d/geometric/vertical_flip.py+++ b/kornia/augmentation/_2d/geometric/vertical_flip.py@@ -19,6 +19,7 @@ from typing import Any, Dict, Optional, Tupleimport torch+from kornia.augmentation._2d.base import _input_metadata_onlyfrom kornia.augmentation._2d.geometric.base import GeometricAugmentationBase2Dfrom kornia.geometry.transform import vflip@@ -68,6 +69,7 @@ class RandomVerticalFlip(GeometricAugmentationBase2D):# it until `.transform_matrix` is read (see RigidAffineAugmentationBase2D)._compute_matrix_lazily = True+ @_input_metadata_onlydef compute_transformation(self, input: torch.Tensor, params: Dict[str, torch.Tensor], flags: Dict[str, Any]) -> torch.Tensor:diff --git a/kornia/augmentation/_2d/intensity/base.py b/kornia/augmentation/_2d/intensity/base.pyindex e0aa7e526..18e47963e 100644--- a/kornia/augmentation/_2d/intensity/base.py+++ b/kornia/augmentation/_2d/intensity/base.py@@ -19,7 +19,7 @@ from typing import Any, Dict, Optionalfrom torch import Tensor-from kornia.augmentation._2d.base import RigidAffineAugmentationBase2D+from kornia.augmentation._2d.base import RigidAffineAugmentationBase2D, _input_metadata_onlyfrom kornia.geometry.boxes import Boxesfrom kornia.geometry.keypoints import Keypoints@@ -58,6 +58,7 @@ class IntensityAugmentationBase2D(RigidAffineAugmentationBase2D):# `.transform_matrix` is read, saving an eye_like + blend on every forward._compute_matrix_lazily = True+ @_input_metadata_onlydef compute_transformation(self, input: Tensor, params: Dict[str, Tensor], flags: Dict[str, Any]) -> Tensor:return self.identity_matrix(input)diff --git a/tests/augmentation/test_lazy_matrix.py b/tests/augmentation/test_lazy_matrix.pynew file mode 100644index 000000000..eb57976e6--- /dev/null+++ b/tests/augmentation/test_lazy_matrix.py@@ -0,0 +1,283 @@+# LICENSE HEADER MANAGED BY add-license-header+#+# Copyright 2018 Kornia Team+#+# Licensed under the Apache License, Version 2.0 (the "License");+# you may not use this file except in compliance with the License.+# You may obtain a copy of the License at+#+# http://www.apache.org/licenses/LICENSE-2.0+#+# Unless required by applicable law or agreed to in writing, software+# distributed under the License is distributed on an "AS IS" BASIS,+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+# See the License for the specific language governing permissions and+# limitations under the License.+#++from __future__ import annotations++import copy+import gc+import io+import pickle+import weakref+from functools import wraps++import pytest+import torch++import kornia.augmentation as K++from testing.base import BaseTester+++class ContentAwareFlip(K.RandomHorizontalFlip):+ """Flip bright images only; both pixels and coordinates depend on the input."""++ def compute_transformation(self, input, params, flags):+ matrix = super().compute_transformation(input, params, flags)+ selected = input.mean(dim=(1, 2, 3)) > 0.5+ return torch.where(selected[:, None, None], matrix, self.identity_matrix(input))++ def apply_transform(self, input, params, flags, transform=None):+ selected = input.mean(dim=(1, 2, 3)) > 0.5+ return torch.where(selected[:, None, None, None], input.flip(-1), input)+++class WrappedContentAwareFlip(ContentAwareFlip):+ # functools.wraps copies function attributes; it must not make a new implementation+ # inherit a promise about whether the original implementation reads pixels.+ @wraps(K.RandomHorizontalFlip.compute_transformation)+ def compute_transformation(self, input, params, flags):+ return super().compute_transformation(input, params, flags)+++class InheritedFlip(K.RandomHorizontalFlip):+ pass+++def make_augmentation(name):+ factories = {+ "hflip": lambda: K.RandomHorizontalFlip(p=1.0),+ "vflip": lambda: K.RandomVerticalFlip(p=1.0),+ "invert": lambda: K.RandomInvert(p=1.0),+ "brightness": lambda: K.RandomBrightness((1.1, 1.1), p=1.0),+ "resize": lambda: K.Resize((4, 6)),+ "longest": lambda: K.LongestMaxSize(6),+ "smallest": lambda: K.SmallestMaxSize(4),+ "resized_crop": lambda: K.RandomResizedCrop((4, 6), scale=(0.8, 0.8), cropping_mode="slice"),+ "inherited_flip": lambda: InheritedFlip(p=1.0),+ }+ return factories[name]()+++LAZY_OPS = ["hflip", "vflip", "invert", "brightness", "resize", "longest", "smallest", "resized_crop", "inherited_flip"]+++class TestLazyMatrixState(BaseTester):+ @pytest.mark.device_agnostic+ @pytest.mark.parametrize("name", ["hflip", "invert", "longest"])+ def test_export_with_unread_matrix(self, name):+ augmentation = make_augmentation(name).eval()+ input = torch.linspace(0, 1, 2 * 3 * 8 * 10).reshape(2, 3, 8, 10)+ expected = augmentation(input)+ # An eager call leaves pending metadata in the module's state. PyTorch 2.5's+ # non-strict exporter must be able to snapshot it without reading the matrix.+ assert augmentation._transform_matrix is None+ assert augmentation._lazy_matrix_args is not None+ exported = torch.export.export(augmentation, (input,), strict=False).module()+ self.assert_close(exported(input), expected)+ other_input = input.flip(-1)+ self.assert_close(exported(other_input), augmentation(other_input))++ @pytest.mark.parametrize("name", LAZY_OPS)+ def test_forward_releases_input_4482(self, name, device, dtype):+ augmentation = make_augmentation(name)+ input = torch.linspace(0, 1, 2 * 3 * 8 * 10, device=device, dtype=dtype).reshape(2, 3, 8, 10)+ reference = weakref.ref(input)+ augmentation(input)+ assert augmentation._transform_matrix is None # matrix evaluation stays lazy+ del input+ gc.collect()+ assert reference() is None++ @pytest.mark.parametrize("serializer", ["pickle", "torch"])+ def test_serialized_size_does_not_scale_with_pixels_4482(self, serializer, device, dtype):+ sizes = []+ for side in (16, 128):+ augmentation = K.RandomHorizontalFlip(p=1.0)+ augmentation(torch.zeros(2, 3, side, side, device=device, dtype=dtype))+ if serializer == "pickle":+ payload = pickle.dumps(augmentation)+ else:+ stream = io.BytesIO()+ torch.save(augmentation, stream)+ payload = stream.getvalue()+ sizes.append(len(payload))+ # Leave room for protocol/metadata differences, but not another image's storage.+ assert sizes[1] < sizes[0] + 4096++ @pytest.mark.parametrize("augmentation_cls", [ContentAwareFlip, WrappedContentAwareFlip])+ def test_custom_pixel_dependent_matrix(self, augmentation_cls, device, dtype):+ augmentation = augmentation_cls(p=1.0)+ dark = torch.linspace(0, 0.4, 24, device=device, dtype=dtype).reshape(1, 1, 4, 6)+ input = torch.cat([dark, dark + 0.6])+ output = augmentation(input)+ assert augmentation._transform_matrix is None+ self.assert_close(output, torch.cat([dark, (dark + 0.6).flip(-1)]))+ expected = torch.tensor(+ [[[1, 0, 0], [0, 1, 0], [0, 0, 1]], [[-1, 0, 5], [0, 1, 0], [0, 0, 1]]],+ device=device,+ dtype=dtype,+ )+ self.assert_close(augmentation.transform_matrix, expected)++ @pytest.mark.parametrize(+ "method_name",+ ["transform_tensor", "generate_transformation_matrix", "compute_transformation", "identity_matrix"],+ )+ def test_custom_matrix_path_receives_real_pixels(self, method_name, device, dtype):+ input = torch.linspace(0, 1, 24, device=device, dtype=dtype).reshape(1, 1, 4, 6)+ original = getattr(K.RandomHorizontalFlip, method_name)+ calls = []++ def implementation(self, actual, *args, **kwargs):+ calls.append(True)+ torch.testing.assert_close(actual, input)+ return original(self, actual, *args, **kwargs)++ custom_cls = type("CustomMatrixPath", (K.RandomHorizontalFlip,), {method_name: implementation})+ augmentation = custom_cls(p=0.5)+ params = augmentation.forward_parameters(input.shape)+ params["batch_prob"] = torch.ones(1, device=device)+ augmentation(input, params=params)+ matrix = augmentation.transform_matrix+ assert calls+ expected = torch.tensor([[[-1, 0, 5], [0, 1, 0], [0, 0, 1]]], device=device, dtype=dtype)+ self.assert_close(matrix, expected)++ @pytest.mark.parametrize("name", LAZY_OPS)+ def test_replay_matches_eager_matrix_path(self, name, device, dtype):+ augmentation = make_augmentation(name)+ eager = copy.deepcopy(augmentation)+ eager._compute_matrix_lazily = False+ input = torch.linspace(0, 1, 2 * 3 * 8 * 10, device=device, dtype=dtype).reshape(2, 3, 10, 8).transpose(-1, -2)+ params = augmentation.forward_parameters(input.shape)+ rng = torch.get_rng_state()+ output = augmentation(input, params=params)+ assert torch.equal(torch.get_rng_state(), rng)+ assert augmentation._transform_matrix is None+ expected_output = eager(input, params=params)+ matrix = augmentation.transform_matrix+ assert matrix is not None+ assert matrix.dtype == dtype+ assert matrix.device == input.device+ self.assert_close(output, expected_output)+ self.assert_close(matrix, eager.transform_matrix)+ assert augmentation.transform_matrix is matrix+ self.assert_close(augmentation(input, params=params), output)++ @pytest.mark.parametrize("gate", [[0.0, 0.0], [1.0, 0.0], [1.0, 1.0]])+ def test_partial_batch_matrix_and_image(self, gate, device, dtype):+ augmentation = K.RandomHorizontalFlip(p=0.5)+ input = torch.arange(48, device=device, dtype=dtype).reshape(2, 1, 4, 6)+ params = augmentation.forward_parameters(input.shape)+ params["batch_prob"] = torch.tensor(gate) # CPU params also exercise accelerator placement.+ output = augmentation(input, params=params)+ expected_output = torch.stack([row.flip(-1) if selected else row for row, selected in zip(input, gate)])+ flip = torch.tensor([[-1, 0, 5], [0, 1, 0], [0, 0, 1]], device=device, dtype=dtype)+ identity = torch.eye(3, device=device, dtype=dtype)+ expected_matrix = torch.stack([flip if selected else identity for selected in gate])+ self.assert_close(output, expected_output)+ self.assert_close(augmentation.transform_matrix, expected_matrix)++ def test_next_call_replaces_cached_shape(self, device, dtype):+ augmentation = K.RandomHorizontalFlip(p=1.0)+ for shape in [(2, 1, 4, 6), (3, 1, 7, 9)]:+ augmentation(torch.zeros(shape, device=device, dtype=dtype))+ assert augmentation._transform_matrix is None+ expected = torch.tensor([[-1, 0, shape[-1] - 1], [0, 1, 0], [0, 0, 1]], device=device, dtype=dtype)+ self.assert_close(augmentation.transform_matrix, expected.expand(shape[0], 3, 3))++ @pytest.mark.parametrize("shape", [(4, 6), (1, 4, 6), (0, 1, 4, 6)])+ def test_unbatched_and_empty_input(self, shape, device, dtype):+ augmentation = K.RandomHorizontalFlip(p=1.0, keepdim=True)+ input = torch.zeros(shape, device=device, dtype=dtype)+ self.assert_close(augmentation(input), input)+ batch = 0 if len(shape) == 4 else 1+ expected = torch.tensor([[-1, 0, 5], [0, 1, 0], [0, 0, 1]], device=device, dtype=dtype).expand(batch, 3, 3)+ self.assert_close(augmentation.transform_matrix, expected)++ def test_input_gradient_and_graph_release(self, device, dtype):+ augmentation = K.RandomHorizontalFlip(p=1.0)+ leaf = torch.linspace(0, 1, 24, device=device, dtype=dtype).reshape(1, 1, 4, 6).requires_grad_()+ leaf_reference = weakref.ref(leaf)+ input = leaf.square()+ reference = weakref.ref(input)+ output = augmentation(input)+ output.sum().backward()+ self.assert_close(leaf.grad, 2 * leaf)+ del leaf, input, output+ gc.collect()+ assert reference() is None+ assert leaf_reference() is None+ assert augmentation.transform_matrix is not None++ def test_matrix_parameter_gradcheck(self, device):+ augmentation = K.Resize((3, 4))+ input = torch.zeros(1, 1, 5, 6, device=device, dtype=torch.float64)+ params = augmentation.forward_parameters(input.shape)+ params["src"] = params["src"].to(input)+ destination = params["dst"].to(input).requires_grad_()++ def matrix_from_destination(dst):+ augmentation(input, params={**params, "dst": dst})+ return augmentation.transform_matrix++ self.gradcheck(matrix_from_destination, (destination,))++ @pytest.mark.parametrize("mode", ["image", "silent", "skip"])+ def test_container_releases_input(self, mode, device, dtype):+ child = K.RandomHorizontalFlip(p=1.0)+ augmentation = (+ K.ImageSequential(child)+ if mode == "image"+ else K.AugmentationSequential(child, transformation_matrix_mode=mode)+ )+ input = torch.linspace(0, 1, 24, device=device, dtype=dtype).reshape(1, 1, 4, 6)+ reference = weakref.ref(input)+ output = augmentation(input)+ self.assert_close(output, input.flip(-1))+ del input, output+ gc.collect()+ assert reference() is None+ assert child.transform_matrix is not None++ def test_dynamo(self, device, dtype, torch_optimizer):+ augmentation = K.RandomHorizontalFlip(p=0.5)+ compiled = torch_optimizer(copy.deepcopy(augmentation))+ input = torch.arange(48, device=device, dtype=dtype).reshape(2, 1, 4, 6)+ params = augmentation.forward_parameters(input.shape)+ params["batch_prob"] = torch.tensor([1.0, 0.0])+ self.assert_close(compiled(input, params=params), augmentation(input, params=params))+ self.assert_close(compiled.transform_matrix, augmentation.transform_matrix)++ @pytest.mark.parametrize("serializer", ["pickle", "deepcopy", "torch"])+ def test_serialization_preserves_unread_matrix(self, serializer, device, dtype):+ augmentation = K.RandomHorizontalFlip(p=1.0)+ input = torch.arange(48, device=device, dtype=dtype).reshape(2, 1, 4, 6)+ output = augmentation(input)+ if serializer == "pickle":+ restored = pickle.loads(pickle.dumps(augmentation)) # noqa: S301+ elif serializer == "deepcopy":+ restored = copy.deepcopy(augmentation)+ else:+ stream = io.BytesIO()+ torch.save(augmentation, stream)+ stream.seek(0)+ restored = torch.load(stream, weights_only=False)+ assert restored._transform_matrix is None+ expected = torch.tensor([[-1, 0, 5], [0, 1, 0], [0, 0, 1]], device=device, dtype=dtype).expand(2, 3, 3)+ self.assert_close(restored.transform_matrix, expected)+ self.assert_close(restored(input, params=restored._params), output)