π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
fix(augmentation): invalidate stale transform matrix cache (#5854)
Karnajeet Gosavi8130f7b3f9a6
diff --git a/changelog.d/5854.fixed.md b/changelog.d/5854.fixed.mdnew file mode 100644index 000000000..2a6afd83b--- /dev/null+++ b/changelog.d/5854.fixed.md@@ -0,0 +1 @@+`AugmentationSequential` annotation-only replays and `inverse` calls now recompute a geometric child's transform matrix when a value in the params dict was replaced or edited in place after the image call, instead of reusing the image call's matrix (#5846).diff --git a/docs/source/augmentation.base.rst b/docs/source/augmentation.base.rstindex 3dd519a1c..fe2017648 100644--- a/docs/source/augmentation.base.rst+++ b/docs/source/augmentation.base.rst@@ -49,8 +49,10 @@ Kornia augmentations generally follow a `sample-apply` routine.and transforms of other data modalities (`data keys` in Kornia) such as masks, keypoints, and bounding boxes.These features depend on the concrete operation and its data-key handlers. `AugmentationSequential` passes thematrix of the call's parameters to the mask, box and keypoint handlers of geometric children and of custom- `RigidAffineAugmentationBase2D` subclasses, recomputing it from replayed ``params`` that the child did not last apply to an image. Non-rigid coordinate transforms are not supplied automatically- (`#4420 <https://github.com/kornia/kornia/issues/4420>`_).+ `RigidAffineAugmentationBase2D` subclasses, recomputing it from replayed ``params`` that the child did not last+ apply to an image or that were edited since. An in-place edit made inside ``torch.inference_mode`` is not seen,+ because inference tensors have no version counter; replace the value instead. Non-rigid coordinate transforms+ are not supplied automatically (`#4420 <https://github.com/kornia/kornia/issues/4420>`_).Custom Augmentation Classes---------------------------diff --git a/kornia/augmentation/_2d/base.py b/kornia/augmentation/_2d/base.pyindex 29a7f76d2..ee764443a 100644--- a/kornia/augmentation/_2d/base.py+++ b/kornia/augmentation/_2d/base.py@@ -25,7 +25,7 @@ from torch import float16, float32, float64from kornia.augmentation.base import _AugmentationBasefrom kornia.augmentation.utils import _transform_input, _transform_input_by_shape, _validate_input_dtypefrom kornia.core.ops import eye_like-from kornia.core.utils import is_autocast_enabled, is_exporting+from kornia.core.utils import is_autocast_enabled, is_compiling, is_exportingfrom kornia.geometry.boxes import Boxesfrom kornia.geometry.keypoints import Keypoints@@ -175,6 +175,41 @@ class RigidAffineAugmentationBase2D(AugmentationBase2D):_compute_matrix_lazily: bool = False_lazy_matrix_args: Optional[_LazyMatrixArgs] = None_transform_matrix_params: Optional[Dict[str, Any]] = None+ _transform_matrix_params_snapshot: Optional[Tuple[Tuple[str, Any, int], ...]] = None++ @staticmethod+ def _params_snapshot(params: Dict[str, Any]) -> Tuple[Tuple[str, Any, int], ...]:+ """Return each value of ``params`` with the version counter of each tensor value.++ The values themselves are kept, not their ``id()``: a replaced tensor that is freed can hand its address to the+ next tensor. An inference tensor has no version counter, so only its replacement is seen, not an in-place edit+ made inside ``torch.inference_mode``.+ """+ return tuple(+ (key, value, value._version if isinstance(value, torch.Tensor) and not value.is_inference() else -1)+ for key, value in params.items()+ )++ def _matrix_matches_params(self, params: Dict[str, Any]) -> bool:+ """Whether the recorded matrix was computed from ``params`` as they are now, not before a caller edited them."""+ if self._transform_matrix_params is not params:+ return False+ recorded = self._transform_matrix_params_snapshot+ if recorded is None:+ # An image call inside a Dynamo capture records no snapshot: Dynamo cannot trace ``is_inference`` and reads+ # each version counter as a new unbacked symbol. Within one compiled call nothing edits the params between+ # the image and its annotations, so the dict's identity is enough there.+ return is_compiling()+ current = self._params_snapshot(params)+ if len(recorded) != len(current):+ return False+ return all(k0 == k1 and v0 is v1 and n0 == n1 for (k0, v0, n0), (k1, v1, n1) in zip(recorded, current))++ def _record_matrix_params(self, params: Dict[str, Any]) -> None:+ """Record the params dict the image call was given, and its values, next to the matrix computed from it."""+ if not is_exporting():+ self._transform_matrix_params = params+ self._transform_matrix_params_snapshot = None if is_compiling() else self._params_snapshot(params)@propertydef transform_matrix(self) -> Optional[torch.Tensor]:@@ -286,10 +321,9 @@ class RigidAffineAugmentationBase2D(AugmentationBase2D):if flags is None:flags = self.flags# ``forward`` committed the caller's params dict as ``_params`` before overriding a copy for this call (and- # ``transform_inputs`` commits that copy). Pair the caller's dict with the matrix, so the container's annotation- # handlers can tell a replay of this draw from another one by identity.+ # ``transform_inputs`` commits that copy). Pair the caller's dict and a snapshot of its values with the matrix,+ # so the container's annotation handlers can tell a replay of this draw from another draw or an edited dict.matrix_params = self._params-if self._compute_matrix_lazily:# 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@@ -309,14 +343,12 @@ class RigidAffineAugmentationBase2D(AugmentationBase2D):# 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))- if not is_exporting():- self._transform_matrix_params = matrix_params+ self._record_matrix_params(matrix_params)return self.transform_inputs(in_tensor, params, flags, None)trans_matrix = self.generate_transformation_matrix(in_tensor, params, flags)output = self.transform_inputs(in_tensor, params, flags, trans_matrix)self._commit_state(transform_matrix=trans_matrix, lazy_matrix_args=None)- if not is_exporting():- self._transform_matrix_params = matrix_params+ self._record_matrix_params(matrix_params)return outputdiff --git a/kornia/augmentation/container/augment.py b/kornia/augmentation/container/augment.pyindex 2a3615ce0..9d6523f00 100644--- a/kornia/augmentation/container/augment.py+++ b/kornia/augmentation/container/augment.py@@ -164,8 +164,10 @@ class AugmentationSequential(TransformMatrixMinIn, ImageSequential):cannot recover pixels moved out of the frame.- the ``mask``, box and ``keypoints`` handlers of a geometric child, or of a custom:class:`~kornia.augmentation.RigidAffineAugmentationBase2D` subclass, receive the transform of the- call's ``params``: the one the child recorded when it last transformed an image with those params, or- else one recomputed from them, so a replay without the image or after a newer draw follows ``params``.+ call's ``params``: the one the child recorded when it last transformed an image with those params, while no+ value in them has been replaced or edited in place, or else one recomputed from them, so a replay without+ the image, after a newer draw or after an edit follows ``params``. Inference tensors have no version+ counter, so an in-place edit made inside ``torch.inference_mode`` is not seen; replace the value instead.The mask limitations above apply; a handler the subclass does not implement raises``NotImplementedError``. A non-rigid warp child has no matrix, so the coordinate keys are left unchanged;see the warning below.diff --git a/kornia/augmentation/container/ops.py b/kornia/augmentation/container/ops.pyindex 287442cd9..f15c0dc2f 100644--- a/kornia/augmentation/container/ops.py+++ b/kornia/augmentation/container/ops.py@@ -64,9 +64,11 @@ class SequentialOpsInterface(Generic[T], metaclass=ABCMeta):def get_transform_matrix(cls, module: nn.Module, param: ParamItem, input: Any) -> torch.Tensor:"""Get the matrix recorded by these params, not by the module's most recent image call."""params = cls.get_instance_module_param(param)- # The image call records the params dict it was given next to the matrix it computed from it. The same dict- # object is the same draw, so the recorded matrix is reused; other params are replayed from their values.- if not is_exporting() and getattr(module, "_transform_matrix_params", None) is params:+ # The image call records the params dict it was given, and its values and their versions, next to the matrix+ # it computed. The matrix is reused while the dict holds the same values unedited: the annotations of the same+ # draw share it, and a replay after a caller replaced or edited a value is recomputed from the values.+ matches = getattr(module, "_matrix_matches_params", None)+ if not is_exporting() and matches is not None and matches(params):transform = getattr(module, "transform_matrix", None)if transform is not None:return transformdiff --git a/tests/augmentation/container/test_augmentation_sequential.py b/tests/augmentation/container/test_augmentation_sequential.pyindex 760ba183e..e0080c2a8 100644--- a/tests/augmentation/container/test_augmentation_sequential.py+++ b/tests/augmentation/container/test_augmentation_sequential.py@@ -2847,6 +2847,69 @@ class TestConventionAugmentationSequential(BaseTester):class TestAugmentationSequentialReplay:+ @pytest.mark.parametrize("edit_in_place", [False, True])+ def test_annotation_replay_uses_edited_params(self, device, dtype, edit_in_place):+ with torch.random.fork_rng(devices=[device] if device.type == "cuda" else []):+ torch.manual_seed(0)+ image = torch.rand(2, 1, 16, 16, device=device, dtype=dtype)+ keypoints = torch.tensor([[[3.0, 4.0]], [[3.0, 4.0]]], device=device, dtype=dtype)+ aug = K.AugmentationSequential(K.RandomAffine(30.0, p=0.5), data_keys=["input", "keypoints"])+ params = aug.forward_parameters(image.shape)+ first_gate = torch.tensor([True, False], device=device)+ second_gate = torch.tensor([False, True], device=device)+ params[0].data["batch_prob"] = first_gate.clone()+ aug(image, keypoints, params=params)++ if edit_in_place:+ params[0].data["batch_prob"][:] = second_gate+ else:+ params[0].data["batch_prob"] = second_gate++ replayed = aug(keypoints, params=params, data_keys=["keypoints"])+ moved = [(replayed[i] - keypoints[i]).abs().max() > 1e-4 for i in range(2)]+ assert [bool(value) for value in moved] == [False, True]++ def test_annotation_replay_after_repeated_replacements(self, device, dtype):+ # Each replacement frees the previous tensor, and the next one can take its address, so a cache keyed by+ # ``id()`` would see the tensor recorded by the image call again. Repeat to make an address reuse likely.+ image = torch.rand(2, 1, 16, 16, device=device, dtype=dtype)+ keypoints = torch.tensor([[[3.0, 4.0]], [[9.0, 12.0]]], device=device, dtype=dtype)+ aug = K.AugmentationSequential(K.RandomAffine(30.0, p=1.0), data_keys=["input", "keypoints"])+ for _ in range(10):+ params = aug.forward_parameters(image.shape)+ aug(image, keypoints, params=params)+ params[0].data["angle"] = params[0].data["angle"] * 0+ params[0].data["angle"] = params[0].data["angle"] + 10.0+ replayed = aug(keypoints, params=params, data_keys=["keypoints"])+ _, expected = aug(image, keypoints, params=params)+ assert_close(replayed, expected)++ def test_annotation_replay_with_inference_tensors(self, monkeypatch):+ # Inference tensors have no version counter: a replaced value is still seen, and the annotations of one call+ # still share the image's matrix instead of recomputing one each.+ calls = []+ generate = K.RandomAffine.generate_transformation_matrix++ def counted(self, *args, **kwargs):+ calls.append(None)+ return generate(self, *args, **kwargs)++ monkeypatch.setattr(K.RandomAffine, "generate_transformation_matrix", counted)+ with torch.inference_mode():+ image = torch.rand(2, 1, 16, 16)+ keypoints = torch.tensor([[[3.0, 4.0]], [[3.0, 4.0]]])+ boxes = torch.tensor([[[2.0, 4.0, 6.0, 8.0]]]).expand(2, -1, -1)+ data_keys = ["input", "mask", "bbox_xyxy", "keypoints"]+ aug = K.AugmentationSequential(K.RandomAffine(30.0, p=0.5), data_keys=data_keys)+ params = aug.forward_parameters(image.shape)+ params[0].data["batch_prob"] = torch.tensor([True, False])+ aug(image, image, boxes, keypoints, params=params)+ assert len(calls) == 1+ params[0].data["batch_prob"] = torch.tensor([False, True])+ replayed = aug(keypoints, params=params, data_keys=["keypoints"])+ moved = [(replayed[i] - keypoints[i]).abs().max() > 1e-4 for i in range(2)]+ assert [bool(value) for value in moved] == [False, True]+def test_annotation_replay_uses_matrices_from_params(self, device, dtype):with torch.random.fork_rng(devices=[device] if device.type == "cuda" else []):torch.manual_seed(0)diff --git a/tests/augmentation/test_augmentation_compile.py b/tests/augmentation/test_augmentation_compile.pyindex 2dead5c4e..b06743747 100644--- a/tests/augmentation/test_augmentation_compile.py+++ b/tests/augmentation/test_augmentation_compile.py@@ -478,3 +478,45 @@ class TestContainerCompile(BaseTester):self.assert_close(out_video, video.flip(-1))self.assert_close(out_mask, mask.expand(2, -1, -1, -1, -1).flip(-1))assert counter.frame_count == 1++ @pytest.mark.skipif(not dynamo_is_available(), reason="no Dynamo on this torch/python pair")+ def test_eager_replay_after_a_traced_image_call_follows_edited_params(self, device, dtype):+ # A traced image call cannot snapshot its params, so an eager replay recomputes from the edited dict.+ torch._dynamo.reset()+ image = torch.rand(2, 1, 16, 16, device=device, dtype=dtype)+ keypoints = torch.tensor([[[3.0, 4.0]], [[9.0, 12.0]]], device=device, dtype=dtype)+ aug = K.AugmentationSequential(K.RandomAffine(30.0, p=1.0), data_keys=["input", "keypoints"])+ params = aug.forward_parameters(image.shape)+ torch.compile(aug, backend=CompileCounter())(image, keypoints, params=params)+ params[0].data["angle"][:] = torch.tensor([0.0, 25.0], device=device, dtype=dtype)+ replayed = aug(keypoints, params=params, data_keys=["keypoints"])+ _, expected = aug(image, keypoints, params=params)+ self.assert_close(replayed, expected)++ def test_dynamo_sequential_annotations_share_the_image_matrix(self, device, dtype, torch_optimizer):+ # Recomputing from ``forward_input_shape`` makes the matrix batch size data-dependent inside fullgraph capture.+ aug = K.AugmentationSequential(+ K.RandomAffine(30.0, p=1.0), K.RandomHorizontalFlip(p=1.0), data_keys=["input", "mask", "keypoints"]+ )+ image = torch.rand(2, 3, 8, 8, device=device, dtype=dtype)+ keypoints = torch.tensor([[[1.0, 2.0], [5.0, 6.0]]], device=device, dtype=dtype).expand(2, -1, -1)+ out_image, out_mask, out_keypoints = torch_optimizer(aug, fullgraph=True)(image, image[:, :1], keypoints)+ assert out_image.shape == image.shape+ assert out_mask.shape == (2, 1, 8, 8)+ assert out_keypoints.shape == keypoints.shape++ @pytest.mark.skipif(not dynamo_is_available(), reason="no Dynamo on this torch/python pair")+ def test_traced_replay_of_another_draw_after_a_traced_image_call(self, device, dtype):+ # A traced image call records its params dict without a snapshot. A traced replay of another draw still has to+ # see that its dict is not the recorded one and recompute, instead of reusing the image call's matrix.+ torch._dynamo.reset()+ image = torch.rand(2, 1, 16, 16, device=device, dtype=dtype)+ keypoints = torch.tensor([[[3.0, 4.0]], [[9.0, 12.0]]], device=device, dtype=dtype)+ aug = K.AugmentationSequential(K.RandomAffine(30.0, p=1.0), data_keys=["input", "keypoints"])+ params = aug.forward_parameters(image.shape)+ other = aug.forward_parameters(image.shape)+ traced = torch.compile(aug, backend=CompileCounter())+ traced(image, keypoints, params=params)+ replayed = traced(keypoints, params=other, data_keys=["keypoints"])+ _, expected = aug(image, keypoints, params=other)+ self.assert_close(replayed, expected)