Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

fix(augmentation): make deterministic transforms torch.export-clean (#3856)

Edgar Riba2054b7ea4e3f
diff --git a/kornia/augmentation/_2d/base.py b/kornia/augmentation/_2d/base.py
index 233bdf1bb..60ed3cf09 100644
--- a/kornia/augmentation/_2d/base.py
+++ b/kornia/augmentation/_2d/base.py
@@ -23,7 +23,7 @@ from torch import float16, float32, float64
from kornia.augmentation.base import _AugmentationBase
from kornia.augmentation.utils import _transform_input, _transform_input_by_shape, _validate_input_dtype
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
from kornia.geometry.keypoints import Keypoints
@@ -197,13 +197,15 @@ class RigidAffineAugmentationBase2D(AugmentationBase2D):
# apply_transform ignores the matrix for these ops, so don't build it here; defer to
# the first `.transform_matrix` access (e.g. AugmentationSequential propagating to
# boxes/keypoints/masks). A standalone flip that never reads the matrix skips it.
- self._transform_matrix = None
- self._lazy_matrix_args = (in_tensor, params, flags)
+ if not is_exporting():
+ self._transform_matrix = None
+ self._lazy_matrix_args = (in_tensor, params, flags)
return self.transform_inputs(in_tensor, params, flags, None)
trans_matrix = self.generate_transformation_matrix(in_tensor, params, flags)
output = self.transform_inputs(in_tensor, params, flags, trans_matrix)
- self._transform_matrix = trans_matrix
- self._lazy_matrix_args = None
+ if not is_exporting():
+ self._transform_matrix = trans_matrix
+ self._lazy_matrix_args = None
return output
diff --git a/kornia/augmentation/base.py b/kornia/augmentation/base.py
index d1f9819a8..d72e52d22 100644
--- a/kornia/augmentation/base.py
+++ b/kornia/augmentation/base.py
@@ -26,7 +26,7 @@ from kornia.augmentation.utils import (
_transform_output_shape,
override_parameters,
)
-from kornia.core.utils import is_autocast_enabled
+from kornia.core.utils import is_autocast_enabled, is_exporting
from kornia.geometry.boxes import Boxes
from kornia.geometry.keypoints import Keypoints
@@ -223,9 +223,11 @@ class _BasicAugmentationBase(nn.Module):
if save_kwargs:
params = override_parameters(params, kwargs, in_place=True)
- self._params = params
+ if not is_exporting():
+ self._params = params
else:
- self._params = params
+ if not is_exporting():
+ self._params = params
params = override_parameters(params, kwargs, in_place=False)
flags = override_parameters(flags, kwargs, in_place=False)
diff --git a/kornia/core/utils.py b/kornia/core/utils.py
index 427c12774..3e0e50317 100644
--- a/kornia/core/utils.py
+++ b/kornia/core/utils.py
@@ -355,6 +355,20 @@ def is_autocast_enabled(both: bool = True) -> bool:
return torch.is_autocast_enabled()
+# ``torch.compiler.is_exporting`` is absent on very old torch; resolve it once at import.
+_torch_is_exporting = getattr(torch.compiler, "is_exporting", None)
+
+
+def is_exporting() -> bool:
+ """Whether execution is inside a ``torch.export`` capture.
+
+ Used to skip in-``forward`` side effects (e.g. stashing per-call state on ``self``) that
+ ``torch.export`` on torch <= 2.9 rejects, without changing the captured output. Returns
+ ``False`` on torch versions where ``torch.compiler.is_exporting`` is unavailable.
+ """
+ return bool(_torch_is_exporting()) if _torch_is_exporting is not None else False
+
+
def dataclass_to_dict(obj: Any) -> Any:
"""Recursively convert dataclass instances to dictionaries."""
if is_dataclass(obj) and not isinstance(obj, type):
diff --git a/tests/augmentation/test_torch_export.py b/tests/augmentation/test_torch_export.py
index 3b2f68776..a0ba78336 100644
--- a/tests/augmentation/test_torch_export.py
+++ b/tests/augmentation/test_torch_export.py
@@ -22,17 +22,16 @@ with its preprocessing (Normalize / Resize / CenterCrop / Pad) as a single expor
TorchGeo migrated its inference-time transforms off kornia onto ``torchvision.transforms.v2``
citing exactly this gap ("kornia augmentations can't be torch.exported").
-Status: this does **not** work yet on the torch versions kornia's CI runs (<= 2.9). The
-augmentation base ``forward`` assigns state on ``self`` (``self._params``, and the lazy
-``_transform_matrix`` / ``_lazy_matrix_args``), and ``torch.export`` on torch <= 2.9 rejects
-modules that create/mutate attributes in ``forward`` ("attrs were created in model.forward",
-then a pytree "Node arity mismatch"). torch 2.10 relaxes the first restriction (export then only
-*warns*), so this can pass locally on a newer wheel while failing in CI β€” hence the ``xfail``
-below. A real fix means making the deterministic ``forward`` path export-clean (no per-call state
-assignment). When that lands, this flips to ``xpass`` and the ``xfail`` should be removed.
-
-Only *deterministic* transforms are covered β€” random augmentations sample parameters during
-capture in ways that don't line up with a separate eager call, which is RNG bookkeeping.
+The augmentation base ``forward`` stashes per-call state on ``self`` (``_params`` and the lazy
+transform matrix), which ``torch.export`` on torch <= 2.9 rejects ("attrs created in forward" /
+pytree "Node arity mismatch"). Those side effects are now skipped under ``torch.export`` (the
+captured image output is unchanged), so the deterministic transforms export cleanly and
+numerically match eager. This pins that so it does not regress.
+
+Only *deterministic single* transforms are covered β€” random augmentations sample parameters
+during capture in ways that don't line up with a separate eager call (RNG bookkeeping), and
+``AugmentationSequential`` containers still stash their own per-call state and are not export-clean
+yet.
"""
from __future__ import annotations
@@ -74,11 +73,6 @@ TORCH_EXPORT_DETERMINISTIC: list[Tuple[str, Callable[[], torch.nn.Module]]] = [
]
- reason="augmentation forward assigns state on self; torch.export rejects this on torch<=2.9 "
- "(CI). Passes on torch>=2.10. Remove this mark once forward is export-clean.",
- strict=False,
-)
@pytest.mark.skipif(not hasattr(torch, "export"), reason="torch.export requires torch>=2.1")
@pytest.mark.parametrize("name,factory", TORCH_EXPORT_DETERMINISTIC, ids=[n for n, _ in TORCH_EXPORT_DETERMINISTIC])
def test_torch_export_deterministic(name: str, factory: Callable[[], torch.nn.Module]) -> None: