π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
fix(onnx): to_onnx keeps every image module's output cache; HF to_onnx metadata goes on a copy (#6130)
Dmytro Mishkin16f01effc580
diff --git a/changelog.d/6130.fixed.md b/changelog.d/6130.fixed.mdnew file mode 100644index 000000000..0ff1f4fa6--- /dev/null+++ b/changelog.d/6130.fixed.md@@ -0,0 +1,3 @@+- `to_onnx` no longer overwrites the output cache that `show()` and `save()` read. On the TorchScript exporter (the `to_onnx` default below torch 2.9, or `dynamo=False`), the export's run on its random dummy input used to leave that output in the exported module's cache and in the cache of every image module inside it, `AugmentationSequential` included, so `show()` rendered noise after an export. Every cache now holds the same object as before the export, whether the export succeeds or raises.+- `HFONNXComunnityModel.to_onnx` returns a copy carrying that call's metadata. It used to add the metadata to the stored graph, which is the `ModelProto` the model was built from, so the keys of one call appeared in the caller's graph and in every later export.+- `HFONNXComunnityModel.resize_back` with a `target_images` that is not a tensor raises a `TypeError` naming the type; it raised a `RuntimeError` without a message.diff --git a/kornia/contrib/object_detection.py b/kornia/contrib/object_detection.pyindex 8add5f237..ccd5fe0db 100644--- a/kornia/contrib/object_detection.py+++ b/kornia/contrib/object_detection.py@@ -28,7 +28,13 @@ from kornia.constants import _get_by_namefrom kornia.core.check import KORNIA_CHECK_SHAPEfrom kornia.core.external import PILImage as Imagefrom kornia.core.external import onnx-from kornia.core.mixin.onnx import ONNXExportMixin, _eval_mode, _first_floating_tensor, _to_floating+from kornia.core.mixin.onnx import (+ ONNXExportMixin,+ _eval_mode,+ _first_floating_tensor,+ _preserved_output_caches,+ _to_floating,+)from kornia.image.draw import draw_rectanglefrom kornia.models.base import ModelBasefrom kornia.models.processors import ResizePreProcessor@@ -130,12 +136,15 @@ 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.+ 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."""reference = _first_floating_tensor(detector)if reference is not None:images = _to_floating(images, reference)- with _eval_mode(detector), torch.no_grad():+ # 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():return isinstance(detector(images), list)diff --git a/kornia/core/mixin/onnx.py b/kornia/core/mixin/onnx.pyindex 56f70b3df..536f0f164 100644--- a/kornia/core/mixin/onnx.py+++ b/kornia/core/mixin/onnx.py@@ -79,6 +79,32 @@ def _eval_mode(module: Any) -> Iterator[None]:submodule.training = training+_NO_OUTPUT_CACHE = object()+++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.++ 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.+ """+ caches = (+ [(m, m.__dict__.get("_output_image", _NO_OUTPUT_CACHE)) 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++class ONNXExportMixin:"""Mixin class that provides ONNX export functionality for objects that support it.@@ -162,6 +188,8 @@ class ONNXExportMixin:The one opt-out is ``training=torch.onnx.TrainingMode.TRAINING``, which torch deprecates: the legacyTorchScript exporter (the default before torch 2.9, ``dynamo=False`` from it) then exports thetraining-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 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.@@ -238,9 +266,10 @@ class ONNXExportMixin:default_args.update(kwargs)# 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.+ # 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.# A file path rather than a buffer: exporting to ``io.BytesIO`` is deprecated from torch 2.9.- with _eval_mode(module), tempfile.TemporaryDirectory() as tmp_dir:+ with _eval_mode(module), _preserved_output_caches(module), tempfile.TemporaryDirectory() as tmp_dir:tmp_path = os.path.join(tmp_dir, "model.onnx")torch.onnx.export(module,diff --git a/kornia/models/_hf_models/hf_onnx_community.py b/kornia/models/_hf_models/hf_onnx_community.pyindex ef34bd212..4fa882b20 100644--- a/kornia/models/_hf_models/hf_onnx_community.py+++ b/kornia/models/_hf_models/hf_onnx_community.py@@ -190,10 +190,13 @@ class HFONNXComunnityModel(ONNXSequential, ModelBaseMixin):Returns:The resized images.+ Raises:+ TypeError: if ``target_images`` is not a tensor.+"""if isinstance(target_images, torch.Tensor):return resize(images, target_images.shape[-2:])- raise RuntimeError+ raise TypeError(f"target_images must be a torch.Tensor, got {type(target_images).__name__}.")def to_onnx(self,@@ -216,20 +219,22 @@ class HFONNXComunnityModel(ONNXSequential, ModelBaseMixin):save:If to save the model or load it.additional_metadata:- Additional metadata to add to the ONNX model.+ Additional metadata to add to the exported model. It goes on a copy: the stored graphs, and a+ ``ModelProto`` the model was built from, are left as they are.kwargs: Additional arguments to convert to onnx.+ Returns:+ A copy of the model or of the combined graph, with ``source``, ``version`` and ``additional_metadata``.+"""if onnx_name is None:onnx_name = f"kornia_{self.name}.onnx"- if not include_pre_and_post_processor:- self._add_metadata(self.model, additional_metadata)- if save:- self._export(self.model, onnx_name, **kwargs)- return self.model-- self._add_metadata(self._combined_op, additional_metadata)+ # The metadata goes on a copy: written into the stored graph, which is the caller's ModelProto, one call's keys+ # would reach every later export.+ op = onnx.ModelProto()+ op.CopyFrom(self._combined_op if include_pre_and_post_processor else self.model)+ self._add_metadata(op, additional_metadata)if save:- self._export(self._combined_op, onnx_name, **kwargs)- return self._combined_op+ self._export(op, onnx_name, **kwargs)+ return opdiff --git a/tests/core/test_onnx_mixin.py b/tests/core/test_onnx_mixin.pyindex 8684d5ee0..dc97682cf 100644--- a/tests/core/test_onnx_mixin.py+++ b/tests/core/test_onnx_mixin.py@@ -50,6 +50,14 @@ def _input_dims(op):return [d.dim_param or d.dim_value for d in op.graph.input[0].type.tensor_type.shape.dim]+_NO_CACHE = object()+++def _cache_of(module):+ # The ``show()`` / ``save()`` output cache as stored on the module, or a sentinel when it has none.+ return module.__dict__.get("_output_image", _NO_CACHE)++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])@@ -85,6 +93,58 @@ class TestONNXExportMixin(BaseTester):model.to_onnx(save=False, **_RGB)assert [m.training for m in (model, *model)] == [True, False, True]+ @staticmethod+ def _cached_tree():+ # Every image module caches its last output for ``show()`` / ``save()``: a nested ``ImageModule`` through+ # ``_store_output_image``, an ``AugmentationSequential`` by writing the attribute itself.+ import kornia.augmentation as K+ from kornia.core import ImageModule++ class _Child(ImageModule):+ def __init__(self):+ super().__init__()+ self.conv = nn.Conv2d(3, 3, 1)++ def forward(self, x):+ return self.conv(x)++ child, aug = _Child(), K.AugmentationSequential(K.RandomHorizontalFlip(p=1.0))+ model = ImageSequential(child, aug, nn.Identity())+ model(torch.rand(1, 3, 8, 8))+ fresh = ImageSequential(nn.Identity()) # never called: its cache is None+ outer = ImageSequential(model, fresh)+ outer._output_image = torch.rand(1, 3, 8, 8) # the exported module's own cache, set as a call would+ return outer, [outer, model, child, aug, fresh]++ # Not "dynamo" in the ids: conftest deselects every test whose name contains it unless an optimizer is set.+ @pytest.mark.parametrize("dynamo", [True, False], ids=["default-exporter", "legacy-exporter"])+ def test_export_keeps_every_output_cache(self, dynamo):+ # The legacy exporter runs the module on the dummy input outside ``is_exporting()``: each image module in the+ # tree used to cache the dummy's (2, 3, 4, 4) output, so ``show()`` rendered noise after an export.+ if dynamo and not torch_version_ge(2, 9, 0):+ pytest.skip("the default exporter below torch 2.9 is the legacy one")+ outer, modules = self._cached_tree()+ before = [_cache_of(m) for m in modules]+ outer.to_onnx(save=False, pseudo_shape=[1, 3, 4, 4], dynamo=dynamo, **_RGB)+ assert all(_cache_of(m) is cache for m, cache in zip(modules, before))++ def test_failed_export_keeps_every_output_cache(self, monkeypatch):+ outer, modules = self._cached_tree()+ before = [_cache_of(m) for m in modules]+ bare = nn.Identity() # a module without the attribute must not get one+ outer.append(bare)++ def _run_then_fail(module, args, *rest, **kwargs):+ module(*args) if isinstance(args, tuple) else module(args)+ bare._output_image = "written by the export"+ raise RuntimeError("export failed")++ monkeypatch.setattr(torch.onnx, "export", _run_then_fail)+ with pytest.raises(RuntimeError, match="export failed"):+ outer.to_onnx(save=False, pseudo_shape=[1, 3, 4, 4], **_RGB)+ assert all(_cache_of(m) is cache for m, cache in zip(modules, before))+ assert _cache_of(bare) is _NO_CACHE+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.diff --git a/tests/models/test_hf_onnx_community.py b/tests/models/test_hf_onnx_community.pyindex c022e1408..e8b6a71bc 100644--- a/tests/models/test_hf_onnx_community.py+++ b/tests/models/test_hf_onnx_community.py@@ -68,6 +68,34 @@ def test_to_onnx_keeps_one_metadata_entry_per_key(include_pre_and_post_processoronnx.checker.check_model(exported)[email protected]("include_pre_and_post_processor", [False, True])+def test_to_onnx_leaves_the_stored_and_the_callers_graphs_unchanged(include_pre_and_post_processor):+ # Each export carries that call's metadata on a copy: the keys of one call used to be written into the stored+ # graph, which is the caller's ModelProto, and so into every later export.+ model = _identity_model(("keep", "yes"))+ hf_model = HFONNXComunnityModel(model, pre_processor=_identity_model())+ stored = hf_model._combined_op.SerializeToString()++ first = hf_model.to_onnx(+ save=False, include_pre_and_post_processor=include_pre_and_post_processor, additional_metadata=[("run", "1")]+ )+ second = hf_model.to_onnx(save=False, include_pre_and_post_processor=include_pre_and_post_processor)++ assert ("run", "1") in [(prop.key, prop.value) for prop in first.metadata_props]+ assert "run" not in [prop.key for prop in second.metadata_props]+ assert [(prop.key, prop.value) for prop in model.metadata_props] == [("keep", "yes")]+ assert hf_model.model is model+ assert hf_model._combined_op.SerializeToString() == stored+++def test_resize_back_names_the_expected_type():+ import torch++ hf_model = HFONNXComunnityModel(_identity_model())+ with pytest.raises(TypeError, match=r"target_images must be a torch\.Tensor, got list"):+ hf_model.resize_back(torch.rand(1, 3, 4, 4), [torch.rand(3, 8, 8)])++def test_each_repository_preprocessing_config_is_cached_beside_its_model(monkeypatch, tmp_path):# #5902: every onnx-community repository's preprocessor_config.json used to be cached as one file,# <hub_cache_dir>/preprocessor_config.json, outside the loader's cache_dir, so the second model built loaded thediff --git a/tests/models/test_object_detector.py b/tests/models/test_object_detector.pyindex acb65ba57..4ba58d5fd 100644--- a/tests/models/test_object_detector.py+++ b/tests/models/test_object_detector.py@@ -168,6 +168,35 @@ class TestObjectDetector(BaseTester):assert model_path.is_file()+ def test_output_check_keeps_an_image_module_cache(self):+ # ObjectDetector.to_onnx first runs the detector once to tell a per-image list from one tensor. That run, like+ # the export's own, leaves the show()/save() cache of an image module inside the detector as it was.+ from kornia.contrib.object_detection import _returns_detections_per_image++ class _Pre(kornia.core.ImageModule):+ def forward(self, x):+ return x, torch.tensor([[x.shape[-2], x.shape[-1]]] * x.shape[0])++ 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)++ pre = _Pre()+ detector = kornia.contrib.object_detection.ObjectDetector(_Model(), pre, _Post())+ pre(torch.rand(1, 3, 8, 8))+ cache = pre.__dict__["_output_image"]+ assert not _returns_detections_per_image(detector, torch.rand(2, 3, 16, 16))+ assert pre.__dict__["_output_image"] is cache+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: