Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

fix(augmentation): Compose nested image-sequence matrices (#6415)

A Aswanth Raje292261c3673
diff --git a/changelog.d/6415.fixed.md b/changelog.d/6415.fixed.md
new file mode 100644
index 000000000..ff5f1546a
--- /dev/null
+++ b/changelog.d/6415.fixed.md
@@ -0,0 +1 @@
+`AugmentationSequential.transform_matrix` now includes geometric operations inside plain `ImageSequential` children in `silent` mode instead of omitting them. Each operation contributes its current matrix in execution order, including repeated sampled members. The `rigid` and `skip` modes retain their behavior.
diff --git a/docs/source/get-started/conventions.rst b/docs/source/get-started/conventions.rst
index 00d8a6a54..b7d8ee9a6 100644
--- a/docs/source/get-started/conventions.rst
+++ b/docs/source/get-started/conventions.rst
@@ -557,9 +557,10 @@ Augmentations
:class:`kornia.geometry.boxes.Boxes` (see *Bounding boxes* above). Flips use
integer pixel centres: ``x' = W - 1 - x``.
- Nested ``AugmentationSequential`` children contribute matrices from the
- current call. A plain ``ImageSequential`` child is still omitted from an
- outer ``AugmentationSequential`` matrix
- (`#4476 <https://github.com/kornia/kornia/issues/4476>`_).
+ current call under their own matrix mode. Plain ``ImageSequential`` children
+ contribute their geometric operations in ``silent`` mode, including repeated
+ members of a sampled sequence. ``rigid`` still rejects a plain image sequence,
+ and ``skip`` records no matrix.
- Dictionary keys match a data-key name exactly or before an ``_``/``-``
suffix, the longest match winning. Unrecognized keys are returned unchanged
as metadata, and the caller's dictionary is not modified.
diff --git a/kornia/augmentation/container/augment.py b/kornia/augmentation/container/augment.py
index bbbb31bc0..9f3523f60 100644
--- a/kornia/augmentation/container/augment.py
+++ b/kornia/augmentation/container/augment.py
@@ -17,7 +17,7 @@
import sys
import warnings
-from typing import Any, Dict, List, Literal, Optional, Sequence, Tuple, Union, cast
+from typing import Any, Dict, Iterator, List, Literal, Optional, Sequence, Tuple, Union, cast
import torch
from torch import nn
@@ -186,8 +186,9 @@ class AugmentationSequential(TransformMatrixMinIn, ImageSequential):
``True`` or ``False`` overrides it.
- Nested :class:`AugmentationSequential` children contribute the matrix they record for the current call
under their own ``transformation_matrix_mode``; one whose children are all non-rigid records none and is
- skipped. A plain :class:`ImageSequential` child is still omitted from the outer matrix
- (`#4476 <https://github.com/kornia/kornia/issues/4476>`_).
+ skipped. In ``silent`` mode, plain :class:`ImageSequential` children contribute their geometric operations,
+ using each operation's recorded parameters even when the sampled sequence repeats a member. The ``rigid``
+ mode still rejects a plain image sequence, and ``skip`` records no matrix.
.. note::
:class:`~kornia.augmentation.RandomElasticTransform`, :class:`~kornia.augmentation.RandomThinPlateSpline`
@@ -416,6 +417,60 @@ class AugmentationSequential(TransformMatrixMinIn, ImageSequential):
if matrix is not None:
self._transform_matrices.append(matrix)
+ @staticmethod
+ def _image_sequence_matrices(
+ container: ImageSequential,
+ params: List[ParamItem],
+ input: DataType,
+ extra_args: Optional[Dict[str, Any]] = None,
+ sequence_matrices: Optional[Iterator[Optional[torch.Tensor]]] = None,
+ ) -> Iterator[torch.Tensor]:
+ """Read invocation snapshots and parameter-aware geometric matrices from a plain image sequence."""
+ for param in params:
+ module = container.get_submodule(param.name)
+ if type(module) is ImageSequential:
+ yield from AugmentationSequential._image_sequence_matrices(
+ module, InputSequentialOps.get_sequential_module_param(param), input, extra_args, sequence_matrices
+ )
+ elif isinstance(module, AugmentationSequential):
+ if sequence_matrices is None and type(module) is AugmentationSequential:
+ if module._transformation_matrix_arg != "skip":
+ yield from AugmentationSequential._image_sequence_matrices(
+ module, InputSequentialOps.get_sequential_module_param(param), input, extra_args
+ )
+ else:
+ matrix = module.transform_matrix if sequence_matrices is None else next(sequence_matrices)
+ if matrix is not None:
+ yield matrix
+ elif isinstance(module, (RigidAffineAugmentationBase2D, RigidAffineAugmentationBase3D)):
+ yield InputSequentialOps.get_transform_matrix(module, param, input, extra_args=extra_args)
+
+ def _update_image_sequence_matrix(
+ self,
+ module: nn.Module,
+ param: ParamItem,
+ input: DataType,
+ extra_args: Optional[Dict[str, Any]] = None,
+ image_transformed: bool = True,
+ ) -> None:
+ """Collect nested matrices, using invocation snapshots only after an image call."""
+ if (
+ type(module) is ImageSequential
+ and self._transformation_matrix_arg in ("silent", "silence")
+ and not is_exporting()
+ ):
+ self._transform_matrices.extend(
+ self._image_sequence_matrices(
+ module,
+ InputSequentialOps.get_sequential_module_param(param),
+ input,
+ extra_args,
+ iter(module._sequence_matrices) if image_transformed else None,
+ )
+ )
+ else:
+ self._update_transform_matrix_by_module(module)
+
def transform_inputs(
self, input: torch.Tensor, params: List[ParamItem], extra_args: Optional[Dict[str, Any]] = None
) -> torch.Tensor:
@@ -435,7 +490,7 @@ class AugmentationSequential(TransformMatrixMinIn, ImageSequential):
for param in params:
module = self.get_submodule(param.name)
input = InputSequentialOps.transform(input, module=module, param=param, extra_args=extra_args)
- self._update_transform_matrix_by_module(module)
+ self._update_image_sequence_matrix(module, param, input, extra_args=extra_args)
if not is_exporting():
self._params = params
return input
@@ -773,7 +828,13 @@ class AugmentationSequential(TransformMatrixMinIn, ImageSequential):
if len(self.transform_op.data_keys) == 1 or not isinstance(outputs, (list, tuple)):
# One data key can itself hold a mask list; keep it as one argument for the next child.
outputs = [outputs]
- self._update_transform_matrix_by_module(module)
+ self._update_image_sequence_matrix(
+ module,
+ param,
+ outputs[0],
+ extra_args=self.extra_args.get(DataKey.INPUT),
+ image_transformed=DataKey.INPUT in original_data_keys,
+ )
if input_first_order != list(range(len(input_first_order))):
restore_order = [input_first_order.index(i) for i in range(len(input_first_order))]
diff --git a/kornia/augmentation/container/base.py b/kornia/augmentation/container/base.py
index 163ff421f..15c9041c0 100644
--- a/kornia/augmentation/container/base.py
+++ b/kornia/augmentation/container/base.py
@@ -278,9 +278,18 @@ class ImageSequentialBase(SequentialBase):
Returns:
Transformed tensor.
"""
+ if not is_exporting():
+ self._sequence_matrices: List[Optional[torch.Tensor]] = []
for param in params:
module = self.get_submodule(param.name)
input = InputSequentialOps.transform(input, module=module, param=param, extra_args=extra_args)
+ if not is_exporting():
+ if isinstance(module, K.AugmentationSequential):
+ # A repeated child can replace or mutate its matrix on the next invocation.
+ matrix = module.transform_matrix
+ self._sequence_matrices.append(None if matrix is None else matrix.clone())
+ elif type(module) is K.ImageSequential:
+ self._sequence_matrices.extend(module._sequence_matrices)
return input
def inverse_inputs(
diff --git a/kornia/augmentation/container/ops.py b/kornia/augmentation/container/ops.py
index 3fea94f75..19a94e056 100644
--- a/kornia/augmentation/container/ops.py
+++ b/kornia/augmentation/container/ops.py
@@ -23,7 +23,7 @@ from torch import nn
import kornia.augmentation as K
from kornia.augmentation.base import _AugmentationBase
-from kornia.augmentation.utils.helpers import deepcopy_dict
+from kornia.augmentation.utils.helpers import deepcopy_dict, override_parameters
from kornia.constants import DataKey
from kornia.core.utils import is_exporting
from kornia.geometry.boxes import Boxes
@@ -62,7 +62,9 @@ class SequentialOpsInterface(Generic[T], metaclass=ABCMeta):
return _params
@classmethod
- def get_transform_matrix(cls, module: nn.Module, param: ParamItem, input: Any) -> torch.Tensor:
+ def get_transform_matrix(
+ cls, module: nn.Module, param: ParamItem, input: Any, extra_args: Optional[Dict[str, Any]] = None
+ ) -> 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, and its values and their versions, next to the matrix
@@ -99,7 +101,8 @@ class SequentialOpsInterface(Generic[T], metaclass=ABCMeta):
# Compute from a copy of the params, as the image call does (its ``data_keys`` override copies the dict). Under
# export the caller's tensors can be graph constants, and a child that copies one as-is into its matrix, as
# ``RandomAffine`` does with ``center``, makes torch 2.9's dynamo ONNX exporter rename that constant and fail.
- return module.generate_transformation_matrix(matrix_input, deepcopy_dict(params), module.flags)
+ flags = module.flags if extra_args is None else override_parameters(module.flags, extra_args, in_place=False)
+ return module.generate_transformation_matrix(matrix_input, deepcopy_dict(params), flags)
@classmethod
def get_sequential_module_param(cls, param: ParamItem) -> List[ParamItem]:
diff --git a/tests/augmentation/container/test_augmentation_sequential.py b/tests/augmentation/container/test_augmentation_sequential.py
index fa8e0f371..d1ae37ac6 100644
--- a/tests/augmentation/container/test_augmentation_sequential.py
+++ b/tests/augmentation/container/test_augmentation_sequential.py
@@ -2316,9 +2316,12 @@ class TestConventionAugmentationSequential(BaseTester):
(K.RandomRotation((90.0, 90.0), p=1.0), [[[0.0, 1.0]], [[1.0, 2.0]]]),
],
)
- def test_nested_container_matrix_matches_keypoints_4476(self, outer_augmentation, expected_points, device, dtype):
- inner = K.AugmentationSequential(K.RandomVerticalFlip(p=1.0))
- nested = K.AugmentationSequential(inner)
+ @pytest.mark.parametrize("nested_cls", [K.AugmentationSequential, K.ImageSequential])
+ def test_nested_container_matrix_matches_keypoints_4476(
+ self, outer_augmentation, expected_points, nested_cls, device, dtype
+ ):
+ inner = nested_cls(K.RandomVerticalFlip(p=1.0))
+ nested = nested_cls(inner)
outer = K.AugmentationSequential(outer_augmentation, nested, data_keys=["input", "keypoints"])
image = torch.rand(2, 1, 6, 6, device=device, dtype=dtype)
points = torch.tensor([[[1.0, 0.0]], [[2.0, 1.0]]], device=device, dtype=dtype)
@@ -2359,6 +2362,156 @@ class TestConventionAugmentationSequential(BaseTester):
output = outer(image)
self.assert_close(nested.inverse(output), image.flip(-1))
+ @pytest.mark.parametrize("nested_first", [False, True])
+ @pytest.mark.parametrize("mode", ["silent", "silence"])
+ def test_nested_image_sequence_matrix_4476(self, nested_first, mode, device, dtype):
+ nested = K.ImageSequential(K.RandomVerticalFlip(p=1.0))
+ horizontal = K.RandomHorizontalFlip(p=1.0)
+ children = [nested, horizontal] if nested_first else [horizontal, nested]
+ outer = K.AugmentationSequential(*children, data_keys=["input", "keypoints"], transformation_matrix_mode=mode)
+ for batch, height, width in [(2, 8, 10), (1, 4, 6)]:
+ image = torch.arange(batch * height * width, device=device, dtype=dtype).reshape(batch, 1, height, width)
+ points = torch.tensor([[[1.0, 0.0]]], device=device, dtype=dtype).expand(batch, -1, -1)
+ output, moved = outer(image, points)
+ params = outer._params
+ expected = torch.tensor([[[width - 2.0, height - 1.0]]], device=device, dtype=dtype).expand(batch, -1, -1)
+ self.assert_close(output, image.flip((-2, -1)))
+ self.assert_close(moved, expected)
+ homogeneous = torch.cat((points, torch.ones_like(points[..., :1])), dim=-1)
+ self.assert_close((homogeneous @ outer.transform_matrix.transpose(-2, -1))[..., :2], expected)
+ replay = outer(image, points, params=params)
+ self.assert_close(replay[0], output)
+ self.assert_close(replay[1], moved)
+ self.assert_close(outer.inverse(*replay, params=params)[1], points)
+
+ @pytest.mark.parametrize("nested_container", [False, True])
+ def test_repeated_nested_image_member_matrix_4476(self, nested_container, device, dtype):
+ image = torch.arange(24, device=device, dtype=dtype).reshape(1, 1, 4, 6)
+ horizontal = K.RandomHorizontalFlip(p=0.5)
+ child = K.AugmentationSequential(horizontal) if nested_container else horizontal
+ nested = K.ImageSequential(child, random_apply=2)
+ outer = K.AugmentationSequential(nested)
+ first = horizontal.forward_parameters(image.shape)
+ first["batch_prob"].fill_(1.0)
+ second = horizontal.forward_parameters(image.shape)
+ second["batch_prob"].zero_()
+ calls = [
+ ParamItem("AugmentationSequential_0", [ParamItem("RandomHorizontalFlip_0", p)])
+ if nested_container
+ else ParamItem("RandomHorizontalFlip_0", p)
+ for p in (first, second)
+ ]
+ params = [ParamItem("ImageSequential_0", calls)]
+ output = outer(image, params=params)
+ self.assert_close(output, image.flip(-1))
+ expected = torch.tensor([[[-1.0, 0.0, 5.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0]]], device=device, dtype=dtype)
+ self.assert_close(outer.transform_matrix, expected)
+ self.assert_close(outer(image, params=params), output)
+ self.assert_close(outer.transform_matrix, expected)
+
+ @pytest.mark.parametrize("repeated_plain", [False, True])
+ @pytest.mark.parametrize("override", [False, True])
+ def test_repeated_nested_subclass_matrix_4476(self, repeated_plain, override, device, dtype):
+ class CustomSequential(K.AugmentationSequential):
+ def transform_inputs(self, input, params, extra_args=None):
+ output = super().transform_inputs(input, params, extra_args)
+ if override:
+ vertical = input.new_tensor([[[1.0, 0.0, 0.0], [0.0, -1.0, 3.0], [0.0, 0.0, 1.0]]])
+ self._transform_matrix = vertical @ self.transform_matrix
+ output = output.flip(-2)
+ return output
+
+ image = torch.arange(24, device=device, dtype=dtype).reshape(1, 1, 4, 6)
+ horizontal = K.RandomHorizontalFlip(p=0.5)
+ child = CustomSequential(horizontal)
+ nested = K.ImageSequential(child, random_apply=2)
+ if repeated_plain:
+ nested = K.ImageSequential(K.ImageSequential(child), random_apply=2)
+ outer = K.AugmentationSequential(nested)
+ first = horizontal.forward_parameters(image.shape)
+ first["batch_prob"].fill_(1.0)
+ second = horizontal.forward_parameters(image.shape)
+ second["batch_prob"].zero_()
+ for draws in ((first, second), (second, first)):
+ calls = [ParamItem("CustomSequential_0", [ParamItem("RandomHorizontalFlip_0", p)]) for p in draws]
+ if repeated_plain:
+ calls = [ParamItem("ImageSequential_0", [call]) for call in calls]
+ params = [ParamItem("ImageSequential_0", calls)]
+ expected = image.new_tensor([[[-1.0, 0.0, 5.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0]]])
+ for _ in range(2):
+ rng = torch.get_rng_state()
+ self.assert_close(outer(image, params=params), image.flip(-1))
+ self.assert_close(outer.transform_matrix, expected)
+ self.assert_close(torch.get_rng_state(), rng, rtol=0, atol=0)
+
+ def test_nested_image_annotation_only_replay_4476(self, device, dtype):
+ horizontal = K.RandomHorizontalFlip(p=1.0)
+ outer = K.AugmentationSequential(K.ImageSequential(horizontal))
+ draw = horizontal.forward_parameters(torch.Size((1, 1, 4, 6)))
+ params = [ParamItem("ImageSequential_0", [ParamItem("RandomHorizontalFlip_0", draw)])]
+ points = torch.tensor([[[1.0, 0.0]]], device=device, dtype=dtype)
+ expected = points.new_tensor([[[-1.0, 0.0, 5.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0]]])
+ for _ in range(2):
+ self.assert_close(outer(points, params=params, data_keys=["keypoints"]), points.new_tensor([[[4.0, 0.0]]]))
+ self.assert_close(outer.transform_matrix, expected)
+
+ @pytest.mark.parametrize("mode", ["silent", "skip"])
+ def test_nested_image_sequence_modes_4476(self, mode, device, dtype):
+ nested = K.ImageSequential(K.RandomVerticalFlip(p=1.0), K.RandomThinPlateSpline(p=0.0))
+ outer = K.AugmentationSequential(nested, K.RandomHorizontalFlip(p=1.0), transformation_matrix_mode=mode)
+ image = torch.arange(24, device=device, dtype=dtype).reshape(1, 1, 4, 6)
+ self.assert_close(outer(image), image.flip((-2, -1)))
+ if mode == "skip":
+ assert outer.transform_matrix is None
+ else:
+ expected = torch.tensor([[[-1.0, 0.0, 5.0], [0.0, -1.0, 3.0], [0.0, 0.0, 1.0]]], device=device, dtype=dtype)
+ self.assert_close(outer.transform_matrix, expected)
+
+ def test_nested_image_sequence_keeps_mix_labels_4476(self, device, dtype):
+ outer = K.AugmentationSequential(K.ImageSequential(K.RandomMixUpV2(p=1.0)), data_keys=["input", "class"])
+ image = torch.rand(2, 1, 4, 6, device=device, dtype=dtype)
+ labels = torch.tensor([0, 1], device=device)
+ _, result = outer(image, labels)
+ self.assert_close(result, labels, rtol=0, atol=0)
+
+ def test_nested_image_sequence_keeps_inner_skip_mode_4476(self, device, dtype):
+ nested = K.ImageSequential(
+ K.AugmentationSequential(K.RandomVerticalFlip(p=1.0), transformation_matrix_mode="skip"),
+ K.RandomHorizontalFlip(p=1.0),
+ )
+ outer = K.AugmentationSequential(nested)
+ image = torch.rand(1, 1, 4, 6, device=device, dtype=dtype)
+ self.assert_close(outer(image), image.flip((-2, -1)))
+ expected = torch.tensor([[[-1.0, 0.0, 5.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0]]], device=device, dtype=dtype)
+ self.assert_close(outer.transform_matrix, expected)
+ # An annotation-only replay reads the matrix from the parameters and keeps the inner skip mode too.
+ points = torch.tensor([[[1.0, 0.0]]], device=device, dtype=dtype)
+ self.assert_close(
+ outer(points, params=outer._params, data_keys=["keypoints"]), points.new_tensor([[[4.0, 3.0]]])
+ )
+ self.assert_close(outer.transform_matrix, expected)
+
+ def test_nested_image_sequence_3d_matrix_4476(self, device, dtype):
+ outer = K.AugmentationSequential(
+ K.RandomVerticalFlip3D(p=1.0), K.ImageSequential(K.RandomHorizontalFlip3D(p=1.0))
+ )
+ image = torch.rand(1, 1, 3, 4, 6, device=device, dtype=dtype)
+ self.assert_close(outer(image), image.flip((-2, -1)))
+ expected = torch.tensor(
+ [[[-1.0, 0.0, 0.0, 5.0], [0.0, -1.0, 0.0, 3.0], [0.0, 0.0, 1.0, 0.0], [0.0, 0.0, 0.0, 1.0]]],
+ device=device,
+ dtype=dtype,
+ )
+ self.assert_close(outer.transform_matrix, expected)
+
+ def test_repeated_nested_resize_keeps_input_overrides_4476(self, device, dtype):
+ nested = K.ImageSequential(K.Resize((4, 6)), random_apply=2)
+ outer = K.AugmentationSequential(nested, extra_args={DataKey.INPUT: {"align_corners": False}})
+ image = torch.rand(1, 1, 8, 10, device=device, dtype=dtype)
+ outer(image)
+ expected = torch.tensor([[[0.6, 0.0, -0.2], [0.0, 0.5, -0.25], [0.0, 0.0, 1.0]]], device=device, dtype=dtype)
+ self.assert_close(outer.transform_matrix, expected)
+
def test_convention_nested_rigid_container_checks_its_children_4476(self, device, dtype):
# A nested container records its matrix in its own mode, so ``rigid`` rejects a non-rigid child as a direct
# call does.
diff --git a/tests/core/test_onnx_mixin.py b/tests/core/test_onnx_mixin.py
index 3e8d59874..1a8e60e1b 100644
--- a/tests/core/test_onnx_mixin.py
+++ b/tests/core/test_onnx_mixin.py
@@ -122,6 +122,10 @@ _NOT_CALL_STATE = {
"SequentialBase.same_on_batch": (("_same_on_batch",), "a property setter"),
"OperationBase._init_magnitude": (("_factor_name", "_magnitude", "magnitude_range"), "a constructor helper"),
"TransformMatrixMinIn._parse_transformation_matrix_mode": (("_transformation_matrix_arg",), "a constructor helper"),
+ "ImageSequentialBase.transform_inputs": (
+ ("_sequence_matrices",),
+ "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"),
"RandomTransplantation.params_from_input": (