Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

fix(onnx): to_onnx keeps the augmentations' per-call parameters and transforms, and the random state (#6163)

Dmytro Mishkinf98db7a1d31a
diff --git a/changelog.d/6163.fixed.md b/changelog.d/6163.fixed.md
new file mode 100644
index 000000000..b5eb5326a
--- /dev/null
+++ b/changelog.d/6163.fixed.md
@@ -0,0 +1 @@
+`to_onnx` keeps the parameters and transformation matrices that augmentations and their containers stored from their last call, so `inverse()` and `transform_matrix` after an export still describe that call. The export's run on its dummy input used to replace them: after a legacy TorchScript export (the default before torch 2.9, `dynamo=False` from it), `inverse()` raised or inverted the dummy's transform. They now come back as the same objects with the same items, also when the export fails, as the `show()` / `save()` output cache now does (#6130). The export also gives back the global random state it drew from, so the draws after it are the ones they would be without it; it removes the global buffer-registration hook that torch 2.9's `torch.export` leaves after a failed trace, which made every later `torch.compile(..., fullgraph=True)` that registers a buffer raise `Unsupported`; and `RandomResizedCrop` no longer stores each call's crop sizes on its generator, where a torch 2.9 dynamo export left a fake tensor that made `deepcopy` and `pickle` raise.
diff --git a/kornia/augmentation/random_generator/_2d/crop.py b/kornia/augmentation/random_generator/_2d/crop.py
index 571eedb43..a16908537 100644
--- a/kornia/augmentation/random_generator/_2d/crop.py
+++ b/kornia/augmentation/random_generator/_2d/crop.py
@@ -76,9 +76,14 @@ class CropGenerator(RandomGeneratorBase):
)
def forward(self, batch_shape: Tuple[int, ...], same_on_batch: bool = False) -> Dict[str, torch.Tensor]:
+ return self._crop_parameters(batch_shape, same_on_batch, self.size)
+
+ def _crop_parameters(
+ self, batch_shape: Tuple[int, ...], same_on_batch: bool, crop_size: Union[Tuple[int, int], torch.Tensor]
+ ) -> Dict[str, torch.Tensor]:
batch_size = batch_shape[0]
_common_param_check(batch_size, same_on_batch)
- _device, _dtype = _extract_device_dtype([self.size if isinstance(self.size, torch.Tensor) else None])
+ _device, _dtype = _extract_device_dtype([crop_size if isinstance(crop_size, torch.Tensor) else None])
if batch_size == 0:
return {
@@ -87,14 +92,14 @@ class CropGenerator(RandomGeneratorBase):
}
input_size = (batch_shape[-2], batch_shape[-1])
- if not isinstance(self.size, torch.Tensor):
- size = _constant_tensor(self.size, device=_device, dtype=_dtype).repeat(batch_size, 1)
+ if not isinstance(crop_size, torch.Tensor):
+ size = _constant_tensor(crop_size, device=_device, dtype=_dtype).repeat(batch_size, 1)
if size.shape != torch.Size([batch_size, 2]):
raise AssertionError(
- f"`size` must be a (height, width) pair of integers or a (B, 2) tensor. Got {self.size!r}."
+ f"`size` must be a (height, width) pair of integers or a (B, 2) tensor. Got {crop_size!r}."
)
else:
- size = self.size.to(device=_device, dtype=_dtype)
+ size = crop_size.to(device=_device, dtype=_dtype)
if size.shape != torch.Size([batch_size, 2]):
raise AssertionError(
"If `size` is a torch.Tensor, it must be shaped as (B, 2). "
@@ -176,7 +181,11 @@ class ResizedCropGenerator(CropGenerator):
Returns:
params Dict[str, torch.Tensor]: parameters to be passed for transformation.
- - size (torch.Tensor): element-wise cropping sizes with a shape of (B, 2).
+ - src (torch.Tensor): cropping bounding boxes with a shape of (B, 4, 2).
+ - dst (torch.Tensor): output bounding boxes with a shape of (B, 4, 2).
+ - input_size (torch.Tensor): the input's (height, width), repeated to a shape of (B, 2).
+ - output_size (torch.Tensor): ``output_size``, repeated to a shape of (B, 2).
+ An empty batch gives ``src`` and ``dst`` of shape (0, 4, 2) and a ``size`` of shape (0, 2) instead.
Note:
The generated random numbers are not reproducible across different devices and dtypes.
@@ -311,9 +320,9 @@ class ResizedCropGenerator(CropGenerator):
h_out = torch.clamp(h_out, min=1, max=size[0])
w_out = torch.clamp(w_out, min=1, max=size[1])
- # Update the crop size.
- self.size = torch.stack([h_out, w_out], dim=1)
- return super().forward(batch_shape, same_on_batch)
+ # The drawn crop sizes are this call's, so they are passed on rather than stored on the generator, whose
+ # ``size`` stays the output size it was built with.
+ return self._crop_parameters(batch_shape, same_on_batch, torch.stack([h_out, w_out], dim=1))
def center_crop_generator(
diff --git a/kornia/contrib/object_detection.py b/kornia/contrib/object_detection.py
index 9a746e018..4374e355b 100644
--- a/kornia/contrib/object_detection.py
+++ b/kornia/contrib/object_detection.py
@@ -32,7 +32,8 @@ from kornia.core.mixin.onnx import (
ONNXExportMixin,
_eval_mode,
_first_floating_tensor,
- _preserved_output_caches,
+ _preserved_call_state,
+ _preserved_rng,
_to_floating,
_uses_dynamic_shapes,
)
@@ -137,15 +138,16 @@ def _returns_detections_per_image(detector: nn.Module, images: torch.Tensor) ->
"""Return whether ``detector`` returns a list of per-image detections for ``images`` rather than one tensor.
The detector runs once, in eval mode and without gradients, on ``images`` moved to the dtype and device of its first
- floating tensor, as the export's dummy input is. Its output decides, so any post-processor is covered. The output
- cache of every image module inside it is left as it was.
+ floating tensor, as the export's dummy input is. Its output decides, so any post-processor is covered. The
+ attributes that ``to_onnx`` keeps, such as an image module's output cache, hold what they held before, in every
+ module inside the detector, and so does the global random state.
"""
reference = _first_floating_tensor(detector)
if reference is not None:
images = _to_floating(images, reference)
- # The run must not leave its output in the cache of an image module inside the detector, as the export's own
- # run does not.
- with _eval_mode(detector), _preserved_output_caches(detector), torch.no_grad():
+ # The run must not leave its output or parameters in a module inside the detector, nor consume the global random
+ # state, as the export's own run does not.
+ with _eval_mode(detector), _preserved_call_state(detector), _preserved_rng(), torch.no_grad():
return isinstance(detector(images), list)
@@ -294,8 +296,10 @@ class ObjectDetector(ModelBase, ONNXExportMixin):
# Exported for a dynamic batch, a per-image list comes out as the traced batch's detections, or the export
# fails: such a detector is exported for one image.
batch = -1
- if include_pre_and_post_processor and _returns_detections_per_image(self, torch.rand(pseudo_shape)):
- batch = 1
+ # The probe's input draws from the global generator, as the export's dummy does, and gives back what it drew.
+ with _preserved_rng():
+ if include_pre_and_post_processor and _returns_detections_per_image(self, torch.rand(pseudo_shape)):
+ batch = 1
input_shape = [batch, 3, image_size or -1, image_size or -1]
output_names = None if include_pre_and_post_processor else getattr(self.model, "ONNX_OUTPUT_NAMES", None)
diff --git a/kornia/core/mixin/onnx.py b/kornia/core/mixin/onnx.py
index eedae77db..ca6322134 100644
--- a/kornia/core/mixin/onnx.py
+++ b/kornia/core/mixin/onnx.py
@@ -208,30 +208,102 @@ def _eval_mode(module: Any) -> Iterator[None]:
submodule.training = training
-_NO_OUTPUT_CACHE = object()
+# The attributes in which a module keeps what its last call stored for later reads: the output cache that ``show()`` /
+# ``save()`` render; the parameters that ``inverse()`` and a replay use; an augmentation's transformation matrix, built
+# or lazy, with the params dict and values it was computed from, which the containers' annotation handlers match
+# against; a container's per-child matrices; and ``AugmentationSequential``'s input and mask dtypes. A test in
+# ``tests/core/test_onnx_mixin.py`` fails when an augmentation writes an attribute outside its constructor that is
+# neither listed here nor classified there.
+_PER_CALL_STATE = (
+ "_output_image",
+ "_params",
+ "_transform_matrix",
+ "_lazy_matrix_args",
+ "_transform_matrix_params",
+ "_transform_matrix_params_snapshot",
+ "_transform_matrices",
+ "input_dtype",
+ "mask_dtype",
+)
-def _preserved_output_caches(module: Any) -> Iterator[None]:
- """Keep the ``show()`` / ``save()`` output cache of every module in ``module`` as it was before the block.
+def _items(value: Any) -> Any:
+ """Return a shallow copy of the items of a list or dict ``value``, else ``None``."""
+ if isinstance(value, list):
+ return list(value)
+ if isinstance(value, dict):
+ return dict(value)
+ return None
- The TorchScript exporter runs the module on the dummy input outside ``is_exporting()``, so every image module in
- the tree would cache the dummy's output, ``AugmentationSequential`` included, which writes the attribute itself.
- Each cache gets back the object it held, and a cache the block created on a module that had none is removed.
+
+def _preserved_call_state(module: Any) -> Iterator[None]:
+ """Keep the attributes in ``_PER_CALL_STATE`` of every module in ``module`` as they were before the block.
+
+ An export runs the module on its dummy input. The TorchScript exporter does so outside ``is_exporting()``, so each
+ module in the tree would store the dummy's output, parameters and matrices, and the dynamo exporter can put copies
+ back in place of them. Each listed attribute gets back the object it held, and one the block stored on a module
+ that had none is removed, so a class-level default shows through again. A list or dict also gets back its items:
+ under a capture, where ``is_exporting()`` skips their reset, the policy containers append to
+ ``_transform_matrices`` in place.
"""
- caches = (
- [(m, m.__dict__.get("_output_image", _NO_OUTPUT_CACHE)) for m in module.modules()]
+ saved = (
+ [
+ (m, {name: (m.__dict__[name], _items(m.__dict__[name])) for name in _PER_CALL_STATE if name in m.__dict__})
+ for m in module.modules()
+ ]
if isinstance(module, nn.Module)
else []
)
try:
yield
finally:
- for submodule, cache in caches:
- if cache is _NO_OUTPUT_CACHE:
- submodule.__dict__.pop("_output_image", None)
- else:
- submodule.__dict__["_output_image"] = cache
+ for submodule, state in saved:
+ for name in _PER_CALL_STATE:
+ if name not in state:
+ submodule.__dict__.pop(name, None)
+ continue
+ value, items = state[name]
+ if isinstance(value, list):
+ value[:] = items
+ elif isinstance(value, dict):
+ value.clear()
+ value.update(items)
+ submodule.__dict__[name] = value
+
+
+def _preserved_rng() -> Iterator[None]:
+ """Put back the global random state the block draws from.
+
+ That is the CPU generator, every CUDA device's once CUDA is initialized (an augmentation moved to a device draws
+ there even without parameters), and the MPS generator where MPS is available.
+ """
+ cuda_devices = list(range(torch.cuda.device_count())) if torch.cuda.is_initialized() else []
+ with contextlib.ExitStack() as stack:
+ # ``fork_rng`` always restores the CPU generator; the device type picks the accelerator it also restores.
+ stack.enter_context(torch.random.fork_rng(devices=cuda_devices, device_type="cuda"))
+ if torch.backends.mps.is_available():
+ stack.enter_context(torch.random.fork_rng(devices=[0], device_type="mps"))
+ yield
+
+
+def _removed_buffer_hooks() -> Iterator[None]:
+ """Remove the global buffer-registration hooks the block adds.
+
+ torch 2.9's non-strict ``torch.export`` registers one and removes it only when its trace succeeds, and the dynamo
+ ONNX exporter starts with that trace, also when a later strategy then exports the model. Left behind, the hook runs
+ in every later Dynamo trace that registers a buffer, which then raises ``Unsupported``.
+ """
+ hooks = getattr(torch.nn.modules.module, "_global_buffer_registration_hooks", None)
+ before = set(hooks) if hooks is not None else set()
+ try:
+ yield
+ finally:
+ if hooks is not None:
+ for key in set(hooks) - before:
+ del hooks[key]
class ONNXExportMixin:
@@ -317,8 +389,17 @@ class ONNXExportMixin:
The one opt-out is ``training=torch.onnx.TrainingMode.TRAINING``, which torch deprecates: the legacy
TorchScript exporter (the default before torch 2.9, ``dynamo=False`` from it) then exports the
training-mode graph. The dynamo exporter does not read ``training``.
- - The output cache that ``show()`` and ``save()`` read is kept: every image module in the exported module
- holds the same cached object afterwards as before, also when the export fails.
+ - The export runs the model on the dummy input, but these attributes of every module in the exported
+ model keep the objects they held, with the same items, also when the export fails: the output cache
+ that ``show()`` and ``save()`` read, and the parameters and transformation matrices that an
+ augmentation's ``inverse()`` and ``transform_matrix`` read. Other attributes a module writes in its
+ ``forward`` can hold what the run on the dummy left.
+ - The global random state (the CPU generator, the CUDA devices' once CUDA is initialized, and the MPS
+ generator where MPS is available) is restored after the dummy is drawn and after the export, so the
+ draws that follow are the ones they would be without the export.
+ - A global buffer-registration hook that the export leaves behind is removed, also when the export
+ fails: torch 2.9's ``torch.export`` keeps it after a failed trace, and every later Dynamo trace in the
+ process that registers a buffer would raise ``Unsupported`` on it.
- The export requests ONNX opset 18, which the dynamo exporter (the default of `torch.onnx.export`
from torch 2.9) builds natively and the legacy TorchScript exporter emits directly. Pass
`opset_version` to request another one.
@@ -374,7 +455,9 @@ class ONNXExportMixin:
pseudo_shape = [
max(size, 2) if dim == -1 else size for dim, size in zip(input_shape, resolved_pseudo_shape)
]
- dummy_input = self._create_dummy_input(input_shape, pseudo_shape)
+ # The dummy and the export's run on it draw from the global generators; both give back what they drew.
+ with _preserved_rng():
+ dummy_input = self._create_dummy_input(input_shape, pseudo_shape)
reference = _first_floating_tensor(module)
if reference is not None:
dummy_input = _to_floating(dummy_input, reference)
@@ -395,9 +478,15 @@ class ONNXExportMixin:
# The dynamo exporter captures the model in whatever mode it is in, so a model left in training mode would
# export active Dropout. Each submodule's own flag is restored, since ``train(True)`` would reset them all, and
- # so is each image module's output cache, which the TorchScript exporter's run on the dummy overwrites.
+ # so is the state each module keeps from its last call, which the exporters' run on the dummy replaces.
# A file path rather than a buffer: exporting to ``io.BytesIO`` is deprecated from torch 2.9.
- with _eval_mode(module), _preserved_output_caches(module), tempfile.TemporaryDirectory() as tmp_dir:
+ with (
+ _eval_mode(module),
+ _preserved_call_state(module),
+ _preserved_rng(),
+ _removed_buffer_hooks(),
+ tempfile.TemporaryDirectory() as tmp_dir,
+ ):
tmp_path = os.path.join(tmp_dir, "model.onnx")
torch.onnx.export(
module,
diff --git a/tests/core/test_onnx_mixin.py b/tests/core/test_onnx_mixin.py
index f9aea9bc4..3e8d59874 100644
--- a/tests/core/test_onnx_mixin.py
+++ b/tests/core/test_onnx_mixin.py
@@ -17,18 +17,22 @@
"""Export and runtime contract of the ONNX mixins, checked end to end through onnxruntime."""
+import ast
import copy
+import pickle
+from pathlib import Path
import pytest
import torch
from torch import nn
+import kornia
from kornia.core import ImageSequential
from kornia.core._compat import torch_version_ge
from kornia.core.mixin.onnx import ONNXMixin, ONNXRuntimeMixin
from kornia.filters import GaussianBlur2d
-from testing.base import BaseTester
+from testing.base import DYNAMO_UNAVAILABLE_REASON, BaseTester, dynamo_is_available
onnx = pytest.importorskip("onnx")
ort = pytest.importorskip("onnxruntime")
@@ -58,6 +62,116 @@ def _cache_of(module):
return module.__dict__.get("_output_image", _NO_CACHE)
+# What a module keeps from its last call and reads back afterwards (#6140): the output cache of ``show()`` / ``save()``;
+# the parameters ``inverse()`` replays; the transformation matrix, built or lazy, and the params dict and values it was
+# computed from, which the containers' annotation handlers match against; a container's per-child matrices; and
+# ``AugmentationSequential``'s input and mask dtypes.
+_CALL_STATE = (
+ "_output_image",
+ "_params",
+ "_transform_matrix",
+ "_lazy_matrix_args",
+ "_transform_matrix_params",
+ "_transform_matrix_params_snapshot",
+ "_transform_matrices",
+ "input_dtype",
+ "mask_dtype",
+)
+
+
+def _call_state_of(module):
+ # Each of those attributes as stored on the module itself; a class-level default is not an entry.
+ return {name: module.__dict__[name] for name in _CALL_STATE if name in module.__dict__}
+
+
+def _same_objects(state, before):
+ return state.keys() == before.keys() and all(state[name] is before[name] for name in state)
+
+
+def _composed(matrices):
+ # The product a container's lazy ``transform_matrix`` builds from its per-child matrices, in execution order.
+ product = matrices[0]
+ for matrix in matrices[1:]:
+ product = matrix @ product
+ return product
+
+
+# What an augmentation or image module writes on itself outside ``__init__`` and ``make_samplers`` that is not state of
+# its last call, so ``to_onnx`` leaves it alone: per writing method, the attributes and the reason. A name in
+# ``_PER_CALL_STATE`` is exempt in every method, since ``to_onnx`` restores it on any module; any other name is
+# classified for the method that writes it, so the same name written by a new method (``self.p`` in a ``forward``)
+# fails the test. Writes the scan does not see: ``setattr`` and ``self.__dict__[...]``, a write through another name
+# (a container setting ``mod.keepdim``), and a ``for self.x in`` target.
+_NOT_CALL_STATE = {
+ "ColorJitter.compile": (
+ ("_brightness_fn", "_contrast_fn", "_saturation_fn", "_hue_fn", "_cond_fn"),
+ "the compiled kernels",
+ ),
+ "RandomGaussianBlur.compile": (("_gaussian_blur2d_fn",), "the compiled kernel"),
+ "RandomGaussianIllumination.compile": (("_fn",), "the compiled kernel"),
+ "_PicklableCompileMixin._record_compile": (("_compile_kwargs", "_uncompiled_fns"), "compile() records its options"),
+ "_PicklableCompileMixin.__setstate__": (("_uncompiled_fns",), "unpickling"),
+ "AugmentationSequentialOps.data_keys": (
+ ("_data_keys",),
+ "a property setter, which the container calls to set its data keys back before each call returns",
+ ),
+ "ImageModuleForSequentialMixIn.disable_features": (("_disable_features",), "a property setter"),
+ "ImageModule.disable_features": (("_disable_features",), "a property setter"),
+ "ImageSequential.disable_features": (("_disable_features",), "a property setter"),
+ "SequentialBase.keepdim": (("_keepdim",), "a property setter"),
+ "SequentialBase.same_on_batch": (("_same_on_batch",), "a property setter"),
+ "OperationBase._init_magnitude": (("_factor_name", "_magnitude", "magnitude_range"), "a constructor helper"),
+ "TransformMatrixMinIn._parse_transformation_matrix_mode": (("_transformation_matrix_arg",), "a constructor helper"),
+ "_BasicAugmentationBase.set_rng_device_and_dtype": (("device", "dtype"), "called by .to(), not by a call"),
+ "RandomGeneratorBase.set_rng_device_and_dtype": (("device", "dtype"), "called by .to(), not by a call"),
+ "RandomTransplantation.params_from_input": (
+ ("excluded_labels",),
+ "a constructor argument moved to the mask's device; its values never change",
+ ),
+ "AdaptiveDiscriminatorAugmentation.update": (
+ ("p", "_num_calls", "real_acc_ema"),
+ "updated only from an explicit real_acc, which the export does not pass",
+ ),
+}
+
+_SCANNED = ("augmentation", "core/module.py", "core/mixin/image_module.py")
+
+
+def _attributes_written_after_construction():
+ # ``self.<name> = ...`` (also augmented and annotated assignments) in every method of every class in the scanned
+ # sources but ``__init__`` and the generators' ``make_samplers``, as ``(Class.method, name, path:line)``.
+ root = Path(kornia.__file__).parent
+ writes = []
+ for scanned in _SCANNED:
+ paths = sorted((root / scanned).rglob("*.py")) if (root / scanned).is_dir() else [root / scanned]
+ for path in paths:
+ for cls in ast.walk(ast.parse(path.read_text(encoding="utf-8"))):
+ if not isinstance(cls, ast.ClassDef):
+ continue
+ for method in cls.body:
+ if not isinstance(method, ast.FunctionDef) or method.name in ("__init__", "make_samplers"):
+ continue
+ if not method.args.args or method.args.args[0].arg != "self":
+ continue # a static method, a class method or ``__init_subclass__``
+ for node in ast.walk(method):
+ if isinstance(node, ast.Assign):
+ targets = node.targets
+ elif isinstance(node, ast.AugAssign) or (isinstance(node, ast.AnnAssign) and node.value):
+ targets = [node.target]
+ else:
+ continue
+ for target in targets:
+ for item in target.elts if isinstance(target, ast.Tuple) else [target]:
+ if (
+ isinstance(item, ast.Attribute)
+ and isinstance(item.value, ast.Name)
+ and item.value.id == "self"
+ ):
+ where = f"{path.relative_to(root.parent).as_posix()}:{node.lineno}"
+ writes.append((f"{cls.name}.{method.name}", item.attr, where))
+ return writes
+
+
def _run(op, x):
session = ort.InferenceSession(op.SerializeToString(), providers=["CPUExecutionProvider"])
return torch.from_numpy(session.run(None, {session.get_inputs()[0].name: x.numpy()})[0])
@@ -145,6 +259,230 @@ class TestONNXExportMixin(BaseTester):
assert all(_cache_of(m) is cache for m, cache in zip(modules, before))
assert _cache_of(bare) is _NO_CACHE
+ @staticmethod
+ def _augmented(case):
+ # The pipeline of #6140: flips drawn per sample, called on one 8 x 8 image. The export traces a batch of two
+ # 4 x 4 dummies, whose draws then replaced the state ``inverse()`` reads, so it raised or inverted the dummy.
+ # ``exported`` is what ``to_onnx`` exports: the ``ImageSequential`` around a container, or the bare module.
+ import kornia.augmentation as K
+
+ torch.manual_seed(3)
+ if case == "container":
+ aug = K.AugmentationSequential(K.RandomHorizontalFlip(p=0.5), K.RandomVerticalFlip(p=0.5))
+ exported = ImageSequential(aug)
+ else:
+ aug = exported = K.RandomHorizontalFlip(p=0.5)
+ y = exported(torch.rand(1, 3, 8, 8))
+ return exported, aug, y, aug.inverse(y)
+
+ @staticmethod
+ def _export(exported, **kwargs):
+ # A bare augmentation module has no ``to_onnx``; it is exported as the ``model`` of an empty receiver.
+ receiver = exported if isinstance(exported, ImageSequential) else ImageSequential()
+ model = None if receiver is exported else exported
+ return receiver.to_onnx(save=False, model=model, pseudo_shape=[1, 3, 4, 4], **_RGB, **kwargs)
+
+ # Not "dynamo" in the ids: conftest deselects every test whose name contains it unless an optimizer is set. The
+ # default exporter is torch.export-based from torch 2.9 and the legacy one before.
+ @pytest.mark.parametrize("case", ["container", "module"], ids=["nested-container", "bare-module"])
+ @pytest.mark.parametrize("exporter", [{}, {"dynamo": False}], ids=["default-exporter", "legacy-exporter"])
+ def test_export_keeps_the_state_inverse_reads_6140(self, exporter, case):
+ exported, aug, y, expected = self._augmented(case)
+ modules = list(exported.modules())
+ params = aug._params
+ before = [_call_state_of(m) for m in modules]
+
+ self._export(exported, **exporter)
+
+ assert aug._params is params
+ assert all(_same_objects(_call_state_of(m), state) for m, state in zip(modules, before))
+ self.assert_close(aug.inverse(y), expected)
+
+ @pytest.mark.parametrize("exporter", [{}, {"dynamo": False}], ids=["default-exporter", "legacy-exporter"])
+ def test_export_leaves_no_state_on_a_module_never_called_6140(self, exporter):
+ # Several of the attributes are class-level defaults until a call stores them on the instance.
+ import kornia.augmentation as K
+
+ exported = ImageSequential(K.AugmentationSequential(K.RandomHorizontalFlip(p=0.5)))
+ modules = list(exported.modules())
+ before = [_call_state_of(m) for m in modules]
+
+ self._export(exported, **exporter)
+
+ assert all(_same_objects(_call_state_of(m), state) for m, state in zip(modules, before))
+
+ def test_failed_export_keeps_the_state_inverse_reads_6140(self, monkeypatch):
+ exported, aug, y, expected = self._augmented("container")
+ modules = list(exported.modules())
+ before = [_call_state_of(m) for m in modules]
+ bare = nn.Identity() # a module without the state must not get it
+ exported.append(bare)
+
+ def _run_then_fail(module, args, *rest, **kwargs):
+ module(*args) if isinstance(args, tuple) else module(args)
+ bare._params = "written by the export"
+ raise RuntimeError("export failed")
+
+ monkeypatch.setattr(torch.onnx, "export", _run_then_fail)
+ with pytest.raises(RuntimeError, match="export failed"):
+ self._export(exported)
+ assert all(_same_objects(_call_state_of(m), state) for m, state in zip(modules, before))
+ assert _call_state_of(bare) == {}
+ self.assert_close(aug.inverse(y), expected)
+
+ # A static shape: with a dynamic batch, the dynamo exporter stops in the generators before the modules below run.
+ _STATIC = {"input_shape": [2, 3, 4, 4], "pseudo_shape": [2, 3, 4, 4]}
+
+ @pytest.mark.parametrize("exporter", [{}, {"dynamo": False}], ids=["default-exporter", "legacy-exporter"])
+ def test_export_keeps_the_matrix_of_a_policy_6140(self, exporter):
+ # Under a capture, where ``is_exporting()`` skips the reset, a policy appends the dummy's matrices in place to
+ # the list its ``transform_matrix`` composes, so putting the same list back is not enough.
+ from kornia.augmentation.auto.operations import Rotate, ShearX
+ from kornia.augmentation.auto.operations.policy import PolicySequential
+
+ torch.manual_seed(0)
+ policy = PolicySequential(ShearX(initial_probability=1.0), Rotate(initial_probability=1.0))
+ policy(torch.rand(1, 3, 8, 8))
+ matrices = policy._transform_matrices
+ items = list(matrices)
+ expected = _composed(items) # read lazily, so the property must not run before the export
+
+ # The legacy exporter (the default before torch 2.9) lowers the warp's ``affine_grid`` from opset 20 only.
+ legacy = exporter.get("dynamo") is False or not torch_version_ge(2, 9, 0)
+ opset = {"opset_version": 20} if legacy else {}
+ ImageSequential().to_onnx(
+ save=False, model=policy, output_shape=[2, 3, 4, 4], **self._STATIC, **exporter, **opset
+ )
+
+ assert policy._transform_matrices is matrices
+ assert len(matrices) == len(items)
+ assert all(now is item for now, item in zip(matrices, items))
+ self.assert_close(policy.transform_matrix, expected)
+
+ def test_failed_export_keeps_the_matrices_a_policy_appends_in_place_6140(self, monkeypatch):
+ # An auto-augment policy and its sub-policy append in place too. No real exporter reaches them today (their
+ # draws stop torch.export first), so the stand-in export runs the model with ``is_exporting()`` True, as a
+ # capture does, then fails.
+ import kornia.augmentation as K
+ import kornia.core.utils
+
+ torch.manual_seed(0)
+ policy = K.auto.AutoAugment(policy=[[("shear_x", 1.0, 5), ("rotate", 1.0, 5)]])
+ policy(torch.rand(1, 3, 8, 8))
+ lists = [
+ (m, m._transform_matrices, list(m._transform_matrices))
+ for m in policy.modules()
+ if m.__dict__.get("_transform_matrices")
+ ]
+ expected = _composed(policy._transform_matrices)
+
+ def _capture_then_fail(module, args, *rest, **kwargs):
+ with monkeypatch.context() as patch:
+ patch.setattr(kornia.core.utils, "_is_exporting_eager", lambda: True)
+ module(*args) if isinstance(args, tuple) else module(args)
+ raise RuntimeError("export failed")
+
+ monkeypatch.setattr(torch.onnx, "export", _capture_then_fail)
+ with pytest.raises(RuntimeError, match="export failed"):
+ ImageSequential().to_onnx(save=False, model=policy, output_shape=[2, 3, 4, 4], **self._STATIC)
+
+ assert len(lists) == 2 # the policy and its one sub-policy
+ for module, matrices, items in lists:
+ assert module._transform_matrices is matrices
+ assert len(matrices) == len(items)
+ assert all(now is item for now, item in zip(matrices, items))
+ self.assert_close(policy.transform_matrix, expected)
+
+ def test_failed_export_gives_back_the_items_of_a_params_dict_6140(self, monkeypatch):
+ # ``_params`` and ``_transform_matrix_params`` are dicts that ``forward`` edits in place when they are passed
+ # back to it (``params["batch_prob"] = ...``, ``save_kwargs=True``). No export run does that today; the stand-in
+ # export edits the stored dict in place, then fails.
+ exported, aug, y, expected = self._augmented("module")
+ params = aug._params
+ items = dict(params)
+
+ def _edit_then_fail(module, args, *rest, **kwargs):
+ module._params["batch_prob"] = torch.zeros(2)
+ module._params["written by the export"] = True
+ raise RuntimeError("export failed")
+
+ monkeypatch.setattr(torch.onnx, "export", _edit_then_fail)
+ with pytest.raises(RuntimeError, match="export failed"):
+ self._export(exported)
+
+ assert aug._params is params
+ assert params.keys() == items.keys()
+ assert all(params[key] is items[key] for key in items)
+ self.assert_close(aug.inverse(y), expected)
+
+ @pytest.mark.parametrize("exporter", [{}, {"dynamo": False}], ids=["default-exporter", "legacy-exporter"])
+ def test_export_leaves_a_resized_crop_copyable_6140(self, exporter):
+ # ``ResizedCropGenerator`` stored each call's crop sizes on itself. A dynamo export on torch 2.9 left its fake
+ # tensor there, and ``deepcopy`` and ``pickle`` raised afterwards. The sizes are now passed on, not stored.
+ import kornia.augmentation as K
+
+ torch.manual_seed(0)
+ aug = K.RandomResizedCrop((6, 6), p=1.0)
+ aug(torch.rand(1, 3, 8, 8))
+
+ ImageSequential().to_onnx(save=False, model=aug, output_shape=[2, 3, 6, 6], **self._STATIC, **exporter)
+
+ assert aug._param_generator.size == (6, 6)
+ copy.deepcopy(aug)
+ pickle.dumps(aug)
+
+ @pytest.mark.skipif(not dynamo_is_available(), reason=DYNAMO_UNAVAILABLE_REASON)
+ def test_failed_export_leaves_no_buffer_registration_hook_6140(self):
+ # torch 2.9's non-strict torch.export registers a global buffer-registration hook and removes it only when its
+ # trace succeeds. Left behind by a failed export, it ran in every later Dynamo trace that registers a buffer,
+ # which then raised ``Unsupported``: on CI, the losses' traces after this file.
+ class _Fails(nn.Module):
+ def forward(self, x):
+ raise ValueError("this model does not export")
+
+ class _WithBuffer(nn.Module):
+ def __init__(self):
+ super().__init__()
+ self.register_buffer("offset", torch.ones(1))
+
+ hooks = getattr(torch.nn.modules.module, "_global_buffer_registration_hooks", {})
+ before = list(hooks)
+ with pytest.raises(Exception) as info: # each exporter wraps the model's error in its own
+ ImageSequential(_Fails()).to_onnx(save=False, **_RGB)
+ error = info.value
+ while error is not None and not isinstance(error, ValueError):
+ error = error.__cause__ or error.__context__
+ assert error is not None, f"no ValueError behind {info.value!r}"
+ assert "does not export" in str(error)
+ assert list(hooks) == before
+
+ torch._dynamo.reset()
+ traced = torch.compile(lambda x: x + _WithBuffer().offset, backend="eager", fullgraph=True)
+ self.assert_close(traced(torch.zeros(2)), torch.ones(2))
+
+ def test_every_attribute_written_after_construction_is_classified_6140(self):
+ # ``to_onnx`` restores the attributes in ``_PER_CALL_STATE``. An augmentation or image module that starts
+ # writing another attribute on itself outside its constructor must say which kind it is: state of its last
+ # call, which the export's run on the dummy would overwrite, or one of the kinds in ``_NOT_CALL_STATE``.
+ from kornia.core.mixin.onnx import _PER_CALL_STATE
+
+ writes = _attributes_written_after_construction()
+ unclassified = sorted(
+ (writer, name, where)
+ for writer, name, where in writes
+ if name not in _PER_CALL_STATE and name not in _NOT_CALL_STATE.get(writer, ((), ""))[0]
+ )
+ assert not unclassified, (
+ "Add each to _PER_CALL_STATE in kornia/core/mixin/onnx.py if a later call or inverse() reads what the last "
+ "call stored, else to _NOT_CALL_STATE here under its writer with the reason: "
+ + "; ".join(f"{writer} writes {name} ({where})" for writer, name, where in unclassified)
+ )
+ assert set(_PER_CALL_STATE) == set(_CALL_STATE)
+ written = {(writer, name) for writer, name, _ in writes}
+ classified = {(writer, name) for writer, (names, _) in _NOT_CALL_STATE.items() for name in names}
+ stale = sorted(classified - written) + sorted(set(_PER_CALL_STATE) - {name for _, name in written})
+ assert not stale, f"no longer written outside a constructor, remove them: {stale}"
+
def test_explicit_training_mode_is_the_legacy_exporters_opt_out(self):
# The documented opt-out from the eval-mode export: an explicit ``training=TRAINING`` reaches the legacy
# exporter, which traces the training graph. The flags still come back exactly.
@@ -296,6 +634,28 @@ class TestONNXExportMixinDtypeDevice(BaseTester):
self.assert_close(_run(op, x.cpu()), expected.cpu())
+class TestONNXExportMixinRandomState(BaseTester):
+ @pytest.mark.parametrize("exporter", [{}, {"dynamo": False}], ids=["default-exporter", "legacy-exporter"])
+ def test_export_gives_back_the_random_state_6140(self, device, exporter):
+ # The dummy and the export's run on it draw from the global generators, an augmentation moved to a device on
+ # that device's, so the draws after an export were not the ones the same calls make without it (#6140).
+ import kornia.augmentation as K
+
+ def _draws_after(export):
+ torch.manual_seed(3)
+ model = ImageSequential(
+ K.AugmentationSequential(K.RandomHorizontalFlip(p=0.5), K.RandomVerticalFlip(p=0.5))
+ ).to(device)
+ x = torch.rand(4, 3, 8, 8).to(device)
+ model(x)
+ if export:
+ model.to_onnx(save=False, pseudo_shape=[1, 3, 4, 4], **_RGB, **exporter)
+ return model(x), torch.rand(8, device=device), torch.rand(8)
+
+ for after, expected in zip(_draws_after(True), _draws_after(False)):
+ self.assert_close(after, expected)
+
+
@pytest.mark.device_agnostic
class TestONNXRuntimeMixin(BaseTester):
@pytest.fixture
diff --git a/tests/models/test_object_detector.py b/tests/models/test_object_detector.py
index 4ba58d5fd..f9d0e5bda 100644
--- a/tests/models/test_object_detector.py
+++ b/tests/models/test_object_detector.py
@@ -197,6 +197,69 @@ class TestObjectDetector(BaseTester):
assert not _returns_detections_per_image(detector, torch.rand(2, 3, 16, 16))
assert pre.__dict__["_output_image"] is cache
+ def test_output_check_gives_back_the_random_state(self):
+ # The output check runs the detector in eval mode; a model that still draws there must not consume the
+ # global random state, wherever the check runs, before the export or after it.
+ from kornia.contrib.object_detection import _returns_detections_per_image
+
+ class _Pre(torch.nn.Module):
+ def forward(self, x):
+ return x, x.new_full((x.shape[0], 2), float(x.shape[-1]))
+
+ class _DrawingModel(torch.nn.Module):
+ def __init__(self):
+ super().__init__()
+ self.conv = torch.nn.Conv2d(3, 6, 1)
+
+ def forward(self, x):
+ y = self.conv(x + 0.0 * torch.rand_like(x)).mean((-2, -1))
+ return y[:, None, :2], y[:, None, 2:]
+
+ class _Post(torch.nn.Module):
+ def forward(self, logits, boxes, sizes):
+ return torch.cat([logits, boxes], -1)
+
+ detector = kornia.contrib.object_detection.ObjectDetector(_DrawingModel(), _Pre(), _Post())
+ images = torch.rand(2, 3, 16, 16)
+ state = torch.get_rng_state()
+ assert not _returns_detections_per_image(detector, images)
+ assert torch.equal(torch.get_rng_state(), state)
+
+ @pytest.mark.parametrize("exporter", [{}, {"dynamo": False}], ids=["default-exporter", "legacy-exporter"])
+ def test_export_gives_back_the_random_state_6140(self, exporter):
+ # ObjectDetector.to_onnx draws an input for its output check before the export draws its dummy. Both give back
+ # what they drew, so the draws after an export are the ones the same calls make without it.
+ pytest.importorskip("onnx")
+ if not exporter and not torch_version_lt(2, 9, 0):
+ pytest.importorskip("onnxscript") # the default exporter from torch 2.9 is the dynamo one, which needs it
+
+ class _Pre(kornia.core.ImageModule):
+ def forward(self, x):
+ return x, x.new_full((x.shape[0], 2), float(x.shape[-1]))
+
+ class _Model(torch.nn.Module):
+ def __init__(self):
+ super().__init__()
+ self.conv = torch.nn.Conv2d(3, 6, 1)
+
+ def forward(self, x):
+ y = self.conv(x).mean((-2, -1))
+ return y[:, None, :2], y[:, None, 2:]
+
+ class _Post(torch.nn.Module):
+ def forward(self, logits, boxes, sizes):
+ return torch.cat([logits, boxes], -1)
+
+ def _draws_after(export):
+ torch.manual_seed(0)
+ detector = kornia.contrib.object_detection.ObjectDetector(_Model(), _Pre(), _Post())
+ detector(torch.rand(1, 3, 16, 16))
+ if export:
+ detector.to_onnx(image_size=16, save=False, **exporter)
+ return torch.rand(8)
+
+ self.assert_close(_draws_after(True), _draws_after(False))
+
def test_results_from_detections_misspelt_format_5907(self, device, dtype):
detections = torch.zeros(1, 6, device=device, dtype=dtype)
with pytest.raises(ValueError, match="'xywhh' is not a valid BoundingBoxDataFormat") as excinfo: