Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

fix(augmentation): correct + clean up the torch.export container path (#3861)

Edgar Ribaef6a5d47eb77
diff --git a/kornia/augmentation/container/augment.py b/kornia/augmentation/container/augment.py
index b1ddf3add..216b23e4e 100644
--- a/kornia/augmentation/container/augment.py
+++ b/kornia/augmentation/container/augment.py
@@ -281,8 +281,7 @@ class AugmentationSequential(TransformMatrixMinIn, ImageSequential):
# NOTE: only for images are supported for 3D.
if isinstance(arg, AugmentationBase3D):
self.contains_3d_augmentation = True
- if not is_exporting():
- self._transform_matrix = None
+ self._transform_matrix = None
self.extra_args = extra_args or {DataKey.MASK: {"resample": Resample.NEAREST, "align_corners": None}}
def clear_state(self) -> None:
@@ -539,11 +538,9 @@ class AugmentationSequential(TransformMatrixMinIn, ImageSequential):
if len(data_keys) > 1 and DataKey.INPUT in data_keys:
idx = data_keys.index(DataKey.INPUT)
if output_type == "pt":
+ # ``self._output_image`` already holds ``_output_image`` here, so the old
+ # per-key rebind was a no-op; just store the whole output.
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:
diff --git a/kornia/augmentation/container/image.py b/kornia/augmentation/container/image.py
index 3dfe70548..6ef43bb7f 100644
--- a/kornia/augmentation/container/image.py
+++ b/kornia/augmentation/container/image.py
@@ -274,7 +274,7 @@ class ImageSequential(ImageSequentialBase, ImageModuleForSequentialMixIn):
param = ParamItem(name, mod_param)
else:
param = ParamItem(name, None)
- batch_shape = _get_new_batch_shape(param, batch_shape)
+ batch_shape = _get_new_batch_shape(param, batch_shape, module)
params.append(param)
return params
@@ -398,7 +398,7 @@ class ImageSequential(ImageSequentialBase, ImageModuleForSequentialMixIn):
return _output_image
-def _get_new_batch_shape(param: ParamItem, batch_shape: torch.Size) -> torch.Size:
+def _get_new_batch_shape(param: ParamItem, batch_shape: torch.Size, module: Optional[nn.Module] = None) -> torch.Size:
"""Get the new batch shape if the augmentation changes the image size.
Note:
@@ -417,12 +417,18 @@ 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
+ # The sampled ``output_size`` is an unbacked tensor under export (no python int for
+ # ``torch.Size``). Use the module's static ``flags["size"]`` β€” known at construction β€”
+ # so the tracked shape stays correct for a *subsequent* shape-dependent child (e.g. a
+ # resample-mode crop after a resize). Fall back to leaving the shape unchanged when the
+ # size isn't statically available.
+ size = getattr(module, "flags", {}).get("size") if module is not None else None
+ if size is None:
+ return batch_shape
+ new_batch_shape = list(batch_shape)
+ new_batch_shape[-2:] = size
+ return torch.Size(new_batch_shape)
# Inline check for common PyTorch float torch.Tensor case
batch_prob = data.get("batch_prob", None)
if batch_prob is None:
diff --git a/kornia/core/mixin/image_module.py b/kornia/core/mixin/image_module.py
index 0629af25f..14aeef8d4 100644
--- a/kornia/core/mixin/image_module.py
+++ b/kornia/core/mixin/image_module.py
@@ -25,6 +25,7 @@ import torch
from kornia.core.external import PILImage as Image
from kornia.core.external import numpy as np
+from kornia.core.utils import is_exporting
class ImageModuleMixIn:
@@ -199,6 +200,16 @@ class ImageModuleMixIn:
return type(output_image)([self._detach_tensor_to_cpu(out) for out in output_image]) # type: ignore
raise RuntimeError(f"Unexpected object {output_image} with a type of `{type(output_image)}`")
+ def _store_output_image(self, output_image: Any, output_type: str) -> None:
+ """Cache the forward output for the ``.plot()`` / ``.show()`` helpers.
+
+ Skipped inside a ``torch.export`` capture: caching mutates module state in ``forward``,
+ which ``torch.export`` (torch <= 2.9) rejects. The captured output is unaffected.
+ """
+ if is_exporting():
+ return
+ self._output_image = self._detach_tensor_to_cpu(output_image) if output_type == "pt" else output_image
+
def show(self, n_row: Optional[int] = None, backend: str = "pil", display: bool = True) -> Optional[Any]:
"""Return PIL images.
diff --git a/kornia/core/module.py b/kornia/core/module.py
index 70674f8b1..ac4091b1a 100644
--- a/kornia/core/module.py
+++ b/kornia/core/module.py
@@ -23,7 +23,6 @@ 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):
@@ -94,13 +93,7 @@ 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 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
+ self._store_output_image(_output_image, output_type)
else:
_output_image = super().__call__(*inputs, **kwargs)
return _output_image
@@ -174,13 +167,7 @@ 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 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
+ self._store_output_image(_output_image, output_type)
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 b66cdd893..9464e1382 100644
--- a/tests/augmentation/test_torch_export.py
+++ b/tests/augmentation/test_torch_export.py
@@ -100,10 +100,18 @@ def _seq_crop_pad() -> torch.nn.Module:
return K.AugmentationSequential(_normalize(), K.CenterCrop(20), K.PadTo((24, 24)), data_keys=["input"])
+def _seq_resize_then_resample_crop() -> torch.nn.Module:
+ # A resample-mode crop bakes its geometry from the *tracked* batch shape at parameter-generation
+ # time, so a preceding size change must update that shape under export β€” otherwise the crop uses
+ # the stale pre-resize shape and the exported output silently diverges from eager.
+ return K.AugmentationSequential(K.Resize((16, 16)), K.CenterCrop(8, cropping_mode="resample"), 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),
+ ("Seq[Resize,CenterCrop-resample]", _seq_resize_then_resample_crop),
]