Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

fix(augmentation): Refresh nested sequence matrices (#5391)

A Aswanth Raj45dd90eafc37
diff --git a/changelog.d/5391.breaking.md b/changelog.d/5391.breaking.md
new file mode 100644
index 000000000..e6ed4f058
--- /dev/null
+++ b/changelog.d/5391.breaking.md
@@ -0,0 +1,3 @@
+A nested `AugmentationSequential` now records its transformation matrix under its own `transformation_matrix_mode`
+when it runs inside another container. A nested container built with `transformation_matrix_mode="rigid"` therefore
+raises `RuntimeError` for a non-rigid child, as it does when called directly; it used to run without the check. (#4476)
diff --git a/changelog.d/5391.fixed.md b/changelog.d/5391.fixed.md
new file mode 100644
index 000000000..1a19fe47c
--- /dev/null
+++ b/changelog.d/5391.fixed.md
@@ -0,0 +1,5 @@
+`AugmentationSequential.transform_matrix` composes the matrix that a nested `AugmentationSequential` recorded for the
+current call. Depending on the child order it used to raise `TypeError`, omit the nested transform, or reuse the
+matrix of the nested container's last direct call. A nested container whose children are all non-rigid is skipped
+like a non-rigid child, in either order, and `ImageSequential.get_transformation_matrix` reads the nested
+container's current matrix too. A plain `ImageSequential` child is still omitted (#4476).
diff --git a/docs/source/get-started/conventions.rst b/docs/source/get-started/conventions.rst
index 945ccc7b4..bc4067b94 100644
--- a/docs/source/get-started/conventions.rst
+++ b/docs/source/get-started/conventions.rst
@@ -414,8 +414,9 @@ Augmentations
- Boxes use the inclusive ``xyxy_plus`` convention of
:class:`kornia.geometry.boxes.Boxes` (see *Bounding boxes* above). Flips use
integer pixel centres: ``x' = W - 1 - x``.
-- The outer ``.transform_matrix`` of a nested container can be missing or
- stale, even with only rigid children
+- 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>`_).
- Dictionary keys match a data-key name exactly or before an ``_``/``-``
suffix, the longest match winning. Unrecognized keys are returned unchanged
diff --git a/kornia/augmentation/container/augment.py b/kornia/augmentation/container/augment.py
index 7b3e3329f..74511e9e4 100644
--- a/kornia/augmentation/container/augment.py
+++ b/kornia/augmentation/container/augment.py
@@ -37,7 +37,7 @@ from kornia.image.utils import image_to_tensor
from .base import TransformMatrixMinIn
from .image import ImageSequential
-from .ops import AugmentationSequentialOps, DataType
+from .ops import AugmentationSequentialOps, DataType, InputSequentialOps
from .params import ParamItem
from .patch import PatchSequential
from .video import VideoSequential
@@ -162,8 +162,10 @@ class AugmentationSequential(TransformMatrixMinIn, ImageSequential):
interpolation is not recovered.
- ``same_on_batch`` and ``keepdim`` default to ``None``, which keeps each child's own setting;
``True`` or ``False`` overrides it.
- - ``.transform_matrix`` of a chain holding a nested container is unreliable: it can raise, omit the
- nested transform or return a stale one (`#4476 <https://github.com/kornia/kornia/issues/4476>`_).
+ - 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>`_).
.. warning::
A non-rigid child silently desynchronizes the coordinate data keys:
@@ -383,8 +385,37 @@ class AugmentationSequential(TransformMatrixMinIn, ImageSequential):
return super().clear_state()
def _update_transform_matrix_for_valid_op(self, module: nn.Module) -> None:
+ if is_exporting():
+ return
+ matrix = module.transform_matrix
+ # A nested container whose children are all non-rigid records no matrix under its own mode: skip it, as its
+ # own mode skipped them. Appending ``None`` made the product raise or drop it depending on the child order.
+ if matrix is not None:
+ self._transform_matrices.append(matrix)
+
+ def transform_inputs(
+ self, input: torch.Tensor, params: List[ParamItem], extra_args: Optional[Dict[str, Any]] = None
+ ) -> torch.Tensor:
+ """Apply prepared parameters and record the current transformation matrix.
+
+ Nested containers use this entry point instead of :meth:`forward`.
+
+ Args:
+ input: Input tensor.
+ params: Parameters for each child in execution order.
+ extra_args: Optional overrides forwarded to child modules.
+
+ Returns:
+ Transformed tensor.
+ """
+ self.clear_state()
+ 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)
if not is_exporting():
- self._transform_matrices.append(module.transform_matrix)
+ self._params = params
+ return input
def identity_matrix(self, input: torch.Tensor) -> torch.Tensor:
"""Return identity matrix."""
diff --git a/kornia/augmentation/container/image.py b/kornia/augmentation/container/image.py
index 983b70951..294de4c0a 100644
--- a/kornia/augmentation/container/image.py
+++ b/kornia/augmentation/container/image.py
@@ -352,13 +352,15 @@ class ImageSequential(ImageSequentialBase, ImageModuleForSequentialMixIn):
elif isinstance(module, ImageSequentialBase):
# If not augmentationSequential
if isinstance(module, K.AugmentationSequential) and not recompute:
- mat = torch.as_tensor(module._transform_matrix, device=input.device, dtype=input.dtype)
+ _mat = module.transform_matrix
+ if _mat is not None:
+ _mat = torch.as_tensor(_mat, device=input.device, dtype=input.dtype)
else:
maybe_param_data = cast(Optional[List[ParamItem]], param.data)
_mat = module.get_transformation_matrix(
input, maybe_param_data, recompute=recompute, extra_args=extra_args
)
- mat = module.identity_matrix(input) if _mat is None else _mat
+ mat = module.identity_matrix(input) if _mat is None else _mat
res_mat = mat if res_mat is None else mat @ res_mat
return res_mat
diff --git a/tests/augmentation/container/test_augmentation_sequential.py b/tests/augmentation/container/test_augmentation_sequential.py
index 9ee30e21c..bcfc0978c 100644
--- a/tests/augmentation/container/test_augmentation_sequential.py
+++ b/tests/augmentation/container/test_augmentation_sequential.py
@@ -1375,34 +1375,87 @@ class TestConventionAugmentationSequential(BaseTester):
assert (restored_corners.min(dim=0).values < original_corners.min(dim=0).values - 1).all()
assert (restored_corners.max(dim=0).values > original_corners.max(dim=0).values + 1).all()
- def test_wart_nested_container_matrix_is_order_sensitive_4476(self, device, dtype):
- # Wart pin (#4476): nesting itself, not a non-rigid child, breaks outer matrix accumulation. A rigid
- # child followed by a nested rigid sequence raises, while the reverse ordering silently drops the
- # nested transform. A directly-called nested container can also inject stale state.
- image = torch.rand(1, 3, 8, 8, device=device, dtype=dtype)
- nested_rigid = lambda: K.AugmentationSequential( # noqa: E731
- K.RandomVerticalFlip(p=1.0), data_keys=["input"]
- )
- rigid_then_nested = K.AugmentationSequential(K.RandomHorizontalFlip(p=1.0), nested_rigid(), data_keys=["input"])
- assert rigid_then_nested(image).shape == image.shape
- with pytest.raises(TypeError):
- _ = rigid_then_nested.transform_matrix
+ @pytest.mark.parametrize("nested_first", [False, True])
+ @pytest.mark.parametrize("warmed", [False, True])
+ @pytest.mark.parametrize("outer_cls", [K.AugmentationSequential, K.ImageSequential])
+ def test_convention_nested_container_matrix_4476(self, nested_first, warmed, outer_cls, device, dtype):
+ nested = K.AugmentationSequential(K.RandomVerticalFlip(p=1.0), data_keys=["input"])
+ if warmed:
+ nested(torch.rand(2, 1, 8, 10, device=device, dtype=dtype))
+ _ = nested.transform_matrix
+ horizontal = K.RandomHorizontalFlip(p=1.0)
+ children = [nested, horizontal] if nested_first else [horizontal, nested]
+ outer = outer_cls(*children)
+ image = torch.arange(24, device=device, dtype=dtype).reshape(1, 1, 4, 6)
- nested_then_rigid = K.AugmentationSequential(nested_rigid(), K.RandomHorizontalFlip(p=1.0), data_keys=["input"])
- assert nested_then_rigid(image).shape == image.shape
- self.assert_close(
- nested_then_rigid.transform_matrix,
- torch.tensor([[[-1.0, 0.0, 7.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0]]], device=device, dtype=dtype),
- )
+ output = outer(image)
+ params = outer._params
+ self.assert_close(output, image.flip((-2, -1)))
+ 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)
+ if outer_cls is K.AugmentationSequential:
+ self.assert_close(outer.transform_matrix, expected)
+ self.assert_close(outer.get_transformation_matrix(image, params=params), expected)
+ self.assert_close(nested.transform_matrix[:, 1, 2], torch.tensor([3.0], device=device, dtype=dtype))
+ self.assert_close(outer(image, params=params), output)
+ self.assert_close(outer.inverse(output, params=params), image)
- stale_child = K.AugmentationSequential(K.RandomVerticalFlip(p=1.0), data_keys=["input"])
- stale_child(image)
- stale_outer = K.AugmentationSequential(stale_child, data_keys=["input"])
- shorter = image[:, :, :6]
- stale_outer(shorter)
- stale = torch.tensor([[[1.0, 0.0, 0.0], [0.0, -1.0, 7.0], [0.0, 0.0, 1.0]]], device=device, dtype=dtype)
- self.assert_close(stale_outer.transform_matrix, stale)
- assert stale_outer.transform_matrix[0, 1, 2].item() != shorter.shape[-2] - 1
+ @pytest.mark.parametrize(
+ "outer_augmentation,expected_points",
+ [
+ (K.RandomHorizontalFlip(p=1.0), [[[4.0, 5.0]], [[3.0, 4.0]]]),
+ (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)
+ 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)
+ _, output_points = outer(image, points)
+ homogeneous = torch.cat((points, torch.ones_like(points[..., :1])), dim=-1)
+ matrix_points = homogeneous @ outer.transform_matrix.transpose(-2, -1)
+ self.assert_close(matrix_points[..., :2], output_points)
+ self.assert_close(output_points, torch.tensor(expected_points, device=device, dtype=dtype))
+
+ @pytest.mark.parametrize("nested_first", [False, True])
+ def test_convention_nested_non_rigid_container_is_skipped_4476(self, nested_first, device, dtype):
+ # A nested container whose children are all non-rigid records no matrix and is skipped, in either order and
+ # under the outer ``rigid`` mode too: the nested container's own ``silent`` mode skipped its children.
+ image = torch.rand(1, 1, 6, 8, device=device, dtype=dtype)
+ expected = torch.tensor([[[-1.0, 0.0, 7.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0]]], device=device, dtype=dtype)
+
+ def children():
+ nested = K.AugmentationSequential(K.RandomThinPlateSpline(p=1.0))
+ horizontal = K.RandomHorizontalFlip(p=1.0)
+ return [nested, horizontal] if nested_first else [horizontal, nested]
+
+ outer = K.AugmentationSequential(*children())
+ outer(image)
+ self.assert_close(outer.transform_matrix, expected)
+
+ image_outer = K.ImageSequential(*children())
+ image_outer(image)
+ self.assert_close(image_outer.get_transformation_matrix(image, params=image_outer._params), expected)
+
+ rigid_outer = K.AugmentationSequential(*children(), transformation_matrix_mode="rigid")
+ rigid_outer(image)
+ self.assert_close(rigid_outer.transform_matrix, expected)
+
+ def test_nested_container_records_its_params_4476(self, device, dtype):
+ nested = K.AugmentationSequential(K.RandomVerticalFlip(p=1.0))
+ outer = K.AugmentationSequential(K.RandomHorizontalFlip(p=1.0), nested)
+ image = torch.rand(1, 1, 4, 6, device=device, dtype=dtype)
+ output = outer(image)
+ self.assert_close(nested.inverse(output), image.flip(-1))
+
+ 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.
+ nested = K.AugmentationSequential(K.RandomThinPlateSpline(p=1.0), transformation_matrix_mode="rigid")
+ outer = K.AugmentationSequential(K.RandomHorizontalFlip(p=1.0), nested)
+ with pytest.raises(RuntimeError, match="under `rigid` computation mode"):
+ outer(torch.rand(1, 1, 6, 8, device=device, dtype=dtype))
@pytest.mark.parametrize("crop_cls", [K.CenterCrop, K.RandomCrop, K.RandomResizedCrop])
def test_convention_slice_crop_inverse_raises(self, crop_cls, device, dtype):
diff --git a/tests/augmentation/test_augmentation_compile.py b/tests/augmentation/test_augmentation_compile.py
index 2750adbc6..d6060f97a 100644
--- a/tests/augmentation/test_augmentation_compile.py
+++ b/tests/augmentation/test_augmentation_compile.py
@@ -293,6 +293,17 @@ class TestAugmentationCompile(BaseTester):
input = torch.rand(1, 1, 2, 2, device=device, dtype=dtype)
self.assert_close(InheritedFlip()(input), input + 1)
+ @pytest.mark.parametrize("nested_first", [False, True])
+ def test_compile_nested_container_matrix(self, device, dtype, torch_optimizer, nested_first):
+ # A nested container records its matrix inside the compiled outer forward (#4476).
+ nested = K.AugmentationSequential(K.RandomVerticalFlip(p=1.0))
+ horizontal = K.RandomHorizontalFlip(p=1.0)
+ aug = K.AugmentationSequential(*([nested, horizontal] if nested_first else [horizontal, nested]))
+ input = torch.rand(1, 1, 4, 6, device=device, dtype=dtype)
+ self.assert_close(torch_optimizer(aug, fullgraph=True)(input), input.flip((-2, -1)))
+ 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(aug.transform_matrix, expected)
+
class TestRandomCropCompile(BaseTester):
@pytest.mark.parametrize("padding_mode", ["constant", "reflect", "replicate"])