Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

fix(augmentation): make AugmentationSequential torch.export-clean (#3858)

Edgar Riba917f0b1d4d94
diff --git a/kornia/augmentation/container/augment.py b/kornia/augmentation/container/augment.py
index 55eb1822b..b1ddf3add 100644
--- a/kornia/augmentation/container/augment.py
+++ b/kornia/augmentation/container/augment.py
@@ -26,7 +26,7 @@ from kornia.augmentation._3d.base import AugmentationBase3D, RigidAffineAugmenta
from kornia.augmentation.base import _AugmentationBase
from kornia.constants import DataKey, Resample
from kornia.core.ops import eye_like
-from kornia.core.utils import is_autocast_enabled
+from kornia.core.utils import is_autocast_enabled, is_exporting
from kornia.geometry.boxes import Boxes, VideoBoxes
from kornia.geometry.keypoints import Keypoints, VideoKeypoints
@@ -281,7 +281,8 @@ class AugmentationSequential(TransformMatrixMinIn, ImageSequential):
# NOTE: only for images are supported for 3D.
if isinstance(arg, AugmentationBase3D):
self.contains_3d_augmentation = True
- self._transform_matrix = None
+ if not is_exporting():
+ self._transform_matrix = None
self.extra_args = extra_args or {DataKey.MASK: {"resample": Resample.NEAREST, "align_corners": None}}
def clear_state(self) -> None:
@@ -290,7 +291,8 @@ class AugmentationSequential(TransformMatrixMinIn, ImageSequential):
return super().clear_state()
def _update_transform_matrix_for_valid_op(self, module: nn.Module) -> None:
- self._transform_matrices.append(module.transform_matrix)
+ if not is_exporting():
+ self._transform_matrices.append(module.transform_matrix)
def identity_matrix(self, input: torch.Tensor) -> torch.Tensor:
"""Return identity matrix."""
@@ -367,7 +369,8 @@ class AugmentationSequential(TransformMatrixMinIn, ImageSequential):
for arg, dcate in zip(args, data_keys):
if DataKey.get(dcate) in _IMG_OPTIONS:
arg = cast(torch.Tensor, arg)
- self.input_dtype = arg.dtype
+ if not is_exporting():
+ self.input_dtype = arg.dtype
inp.append(arg)
elif DataKey.get(dcate) in _MSK_OPTIONS:
if isinstance(inp, list):
@@ -483,7 +486,8 @@ class AugmentationSequential(TransformMatrixMinIn, ImageSequential):
# Restore it back
self.transform_op.data_keys = self.data_keys
- self._params = params
+ if not is_exporting():
+ self._params = params
if isinstance(original_keys, tuple):
result = {k: v for v, k in zip(outputs, original_keys)}
@@ -531,21 +535,21 @@ class AugmentationSequential(TransformMatrixMinIn, ImageSequential):
in_data_keys = kwargs.get("data_keys", self.data_keys)
data_keys = self.transform_op.preproc_datakeys(in_data_keys)
- if len(data_keys) > 1 and DataKey.INPUT in data_keys:
- # NOTE: we may update it later for more supports of drawing boxes, etc.
- idx = data_keys.index(DataKey.INPUT)
- if output_type == "pt":
- self._output_image = _output_image
- if isinstance(_output_image, dict):
+ if not is_exporting():
+ if len(data_keys) > 1 and DataKey.INPUT in data_keys:
+ idx = data_keys.index(DataKey.INPUT)
+ if output_type == "pt":
+ self._output_image = _output_image
+ if isinstance(_output_image, dict):
+ self._output_image[original_keys[idx]] = _output_image[original_keys[idx]]
+ else:
+ self._output_image[idx] = _output_image[idx]
+ elif isinstance(_output_image, dict):
self._output_image[original_keys[idx]] = _output_image[original_keys[idx]]
else:
self._output_image[idx] = _output_image[idx]
- elif isinstance(_output_image, dict):
- self._output_image[original_keys[idx]] = _output_image[original_keys[idx]]
else:
- self._output_image[idx] = _output_image[idx]
- else:
- self._output_image = _output_image
+ self._output_image = _output_image
else:
_output_image = super(ImageSequential, self).__call__(*inputs, **kwargs)
return _output_image
diff --git a/kornia/augmentation/container/base.py b/kornia/augmentation/container/base.py
index 91182ec68..c63c8e63f 100644
--- a/kornia/augmentation/container/base.py
+++ b/kornia/augmentation/container/base.py
@@ -24,6 +24,7 @@ from torch import nn
import kornia.augmentation as K
from kornia.augmentation.base import _AugmentationBase
+from kornia.core.utils import is_exporting
from kornia.geometry.boxes import Boxes
from kornia.geometry.keypoints import Keypoints
@@ -91,6 +92,8 @@ class BasicSequentialBase(nn.Sequential):
def clear_state(self) -> None:
"""Reset self._params state to None."""
+ if is_exporting():
+ return
self._params = None
# TODO: Implement this for all submodules.
@@ -452,7 +455,8 @@ class ImageSequentialBase(SequentialBase):
input = self.transform_inputs(input, params=params, extra_args=extra_args)
- self._params = params
+ if not is_exporting():
+ self._params = params
return input
@@ -501,11 +505,15 @@ class TransformMatrixMinIn:
)
def _update_transform_matrix(self, transform_matrix: Optional[torch.Tensor]) -> None:
+ if is_exporting():
+ return
if self._transform_matrix is None:
self._transform_matrix = transform_matrix
else:
self._transform_matrix = transform_matrix @ self._transform_matrix
def _reset_transform_matrix_state(self) -> None:
+ if is_exporting():
+ return
self._transform_matrix = None
self._transform_matrices = []
diff --git a/kornia/augmentation/container/image.py b/kornia/augmentation/container/image.py
index 6ead69f6b..3dfe70548 100644
--- a/kornia/augmentation/container/image.py
+++ b/kornia/augmentation/container/image.py
@@ -26,6 +26,7 @@ from kornia.augmentation.utils import override_parameters
from kornia.core import ImageModule
from kornia.core.mixin.image_module import ImageModuleMixIn
from kornia.core.ops import eye_like
+from kornia.core.utils import is_exporting
from .base import ImageSequentialBase
from .params import ParamItem
@@ -416,16 +417,21 @@ def _get_new_batch_shape(param: ParamItem, batch_shape: torch.Size) -> torch.Siz
# Carefully avoid evaluating expression multiple times; batch_prob is often a 1-element torch.Tensor
if "output_size" in data:
+ # Under ``torch.export`` the sampled ``output_size`` is an unbacked tensor, so the tracked
+ # shape can't be turned into a static ``torch.Size``. Skip the shape-tracking entirely:
+ # it only feeds parameter generation for *subsequent* children, and export runs on concrete
+ # tensors, so a shape-changing transform followed by nothing shape-dependent is unaffected.
+ if is_exporting():
+ return batch_shape
# Inline check for common PyTorch float torch.Tensor case
batch_prob = data.get("batch_prob", None)
- if batch_prob is not None:
- # Avoid repeated indexing, always fetch scalar efficiently
- prob = batch_prob.item() if batch_prob.numel() == 1 else batch_prob[0].item()
- if prob <= 0.5:
- return batch_shape
- else:
+ if batch_prob is None:
# batch_prob missing, fallback do not update shape
return batch_shape
+ # Avoid repeated indexing, always fetch scalar efficiently
+ prob = batch_prob.item() if batch_prob.numel() == 1 else batch_prob[0].item()
+ if prob <= 0.5:
+ return batch_shape
# Mutate only last two dims
new_batch_shape = list(batch_shape)
new_batch_shape[-2:] = data["output_size"][0]
diff --git a/kornia/core/module.py b/kornia/core/module.py
index fc6ac4d35..70674f8b1 100644
--- a/kornia/core/module.py
+++ b/kornia/core/module.py
@@ -23,6 +23,7 @@ from torch import nn
from .mixin.image_module import ImageModuleMixIn
from .mixin.onnx import ONNXExportMixin
+from .utils import is_exporting
class ImageModule(nn.Module, ImageModuleMixIn, ONNXExportMixin):
@@ -93,10 +94,13 @@ class ImageModule(nn.Module, ImageModuleMixIn, ONNXExportMixin):
input_names_to_handle=input_names_to_handle, output_type=output_type
)(super().__call__)
_output_image = decorated_forward(*inputs, **kwargs)
- if output_type == "pt":
- self._output_image = self._detach_tensor_to_cpu(_output_image)
- else:
- self._output_image = _output_image
+ if not is_exporting():
+ # ``_output_image`` is an eager-only cache for ``.plot()``; storing it mutates
+ # module state, which ``torch.export`` (torch <= 2.9) rejects inside ``forward``.
+ if output_type == "pt":
+ self._output_image = self._detach_tensor_to_cpu(_output_image)
+ else:
+ self._output_image = _output_image
else:
_output_image = super().__call__(*inputs, **kwargs)
return _output_image
@@ -170,10 +174,13 @@ class ImageSequential(nn.Sequential, ImageModuleMixIn, ONNXExportMixin):
input_names_to_handle=input_names_to_handle, output_type=output_type
)(super().__call__)
_output_image = decorated_forward(*inputs, **kwargs)
- if output_type == "pt":
- self._output_image = self._detach_tensor_to_cpu(_output_image)
- else:
- self._output_image = _output_image
+ if not is_exporting():
+ # ``_output_image`` is an eager-only cache for ``.plot()``; storing it mutates
+ # module state, which ``torch.export`` (torch <= 2.9) rejects inside ``forward``.
+ if output_type == "pt":
+ self._output_image = self._detach_tensor_to_cpu(_output_image)
+ else:
+ self._output_image = _output_image
else:
_output_image = super().__call__(*inputs, **kwargs)
return _output_image
diff --git a/tests/augmentation/test_torch_export.py b/tests/augmentation/test_torch_export.py
index a0ba78336..b66cdd893 100644
--- a/tests/augmentation/test_torch_export.py
+++ b/tests/augmentation/test_torch_export.py
@@ -86,3 +86,36 @@ def test_torch_export_deterministic(name: str, factory: Callable[[], torch.nn.Mo
out = exported.module()(x)
assert out.shape == eager.shape, f"{name}: shape {out.shape} vs {eager.shape}"
torch.testing.assert_close(out, eager, atol=1e-5, rtol=1e-5)
+
+
+def _seq_pointwise() -> torch.nn.Module:
+ return K.AugmentationSequential(_normalize(), K.RandomBrightness((1.2, 1.2), p=1.0), data_keys=["input"])
+
+
+def _seq_resize() -> torch.nn.Module:
+ return K.AugmentationSequential(_normalize(), K.Resize((16, 16)), data_keys=["input"])
+
+
+def _seq_crop_pad() -> torch.nn.Module:
+ return K.AugmentationSequential(_normalize(), K.CenterCrop(20), K.PadTo((24, 24)), data_keys=["input"])
+
+
+TORCH_EXPORT_CONTAINERS: list[Tuple[str, Callable[[], torch.nn.Module]]] = [
+ ("Seq[Norm,Bright]", _seq_pointwise),
+ ("Seq[Norm,Resize]", _seq_resize),
+ ("Seq[Norm,CenterCrop,PadTo]", _seq_crop_pad),
+]
+
+
[email protected](not hasattr(torch, "export"), reason="torch.export requires torch>=2.1")
[email protected]("name,factory", TORCH_EXPORT_CONTAINERS, ids=[n for n, _ in TORCH_EXPORT_CONTAINERS])
+def test_torch_export_container(name: str, factory: Callable[[], torch.nn.Module]) -> None:
+ """A deterministic ``AugmentationSequential`` pipeline captures via ``torch.export`` and matches eager."""
+ torch.manual_seed(0)
+ x = torch.randn(1, 3, 32, 32)
+ seq = factory()
+ eager = seq(x)
+ exported = torch.export.export(seq, (x,))
+ out = exported.module()(x)
+ assert out.shape == eager.shape, f"{name}: shape {out.shape} vs {eager.shape}"
+ torch.testing.assert_close(out, eager, atol=1e-5, rtol=1e-5)