π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
fix(augmentation): honour and validate ImageSequential.if_unsupported_ops (#4764)
Aditya Malkar08d895039839
diff --git a/changelog.d/4764.breaking.md b/changelog.d/4764.breaking.mdnew file mode 100644index 000000000..75757e8d1--- /dev/null+++ b/changelog.d/4764.breaking.md@@ -0,0 +1,9 @@+`ImageSequential(if_unsupported_ops=...)` now takes effect. `inverse` used to skip a plain `nn.Module` member+(a `kornia.filters` blur, for example) under every value of the argument, returning the input with that module+still applied and without an error. With the default `'raise'` it now raises `NotImplementedError` naming the+module, before anything is inverted; `'skip'` keeps the previous behavior. Code that inverted through a plain+module must now pass `if_unsupported_ops='skip'`. A value other than `'raise'` or `'skip'` raises `ValueError`+at construction, where it was stored silently. `VideoSequential` inverts through the same path and now takes+the same argument. `AugmentationSequential` still leaves a plain module child applied, also when it is+nested in another container, but an `ImageSequential` or `VideoSequential` nested in it follows its own+setting and so now raises by default as well. `PatchSequential` is unaffected. Fixes #4423.diff --git a/kornia/augmentation/container/augment.py b/kornia/augmentation/container/augment.pyindex 0421f9de8..33f75d200 100644--- a/kornia/augmentation/container/augment.py+++ b/kornia/augmentation/container/augment.py@@ -310,6 +310,8 @@ class AugmentationSequential(TransformMatrixMinIn, ImageSequential):keepdim=keepdim,random_apply=random_apply,random_apply_weights=random_apply_weights,+ # `inverse` below leaves a plain `nn.Module` child applied; keep that when nested in another container.+ if_unsupported_ops="skip",)self._parse_transformation_matrix_mode(transformation_matrix_mode)diff --git a/kornia/augmentation/container/image.py b/kornia/augmentation/container/image.pyindex f51b84731..c36aba9a2 100644--- a/kornia/augmentation/container/image.py+++ b/kornia/augmentation/container/image.py@@ -21,7 +21,7 @@ import torchfrom torch import nnimport kornia.augmentation as K-from kornia.augmentation.base import _AugmentationBase+from kornia.augmentation.base import _AugmentationBase, _BasicAugmentationBasefrom kornia.augmentation.utils import override_parametersfrom kornia.core import ImageModulefrom kornia.core.mixin.image_module import ImageModuleMixIn@@ -71,8 +71,9 @@ class ImageSequential(ImageSequentialBase, ImageModuleForSequentialMixIn):If False, the whole list of args will be processed as a sequence in original order.random_apply_weights: a list of selection weights for each operation. The length shall be assame as the number of operations. By default, operations are sampled uniformly.- if_unsupported_ops: intended to choose between raising and skipping an uninvertible plain ``nn.Module``.- It is neither validated nor enforced, and the inverse path skips such a module under every value.+ if_unsupported_ops: what ``inverse`` does on reaching a plain ``nn.Module``, which has no inverse:+ ``'raise'`` raises ``NotImplementedError`` naming it, before anything is inverted, and ``'skip'``+ leaves it applied and inverts the other members. Any other value raises ``ValueError``.Convention:- this container takes image tensors only. It has no ``data_keys``, so masks, boxes and keypoints go@@ -85,15 +86,11 @@ class ImageSequential(ImageSequentialBase, ImageModuleForSequentialMixIn):samples ordinary members and mix augmentations through separate paths; a mix member's insertiondoes not honor its ordinary selection weight. Each selected member is recorded in ``_params``, buta plain module records a ``None`` payload: only augmentation members carry a parameter draw to replay.- - ``inverse`` skips uninvertible plain ``nn.Module`` members. Augmentation children can still raise,- for example a slice-mode crop or a 3D geometric augmentation, while non-rigid augmentation children+ - ``inverse`` treats a plain ``nn.Module`` member according to ``if_unsupported_ops``, and a nested+ container according to its own setting. Augmentation children can still raise, for example a+ slice-mode crop or a 3D geometric augmentation, while intensity and non-rigid augmentation childrenare left applied; the round trip is not in general the input.- .. warning::- ``if_unsupported_ops`` never fires: a plain ``nn.Module`` in the chain is skipped on the inverse path- under every value of the flag, an invalid value included, and nothing is raised or warned. Tracked in- `#4423 <https://github.com/kornia/kornia/issues/4423>`_.-.. note::Transformation matrix returned only considers the transformation applied in ``kornia.augmentation`` module.Those transformations in ``kornia.geometry`` will not be taken into account.@@ -150,6 +147,8 @@ class ImageSequential(ImageSequentialBase, ImageModuleForSequentialMixIn):disable_item_features: bool = True,disable_sequential_features: bool = False,) -> None:+ if if_unsupported_ops not in ("raise", "skip"):+ raise ValueError(f"`if_unsupported_ops` must be either `raise` or `skip`. Got {if_unsupported_ops!r}.")if disable_item_features:self.disable_item_features(*args)if disable_sequential_features:@@ -363,6 +362,35 @@ class ImageSequential(ImageSequentialBase, ImageModuleForSequentialMixIn):res_mat = mat if res_mat is None else mat @ res_matreturn res_mat+ def inverse_inputs(+ self, input: torch.Tensor, params: List[ParamItem], extra_args: Optional[Dict[str, Any]] = None+ ) -> torch.Tensor:+ """Apply inverse transforms for an input tensor.++ Args:+ input: Tensor produced by :meth:`transform_inputs`.+ params: Parameters used during forward execution.+ extra_args: Optional per-input-type overrides.++ Returns:+ Tensor mapped back through inverse operations.++ Raises:+ NotImplementedError: if ``if_unsupported_ops`` is ``'raise'`` and ``params`` records a plain+ ``nn.Module``, which has no inverse.+ """+ if self.if_unsupported_ops == "raise":+ # Checked before inverting anything, so a raise never leaves a partial inverse behind.+ invertible = (_BasicAugmentationBase, ImageSequentialBase, K.auto.operations.OperationBase)+ for name, module in self.get_forward_sequence(params):+ if not isinstance(module, invertible):+ raise NotImplementedError(+ f"Cannot invert `{name}` ({type(module).__name__}): a plain `nn.Module` has no inverse, "+ "so the result would keep it applied. Pass `if_unsupported_ops='skip'` to invert the "+ "other members and leave it in place."+ )+ return super().inverse_inputs(input, params, extra_args=extra_args)+# TODO: Make this as a class property to avoid running every time.def is_intensity_only(self, strict: bool = True) -> bool:"""Check if all transformations are intensity-based.diff --git a/kornia/augmentation/container/video.py b/kornia/augmentation/container/video.pyindex bcd682392..b2f449db6 100644--- a/kornia/augmentation/container/video.py+++ b/kornia/augmentation/container/video.py@@ -52,6 +52,8 @@ class VideoSequential(ImageSequential):If (a,), x number of transformations (a <= x <= len(args)) will be selected.If (a, b), x number of transformations (a <= x <= b) will be selected.If None, the whole list of args will be processed as a sequence.+ if_unsupported_ops: what ``inverse`` does on reaching a plain ``nn.Module``, as in+ :class:`~kornia.augmentation.container.ImageSequential`: ``'raise'`` or ``'skip'``.Convention:- the input is 5-dimensional and the layout is named by ``data_format``, which accepts ``"BTCHW"``@@ -137,6 +139,7 @@ class VideoSequential(ImageSequential):same_on_frame: bool = True,random_apply: Union[int, bool, Tuple[int, int]] = False,random_apply_weights: Optional[List[float]] = None,+ if_unsupported_ops: str = "raise",) -> None:super().__init__(*args,@@ -144,6 +147,7 @@ class VideoSequential(ImageSequential):keepdim=None,random_apply=random_apply,random_apply_weights=random_apply_weights,+ if_unsupported_ops=if_unsupported_ops,)self.same_on_frame = same_on_frameself.data_format = data_format.upper()diff --git a/tests/augmentation/container/test_sequential_aug.py b/tests/augmentation/container/test_sequential_aug.pyindex de4b3ba3c..de315dce4 100644--- a/tests/augmentation/container/test_sequential_aug.py+++ b/tests/augmentation/container/test_sequential_aug.py@@ -81,30 +81,24 @@ class TestConventionImageSequential(BaseTester):`.venv/bin/python` (torch 2.14.0, python 3.11, cpu, float32)."""- def test_wart_if_unsupported_ops_is_neither_honoured_nor_validated_4423(self, device, dtype):- # Wart pin (#4423): `ImageSequential.if_unsupported_ops` ("raise" by default) never fires. A plain- # `nn.Module` in the chain is silently skipped on the inverse path under every value of the flag -- # including an invalid one, which is accepted without validation - so `inverse` undoes only the- # invertible ops and returns something that is not the input, with no warning.- # The deterministic checkerboard ensures the omitted blur visibly changes the output: for every- # if_unsupported_ops value in ("raise", "skip", "bogus"), inverse equals hflip(output) exactly- # (only the flip was undone) and differs from the input.- # The fix lands in the repair window; do not "correct" this pin here.+ def test_convention_if_unsupported_ops_skip_leaves_plain_modules_applied_4423(self, device, dtype):+ # #4423: the inverse used to skip a plain `nn.Module` under every value of the flag. That behavior is now+ # what "skip" selects: `inverse` undoes only the invertible members and returns something that is not the+ # input. The deterministic checkerboard ensures the omitted blur visibly changes the output.if device.type == "mps" and torch_version_lt(2, 6, 0):pytest.skip("torch 2.5.1 MPS inverse of expanded matrices can abort the process")yy, xx = torch.meshgrid(torch.arange(6, device=device), torch.arange(8, device=device), indexing="ij")x = ((yy + xx) % 2).to(dtype).expand(2, 3, 6, 8)assert K.ImageSequential(K.RandomHorizontalFlip(p=1.0)).if_unsupported_ops == "raise"- for mode in ("raise", "skip", "bogus"):- seq = K.ImageSequential(- K.RandomHorizontalFlip(p=1.0),- kornia.filters.GaussianBlur2d((3, 3), (1.5, 1.5)),- if_unsupported_ops=mode,- )- out = seq(x)- inverted = seq.inverse(out)- self.assert_close(inverted, out.flip(-1)) # only the flip was undone, the blur was skipped- assert (inverted - x).abs().max().item() > 0.1 # and the round trip is not the input+ seq = K.ImageSequential(+ K.RandomHorizontalFlip(p=1.0),+ kornia.filters.GaussianBlur2d((3, 3), (1.5, 1.5)),+ if_unsupported_ops="skip",+ )+ out = seq(x)+ inverted = seq.inverse(out)+ self.assert_close(inverted, out.flip(-1)) # only the flip was undone, the blur was skipped+ assert (inverted - x).abs().max().item() > 0.1 # and the round trip is not the inputdef test_convention_slice_crop_inverse_raises(self, device, dtype):seq = K.ImageSequential(K.CenterCrop((4, 6), p=1.0))@@ -127,13 +121,9 @@ class TestConventionImageSequential(BaseTester):assert current is not None and recomputed is not Noneassert not torch.equal(current, recomputed)- @pytest.mark.xfail(strict=True, raises=pytest.fail.Exception, reason="Tracked in #4423")def test_convention_if_unsupported_ops_raise_raises_not_implemented(self, device, dtype):- # Strict xfail (#4423): the intended reading is the argument's own contract - `if_unsupported_ops`- # defaults to "raise", so inverting a chain that holds a non-invertible plain `nn.Module` must raise- # `NotImplementedError` rather than silently skip it. This turns XPASS when the repair lands, which- # is the signal to delete the wart pin above. Executed 2026-09-11 (torch 2.14.0, cpu): inverse returns- # quietly.+ # #4423: `if_unsupported_ops` defaults to "raise", so inverting a chain that holds a non-invertible+ # plain `nn.Module` raises `NotImplementedError` rather than silently skipping it.if device.type == "mps" and torch_version_lt(2, 6, 0):pytest.skip("torch 2.5.1 MPS inverse of expanded matrices can abort the process")x = torch.rand(2, 3, 6, 8, device=device, dtype=dtype)@@ -146,9 +136,90 @@ class TestConventionImageSequential(BaseTester):with pytest.raises(NotImplementedError):seq.inverse(out)- @pytest.mark.xfail(strict=True, raises=pytest.fail.Exception, reason="Tracked in #4423")+ def test_convention_if_unsupported_ops_raise_leaves_intensity_augmentations_applied_4423(self, device, dtype):+ # #4423: "raise" is about plain `nn.Module` members only. An intensity augmentation has no geometry to+ # undo and is left applied on the inverse path, as before, under both settings.+ if device.type == "mps" and torch_version_lt(2, 6, 0):+ pytest.skip("torch 2.5.1 MPS inverse of expanded matrices can abort the process")+ x = torch.rand(2, 3, 6, 8, device=device, dtype=dtype)+ seq = K.ImageSequential(K.RandomHorizontalFlip(p=1.0), K.ColorJiggle(0.3, 0.3, p=1.0))+ out = seq(x)+ self.assert_close(seq.inverse(out), out.flip(-1))++ def test_convention_if_unsupported_ops_applies_to_each_container_own_members_4423(self, device, dtype):+ # #4423: a nested container inverts its own members, so its own setting decides for the plain modules it+ # holds, and a nested container is never itself an unsupported member of the outer one.+ if device.type == "mps" and torch_version_lt(2, 6, 0):+ pytest.skip("torch 2.5.1 MPS inverse of expanded matrices can abort the process")+ x = torch.rand(2, 3, 6, 8, device=device, dtype=dtype)+ blur = kornia.filters.GaussianBlur2d((3, 3), (1.5, 1.5))++ inner_skips = K.ImageSequential(+ K.RandomHorizontalFlip(p=1.0),+ K.ImageSequential(blur, if_unsupported_ops="skip"),+ if_unsupported_ops="raise",+ )+ out = inner_skips(x)+ self.assert_close(inner_skips.inverse(out), out.flip(-1))++ inner_raises = K.ImageSequential(+ K.RandomHorizontalFlip(p=1.0),+ K.ImageSequential(blur, if_unsupported_ops="raise"),+ if_unsupported_ops="skip",+ )+ out = inner_raises(x)+ with pytest.raises(NotImplementedError, match="GaussianBlur2d"):+ inner_raises.inverse(out)++ def test_convention_if_unsupported_ops_ignores_members_random_apply_did_not_select_4423(self, device, dtype):+ # #4423: only the members recorded in `params` are checked, so a plain module that `random_apply` did not+ # select cannot make "raise" fire.+ if device.type == "mps" and torch_version_lt(2, 6, 0):+ pytest.skip("torch 2.5.1 MPS inverse of expanded matrices can abort the process")+ x = torch.rand(2, 3, 6, 8, device=device, dtype=dtype)+ blur = kornia.filters.GaussianBlur2d((3, 3), (1.5, 1.5))+ seq = K.ImageSequential(K.RandomHorizontalFlip(p=1.0), blur, random_apply=1, random_apply_weights=[1.0, 0.0])+ out = seq(x)+ assert [p.name for p in seq._params] == ["RandomHorizontalFlip_0"]+ self.assert_close(seq.inverse(out), out.flip(-1))++ def test_convention_augmentation_sequential_leaves_plain_modules_applied_4423(self, device, dtype):+ # #4423: `AugmentationSequential` does not take `if_unsupported_ops`; it leaves a plain module child applied,+ # also when nested in another container, while a nested `ImageSequential` follows its own setting.+ if device.type == "mps" and torch_version_lt(2, 6, 0):+ pytest.skip("torch 2.5.1 MPS inverse of expanded matrices can abort the process")+ x = torch.rand(2, 3, 6, 8, device=device, dtype=dtype)+ blur = kornia.filters.GaussianBlur2d((3, 3), (1.5, 1.5))++ nested_aug = K.ImageSequential(+ K.RandomHorizontalFlip(p=1.0), K.AugmentationSequential(K.RandomVerticalFlip(p=1.0), blur)+ )+ out = nested_aug(x)+ self.assert_close(nested_aug.inverse(out), out.flip(-2).flip(-1))++ nested_image = K.AugmentationSequential(+ K.RandomHorizontalFlip(p=1.0), K.ImageSequential(K.RandomVerticalFlip(p=1.0), blur)+ )+ out = nested_image(x)+ with pytest.raises(NotImplementedError, match="GaussianBlur2d"):+ nested_image.inverse(out)++ def test_convention_video_sequential_passes_if_unsupported_ops_through_4423(self, device, dtype):+ # #4423: VideoSequential inverts through ImageSequential, so it takes the same setting.+ x = torch.rand(1, 3, 3, 6, 8, device=device, dtype=dtype)+ blur = kornia.filters.GaussianBlur2d((3, 3), (1.5, 1.5))+ raises = K.VideoSequential(K.RandomHorizontalFlip(p=1.0), blur)+ assert raises.if_unsupported_ops == "raise"+ out = raises(x)+ with pytest.raises(NotImplementedError, match="GaussianBlur2d"):+ raises.inverse(out)+ skips = K.VideoSequential(K.RandomHorizontalFlip(p=1.0), blur, if_unsupported_ops="skip")+ out = skips(x)+ self.assert_close(skips.inverse(out), out.flip(-1))+ with pytest.raises(ValueError):+ K.VideoSequential(K.RandomHorizontalFlip(p=1.0), if_unsupported_ops="bogus")+def test_convention_if_unsupported_ops_rejects_invalid_value(self):- # Strict xfail (#4423): construction accepts only "raise" and "skip". Executed 2026-09-11 (torch- # 2.14.0, cpu): "bogus" is accepted without validation.+ # #4423: construction accepts only "raise" and "skip".with pytest.raises(ValueError):K.ImageSequential(K.RandomHorizontalFlip(p=1.0), if_unsupported_ops="bogus")