π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
fix(auto): refuse an inverse the drawn sub-policy cannot undo (#4456)
Mohansree Vijayakumar76f4a2a9ee6e
diff --git a/changelog.d/4456.fixed.md b/changelog.d/4456.fixed.mdnew file mode 100644index 000000000..85ae6a356--- /dev/null+++ b/changelog.d/4456.fixed.md@@ -0,0 +1,5 @@+`AutoAugment`, `RandAugment` and `TrivialAugment` now raise a `RuntimeError` from `inverse` when the+drawn sub-policy applied a non-geometric operation, instead of silently returning a tensor that still+carries it -- for a draw with no geometry at all, the input unchanged. Only geometric operations are+invertible, and the sub-policy is redrawn on every forward pass. An operation whose probability gate+skipped every sample does not count.diff --git a/kornia/augmentation/auto/base.py b/kornia/augmentation/auto/base.pyindex 0330caae2..5df4643e8 100644--- a/kornia/augmentation/auto/base.py+++ b/kornia/augmentation/auto/base.py@@ -20,6 +20,7 @@ from typing import Any, Dict, Iterator, List, Optional, Tuple, Union, castimport torchfrom torch import nn+from kornia.augmentation._2d.geometric.base import GeometricAugmentationBase2Dfrom kornia.augmentation.auto.operations.base import OperationBasefrom kornia.augmentation.auto.operations.policy import PolicySequentialfrom kornia.augmentation.container.base import ImageSequentialBase, TransformMatrixMinIn@@ -119,6 +120,65 @@ class PolicyAugmentBase(ImageSequentialBase, TransformMatrixMinIn):return Falsereturn True+ def _non_invertible_ops(self, params: List[ParamItem]) -> List[str]:+ """Name every applied operation that :meth:`inverse` cannot undo.++ An operation whose probability gate skipped every sample left the input untouched, so it does+ not count.++ Args:+ params: Parameters recorded by a forward pass.++ Returns:+ Class names of the applied operations that are not geometric, in execution order.+ """+ names: List[str] = []+ for (_, module), param in zip(self.get_forward_sequence(params), params):+ subpolicy = cast(PolicySequential, module)+ subparams = cast(List[ParamItem], param.data)+ for (_, operation), subparam in zip(subpolicy.get_forward_sequence(subparams), subparams):+ operation = cast(OperationBase, operation)+ if isinstance(operation.op, GeometricAugmentationBase2D):+ continue+ batch_prob = cast(Dict[str, torch.Tensor], subparam.data).get("batch_prob")+ if batch_prob is not None and not batch_prob.any():+ continue+ names.append(operation.op.__class__.__name__)+ return names++ def inverse(+ self, input: torch.Tensor, params: Optional[List[ParamItem]] = None, extra_args: Optional[Dict[str, Any]] = None+ ) -> torch.Tensor:+ """Undo the drawn sub-policy, or refuse when it cannot be undone.++ Only geometric operations are invertible. A policy draw that contains an intensity operation is+ not round-trippable, and inverting it would return a tensor that still carries that operation --+ for a draw with no geometry at all, the input unchanged. This raises instead, as+ :meth:`kornia.augmentation.MixAugmentationBaseV2.inverse` already does for the mix classes.++ Args:+ input: Tensor produced by a forward pass.+ params: Parameters used during that forward pass. Defaults to the cached ones.+ extra_args: Optional per-input-type overrides.++ Returns:+ The inverse-transformed tensor.++ Raises:+ RuntimeError: The drawn sub-policy contains a non-invertible operation.+ """+ if params is None:+ params = self._params+ if params is not None:+ non_invertible = self._non_invertible_ops(params)+ if non_invertible:+ raise RuntimeError(+ f"Inverse for {self.__class__.__name__} is not supported: the drawn sub-policy applied "+ f"{', '.join(non_invertible)}, which cannot be inverted. Only geometric operations are "+ "invertible, and the sub-policy is redrawn on every forward pass."+ )+ return super().inverse(input, params, extra_args=extra_args)+def forward_parameters(self, batch_shape: torch.Size) -> List[ParamItem]:"""Generate per-module parameters for one policy forward pass.diff --git a/tests/augmentation/test_auto_operation.py b/tests/augmentation/test_auto_operation.pyindex a33ff5014..28d1e19dd 100644--- a/tests/augmentation/test_auto_operation.py+++ b/tests/augmentation/test_auto_operation.py@@ -31,7 +31,7 @@ from kornia.augmentation.container import AugmentationSequentialfrom kornia.geometry.bbox import bbox_to_maskfrom testing.augmentation.utils import reproducibility_test-from testing.base import BaseTester+from testing.base import BaseTester, assert_closedef _find_all_ops() -> List[OperationBase]:@@ -256,3 +256,88 @@ def test_operation_preserves_input_dtype(device, low_dtype):assert out.dtype == low_dtype, f"{type(op).__name__}: {out.dtype} != {low_dtype}"checked += 1assert checked, f"no op could run in {low_dtype} on this build"+++# AutoAugment sub-policies are ``(name, probability, magnitude_bin)``; the other two are+# ``(name, min_magnitude, max_magnitude)``. RandAugment and TrivialAugment allow only one+# operation per sub-policy, so a mixed draw has to come from two of them -- and cannot+# happen at all under TrivialAugment, which draws exactly one operation.+_AA_GEOMETRIC, _AA_INTENSITY = ("translate_x", 1.0, 5), ("solarize", 1.0, 5)+_GEOMETRIC, _INTENSITY = ("translate_x", -0.5, 0.5), ("solarize", 0.0, 1.0)+++ ("intensity_only", "mixed", "geometry_only"),+ [+ (+ lambda: AutoAugment(policy=[[_AA_INTENSITY]]),+ lambda: AutoAugment(policy=[[_AA_GEOMETRIC, _AA_INTENSITY]]),+ lambda: AutoAugment(policy=[[_AA_GEOMETRIC]]),+ ),+ (+ lambda: RandAugment(n=1, m=15, policy=[[_INTENSITY]]),+ lambda: RandAugment(n=2, m=15, policy=[[_GEOMETRIC], [_INTENSITY]]),+ lambda: RandAugment(n=1, m=15, policy=[[_GEOMETRIC]]),+ ),+ (+ lambda: TrivialAugment(policy=[[_INTENSITY]]),+ None,+ lambda: TrivialAugment(policy=[[_GEOMETRIC]]),+ ),+ ],+ ids=["AutoAugment", "RandAugment", "TrivialAugment"],+)+def test_inverse_refuses_a_non_invertible_draw(intensity_only, mixed, geometry_only, device, dtype):+ # ``inverse`` can only undo geometric operations. The sub-policy is redrawn on every+ # forward pass, so a draw holding an intensity operation used to come back through+ # ``inverse`` with that operation still applied -- and on a draw with no geometry at+ # all, as the input unchanged, with no error and no warning. It refuses now, the way+ # ``MixAugmentationBaseV2.inverse`` already does.+ x = torch.rand(2, 3, 8, 6, device=device, dtype=dtype)++ aug = intensity_only()+ with pytest.raises(RuntimeError, match="is not supported"):+ aug.inverse(aug(x))++ if mixed is not None:+ # half-undoing a mixed draw is the same trap, so it is refused too+ aug = mixed()+ with pytest.raises(RuntimeError, match="is not supported"):+ aug.inverse(aug(x))++ # a geometry-only draw still inverts. A ramp is what bilinear resampling reproduces+ # exactly, so replaying the same draw backwards has to return it -- everywhere except+ # the pixels the draw pushed out of frame, which the same round trip over ``ones``+ # marks for us. Half precision cannot hold that tolerance (``1 - 1e-4`` even rounds to+ # ``1.0`` there), so the value check runs in float32 or wider; the refusals above keep+ # the fixture dtype.+ aug = geometry_only()+ value_dtype = torch.float32 if dtype in (torch.float16, torch.bfloat16) else dtype+ ramp = 0.5 * (+ torch.linspace(0, 1, 8, device=device, dtype=value_dtype)[:, None]+ + torch.linspace(0, 1, 6, device=device, dtype=value_dtype)+ ).expand(2, 3, 8, 6)+ params = aug.forward_parameters(ramp.shape)+ kept = aug.inverse(aug(torch.ones_like(ramp), params=params), params=params) > 1 - 1e-4+ assert kept.any(), "the drawn geometry pushed the whole image out of frame"+ round_trip = aug.inverse(aug(ramp, params=params), params=params)+ assert_close(round_trip[kept], ramp[kept], rtol=1e-4, atol=1e-4)+++def test_inverse_ignores_an_operation_its_gate_skipped(device, dtype):+ # an intensity operation whose probability gate skipped every sample left the input+ # untouched, so the draw is pure geometry and inverts; applied on any row, it refuses+ x = torch.rand(2, 3, 8, 6, device=device, dtype=dtype)+ aug = AutoAugment(policy=[[("translate_x", 1.0, 5), ("solarize", 0.0, 5)]])+ assert aug.inverse(aug(x)).shape == x.shape++ aug = AutoAugment(policy=[[("translate_x", 1.0, 5), ("solarize", 1.0, 5)]])+ with pytest.raises(RuntimeError, match="applied RandomSolarize"):+ aug.inverse(aug(x))+++def test_inverse_without_a_forward_pass_still_reports_missing_params(device, dtype):+ # the refusal must not shadow the pre-existing error for an un-run policy+ x = torch.rand(2, 3, 8, 6, device=device, dtype=dtype)+ with pytest.raises(ValueError, match="No parameters available"):+ RandAugment(n=1, m=5).inverse(x)