π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
fix(core)!: ONNX export contract β eval mode, opset 18, default shape, dummy dtype/device; session_options and add_metadata (#5244)
Dmytro Mishkin0ea5c86a7235
diff --git a/changelog.d/5244.breaking.md b/changelog.d/5244.breaking.mdnew file mode 100644index 000000000..53862fc2c--- /dev/null+++ b/changelog.d/5244.breaking.md@@ -0,0 +1,19 @@+`ONNXExportMixin.to_onnx` (behind `ImageModule.to_onnx`, `kornia.core.ImageSequential.to_onnx` and the model+exporters) now requests ONNX opset 18, the opset the dynamo exporter builds natively, and documents it. It used to+request 17: the dynamo exporter, the default of `torch.onnx.export` from torch 2.9, met that only when every operator+had a down-conversion adapter (a convolution came back at 17, a `GaussianBlur2d` pipeline at 18 after a logged+conversion failure), and the legacy exporter of older torch returned 17. Pass `opset_version=` to request another one.+To chain an export with the pre-exported Hub operators (opset 17) in `ONNXSequential`, pass+`auto_ir_version_conversion=True`; on torch before 2.9, `to_onnx(opset_version=17)` also works. On torch 2.9 and later+the IR versions already differed, so the conversion was needed before as well.+The default input shape (`ONNX_DEFAULT_INPUTSHAPE`) is now `[-1, 3, -1, -1]` instead of `[-1, -1, -1, -1]`, so a call+without `input_shape` exports a fixed 3-channel input with a dynamic batch, height and width: on torch 2.9 and later+the old default failed for any model with a fixed channel count, and on older torch it declared the channel dimension+dynamic even where the model fixed it. A channel-agnostic model exported without `input_shape` used to accept any+channel count and now takes exactly 3. A `pseudo_shape` given without `input_shape` sets the default's fixed entries,+so `to_onnx(pseudo_shape=[1, 1, 32, 32])` exports a 1-channel input. Pass `input_shape` for a dynamic channel count.+An explicit `input_shape` whose fixed entries differ from an explicit `pseudo_shape` now raises `ValueError`; the+`input_shape` entry used to win silently, so the model was traced with a shape other than the one given.+`ONNXSequential(..., auto_ir_version_conversion=True)` now converts the models to the highest opset among them instead+of to 17, so it accepts kornia's own opset-18 exports; on some of them, such as a `GaussianBlur2d` pipeline, it used to+fail with `No Adapter To Version $17 for Pad`.diff --git a/changelog.d/5244.fixed.md b/changelog.d/5244.fixed.mdnew file mode 100644index 000000000..8d3daef6c--- /dev/null+++ b/changelog.d/5244.fixed.md@@ -0,0 +1,15 @@+`to_onnx` exports the model in eval mode and restores each submodule's training flag afterwards, also when the export+fails. On torch 2.9 and later a model left in training mode exported an active `Dropout`, so onnxruntime zeroed about+half of the outputs; the legacy exporter of older torch exported in eval mode but then reset every submodule to the+model's own mode. The dummy input takes the dtype and device of the model's first floating parameter or, for a model+without one, of its first floating buffer, so float64, float16 and MPS or CUDA models export with an input of their+own dtype. The dummy input used to be float32 on the CPU, which failed on an input/weight mismatch or, for a model that+promotes, exported a float32 input. A dynamic `input_shape` whose rank differs from the pseudo shape now raises+`ValueError`: a longer one raised `IndexError`, and a shorter one exported, sized silently from the pseudo shape's+leading entries. A missing output directory raises `FileNotFoundError` before the export runs rather than after it,+and the export no longer passes through the deprecated `io.BytesIO` destination or, on the dynamo exporter,+`dynamic_axes`, which warned on every call. `ONNXSequential` and `ONNXModule` now use the `session_options=` they are+given instead of raising `UnboundLocalError`, and `kornia.onnx.utils.add_metadata` (behind `to_onnx` and the+`add_metadata` methods) overwrites a key that is already present instead of adding a duplicate that+`onnx.checker.check_model` rejects. It also merges the duplicate keys of a model tagged by an earlier version into one+entry with the last value, so such a model passes the check.diff --git a/kornia/contrib/super_resolution.py b/kornia/contrib/super_resolution.pyindex 95aed6571..1a973c37e 100644--- a/kornia/contrib/super_resolution.py+++ b/kornia/contrib/super_resolution.py@@ -243,12 +243,15 @@ class SuperResolution(ModelBase[SuperResolutionConfig], ONNXExportMixin):if onnx_name is None:onnx_name = f"kornia_{self.name}.onnx"+ # The dummy input must agree with a fixed input size, which ``to_onnx`` checks.+ pseudo_size = self.pseudo_image_size or self.input_image_size or 352+return ONNXExportMixin.to_onnx(self,onnx_name,input_shape=[-1, 3, self.input_image_size or -1, self.input_image_size or -1],output_shape=[-1, 3, self.output_image_size or -1, self.output_image_size or -1],- pseudo_shape=[1, 3, self.pseudo_image_size or 352, self.pseudo_image_size or 352],+ pseudo_shape=[1, 3, pseudo_size, pseudo_size],model=self if include_pre_and_post_processor else self.model,save=save,additional_metadata=additional_metadata,diff --git a/kornia/core/mixin/onnx.py b/kornia/core/mixin/onnx.pyindex 33a89b19c..89ff071cb 100644--- a/kornia/core/mixin/onnx.py+++ b/kornia/core/mixin/onnx.py@@ -17,8 +17,10 @@from __future__ import annotations-import copyimport io+import itertools+import os+import tempfilefrom typing import (Any,ClassVar,@@ -30,10 +32,34 @@ import torchfrom torch import nnimport kornia+from kornia.core._compat import torch_version_gefrom kornia.core.external import numpy as npfrom kornia.core.external import onnxfrom kornia.core.external import onnxruntime as ort+# The opset ``ONNXExportMixin.to_onnx`` requests: the one the dynamo exporter (the ``torch.onnx.export`` default from+# torch 2.9) builds natively, so no version conversion runs. The legacy TorchScript exporter emits it directly as well.+_ONNX_EXPORT_OPSET = 18+++def _first_floating_tensor(module: Any) -> Optional[torch.Tensor]:+ """Return the first floating parameter of ``module``, else its first floating buffer, else ``None``."""+ if not isinstance(module, nn.Module):+ return None+ for tensor in itertools.chain(module.parameters(), module.buffers()):+ if tensor.is_floating_point():+ return tensor+ return None+++def _to_floating(value: Any, reference: torch.Tensor) -> Any:+ """Move the floating tensors in ``value`` (a tensor or a tuple) to the dtype and device of ``reference``."""+ if isinstance(value, torch.Tensor) and value.is_floating_point():+ return value.to(device=reference.device, dtype=reference.dtype)+ if isinstance(value, tuple):+ return tuple(_to_floating(item, reference) for item in value)+ return value+class ONNXExportMixin:"""Mixin class that provides ONNX export functionality for objects that support it.@@ -43,7 +69,8 @@ class ONNXExportMixin:A flag indicating whether the object can be exported to ONNX. Default is True.ONNX_DEFAULT_INPUTSHAPE:Default input shape for the ONNX export. A list of integers where `-1` indicates- dynamic dimensions. Default is [-1, -1, -1, -1].+ dynamic dimensions. Default is [-1, 3, -1, -1]: a batch of 3-channel images of any+ batch size, height and width. A class whose models take another channel count declares its own.ONNX_DEFAULT_OUTPUTSHAPE:Default output shape for the ONNX export. A list of integers where `-1` indicatesdynamic dimensions. Default is [-1, -1, -1, -1].@@ -58,7 +85,7 @@ class ONNXExportMixin:"""ONNX_EXPORTABLE: bool = True- ONNX_DEFAULT_INPUTSHAPE: ClassVar[list[int]] = [-1, -1, -1, -1]+ ONNX_DEFAULT_INPUTSHAPE: ClassVar[list[int]] = [-1, 3, -1, -1]ONNX_DEFAULT_OUTPUTSHAPE: ClassVar[list[int]] = [-1, -1, -1, -1]ONNX_EXPORT_PSEUDO_SHAPE: ClassVar[list[int]] = [1, 3, 256, 256]ADDITIONAL_METADATA: ClassVar[list[tuple[str, str]]] = []@@ -82,26 +109,51 @@ class ONNXExportMixin:format "Kornia-<ClassName>.onnx" will be used.input_shape:The input shape for the model as a list of integers. If None,- `ONNX_DEFAULT_INPUTSHAPE` will be used. Dynamic dimensions can be indicated by `-1`.+ `ONNX_DEFAULT_INPUTSHAPE` will be used, with its fixed entries (the channel count) taken+ from `pseudo_shape` when one of the same rank is given. Dynamic dimensions can be indicated by `-1`.+ Mark only the dimensions the model accepts at any size: on the dynamo exporter a `-1`+ on a dimension the model fixes, such as the channel count of a convolution, is an export error.output_shape:The output shape for the model as a list of integers. If None,`ONNX_DEFAULT_OUTPUTSHAPE` will be used. Dynamic dimensions can be indicated by `-1`.+ Only the legacy TorchScript exporter reads it; the dynamo exporter infers the output shape.pseudo_shape:The pseudo shape for the model as a list of integers. If None,- `ONNX_EXPORT_PSEUDO_SHAPE` will be used.+ `ONNX_EXPORT_PSEUDO_SHAPE` will be used. It needs the rank of `input_shape` when+ `input_shape` has a dynamic dimension, and a fixed entry of an explicit `input_shape` must+ match it.model:The model to export. If not provided, the current object will be used.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 ONNX model. A key that is already present is overwritten.**kwargs:Additional keyword arguments to pass to the `torch.onnx.export` function.+ Raises:+ RuntimeError: If `ONNX_EXPORTABLE` is False.+ ValueError: If `input_shape` has a dynamic dimension and a rank other than the pseudo shape's, or+ a fixed entry of `input_shape` differs from the explicit `pseudo_shape`.+ FileNotFoundError: If `save` is True and the directory of `onnx_name` does not exist. This is+ checked before the export runs.+Notes:- - A dummy input tensor is created based on the provided or default input shape.- - Dynamic axes for input and output tensors are configured where dimensions are marked `-1`.- - The model is exported with `torch.onnx.export`, with constant folding enabled and opset version set to 17.+ - The model is exported in eval mode (``Dropout`` inactive, ``BatchNorm`` on its running+ statistics). The training flag of every submodule is restored afterwards, also when the export fails.+ 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 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.+ - A dummy input tensor is created from the input shape, with each `-1` taken from the pseudo shape.+ It has the dtype and device of the model's first floating parameter or, for a model without one,+ of its first floating buffer; it is float32 on the CPU for a model with neither.+ - The dimensions marked `-1` are exported as dynamic: through `dynamic_shapes` on the dynamo exporter+ from torch 2.9, through `dynamic_axes` otherwise. A `dynamic_axes` or `dynamic_shapes` keyword+ argument replaces them.+ - The model is exported with `torch.onnx.export`, with constant folding enabled."""if not self.ONNX_EXPORTABLE:@@ -109,40 +161,81 @@ class ONNXExportMixin:if input_shape is None:input_shape = self.ONNX_DEFAULT_INPUTSHAPE+ if pseudo_shape is not None and len(pseudo_shape) == len(input_shape):+ # The default's fixed entries (the channel count) follow the example the caller gave.+ input_shape = [dim if dim == -1 else size for dim, size in zip(input_shape, pseudo_shape)]+ elif pseudo_shape is not None and len(pseudo_shape) == len(input_shape):+ conflicts = [i for i, (dim, size) in enumerate(zip(input_shape, pseudo_shape)) if dim not in (-1, size)]+ if conflicts:+ raise ValueError(+ f"input_shape {list(input_shape)} fixes dimension(s) {conflicts} to other sizes than pseudo_shape "+ f"{list(pseudo_shape)}. Make the two agree, or mark those dimensions -1 in input_shape."+ )if output_shape is None:output_shape = self.ONNX_DEFAULT_OUTPUTSHAPE+ resolved_pseudo_shape = self.ONNX_EXPORT_PSEUDO_SHAPE if pseudo_shape is None else pseudo_shape+ if -1 in input_shape and len(input_shape) != len(resolved_pseudo_shape):+ raise ValueError(+ f"input_shape {list(input_shape)} has {len(input_shape)} dimensions, but the pseudo shape "+ f"{list(resolved_pseudo_shape)} that sizes its dynamic dimensions has {len(resolved_pseudo_shape)}. "+ "Pass a pseudo_shape of the same rank."+ )if onnx_name is None:onnx_name = f"Kornia-{self.__class__.__name__}.onnx"+ if save:+ directory = os.path.dirname(os.path.abspath(onnx_name))+ if not os.path.isdir(directory):+ raise FileNotFoundError(f"Cannot save the ONNX model to {onnx_name}: {directory} does not exist.")+ module = self if model is None else modeldummy_input = self._create_dummy_input(input_shape, pseudo_shape)- dynamic_axes = self._create_dynamic_axes(input_shape, output_shape)+ reference = _first_floating_tensor(module)+ if reference is not None:+ dummy_input = _to_floating(dummy_input, reference)default_args: dict[str, Any] = {"export_params": True,- "opset_version": 17,+ "opset_version": _ONNX_EXPORT_OPSET,"do_constant_folding": True,"input_names": ["input"],"output_names": ["output"],- "dynamic_axes": dynamic_axes,}+ if "dynamic_axes" not in kwargs and "dynamic_shapes" not in kwargs:+ # The dynamo exporter (the default from torch 2.9) takes ``dynamic_shapes`` and warns on ``dynamic_axes``.+ if torch_version_ge(2, 9, 0) and kwargs.get("dynamo", True):+ default_args["dynamic_shapes"] = self._create_dynamic_shapes(input_shape, dummy_input)+ else:+ default_args["dynamic_axes"] = self._create_dynamic_axes(input_shape, output_shape)default_args.update(kwargs)- onnx_buffer = io.BytesIO()- torch.onnx.export(- model or self, # type: ignore[arg-type]- dummy_input, # type: ignore[arg-type]- onnx_buffer, # type: ignore[arg-type]- **default_args,- )- onnx_buffer.seek(0)- onnx_model = onnx.load(onnx_buffer) # type: ignore-- if additional_metadata is None:- additional_metadata = []- additional_metadata = copy.deepcopy(additional_metadata)- additional_metadata.extend(self.ADDITIONAL_METADATA)- onnx_model = kornia.onnx.utils.add_metadata(onnx_model, additional_metadata)+ # 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.+ modes = [(m, m.training) for m in module.modules()] if isinstance(module, nn.Module) else []+ try:+ if isinstance(module, nn.Module):+ module.eval()+ # A file path rather than a buffer: exporting to ``io.BytesIO`` is deprecated from torch 2.9.+ with tempfile.TemporaryDirectory() as tmp_dir:+ tmp_path = os.path.join(tmp_dir, "model.onnx")+ torch.onnx.export(+ module, # type: ignore[arg-type]+ dummy_input, # type: ignore[arg-type]+ tmp_path,+ **default_args,+ )+ onnx_model = onnx.load(tmp_path) # type: ignore+ finally:+ # The flag is set directly on purpose: ``train()`` recurses into the children, which would lose a mixed+ # state. It also skips ``train()`` overrides: TinyViT's ``Attention.train(True)`` would drop the attention+ # bias cached in eval mode, which is harmless because a training-mode forward does not read it. Check any+ # new ``train()`` override with side effects against this restore.+ for submodule, training in modes:+ submodule.training = training++ # Later entries overwrite earlier ones, so the caller's metadata wins over the class's.+ metadata = [*self.ADDITIONAL_METADATA, *(additional_metadata or [])]+ onnx_model = kornia.onnx.utils.add_metadata(onnx_model, metadata)if save:onnx.save(onnx_model, onnx_name) # type: ignorereturn onnx_model@@ -163,6 +256,15 @@ class ONNXExportMixin:"output": {i: "dim_" + str(i) for i, dim in enumerate(output_shape) if dim == -1},}+ def _create_dynamic_shapes(+ self, input_shape: list[int], dummy_input: Union[tuple[Any, ...], torch.Tensor]+ ) -> tuple[Optional[dict[int, str]], ...]:+ # A named dimension is ``Dim.DYNAMIC`` to ``torch.export``, and the name is kept in the ONNX graph.+ dims = {i: "dim_" + str(i) for i, dim in enumerate(input_shape) if dim == -1} or None+ if isinstance(dummy_input, tuple):+ return (dims, *([None] * (len(dummy_input) - 1)))+ return (dims,)+class ONNXRuntimeMixin:"""Provide methods to manage ONNX Runtime inference sessions."""@@ -171,7 +273,7 @@ class ONNXRuntimeMixin:self,op: onnx.ModelProto, # type:ignoreproviders: Optional[list[str]] = None,- session_options: Optional[ort.InferenceSession] = None, # type:ignore+ session_options: Optional[ort.SessionOptions] = None, # type:ignore) -> ort.InferenceSession: # type:ignore"""Create an optimized ONNXRuntime InferenceSession for the combined model.@@ -180,18 +282,19 @@ class ONNXRuntimeMixin:providers:Execution providers for ONNXRuntime (e.g., ['CUDAExecutionProvider', 'CPUExecutionProvider']).session_options:- Optional ONNXRuntime session options for session configuration and optimizations.+ Optional ONNXRuntime session options for session configuration and optimizations, used as given.+ If None, the session uses ``ORT_ENABLE_EXTENDED`` graph optimizations.Returns:ort.InferenceSession: The ONNXRuntime session optimized for inference."""if session_options is None:- sess_options = ort.SessionOptions() # type:ignore- sess_options.graph_optimization_level = ort.GraphOptimizationLevel.ORT_ENABLE_EXTENDED # type:ignore+ session_options = ort.SessionOptions() # type:ignore+ session_options.graph_optimization_level = ort.GraphOptimizationLevel.ORT_ENABLE_EXTENDED # type:ignorereturn ort.InferenceSession( # type:ignoreop.SerializeToString(),- sess_options=sess_options,+ sess_options=session_options,providers=providers or ["CPUExecutionProvider"],)@@ -390,11 +493,14 @@ class ONNXMixin:) -> onnx.ModelProto: # type:ignore"""Add metadata to the combined ONNX model.+ The ``source`` and ``version`` entries are always written. A key that is already present is overwritten,+ so the model keeps one entry per key, as ``onnx.checker.check_model`` requires.+Args:op: onnx operation.additional_metadata:A list of tuples representing additional metadata to add to the combined ONNX model.- Example: [("version", 0.1)], [("date", 20240909)].+ Example: [("model_version", "0.1"), ("date", "20240909")]."""return kornia.onnx.utils.add_metadata(op, additional_metadata)@@ -413,7 +519,7 @@ class ONNXMixin:target_opset_version: The target OPSET version to convert to."""- if op.ir_version != target_ir_version or op.opset_import[0].version != target_opset_version:+ if op.ir_version != target_ir_version or self._opset_version(op) != target_opset_version:# Check if all ops are supported in the current IR versionmodel_bytes = io.BytesIO()onnx.save_model(op, model_bytes) # type:ignore@@ -428,3 +534,11 @@ class ONNXMixin:loaded_model.ir_version = target_ir_versionop = loaded_modelreturn op++ @staticmethod+ def _opset_version(op: onnx.ModelProto) -> Optional[int]: # type:ignore+ """Return the version of the default (``ai.onnx``) operator set that ``op`` imports, or None."""+ for entry in op.opset_import:+ if entry.domain in ("", "ai.onnx"):+ return entry.version+ return Nonediff --git a/kornia/onnx/sequential.py b/kornia/onnx/sequential.pyindex d4f4e2afe..8338c9bed 100644--- a/kornia/onnx/sequential.py+++ b/kornia/onnx/sequential.py@@ -42,8 +42,9 @@ class ONNXSequential(ONNXMixin, ONNXRuntimeMixin):If not None, `io_maps[0]` shall represent the `io_map` for combining the first and second ONNX models.cache_dir: The directory where ONNX models are cached locally (only for downloading from HuggingFace).Defaults to None, which will use a default `kornia.config.hub_onnx_dir` directory.- auto_ir_version_conversion: If True, automatically convert the model's IR version to 9, and OPSET version to 17.- Other versions may be pointed to by `target_ir_version` and `target_opset_version`.+ auto_ir_version_conversion: If True, convert the models to one IR version and one OPSET version before+ combining them: IR version 9, and the highest OPSET version among the models, to which the others are+ converted up. Other versions may be pointed to by `target_ir_version` and `target_opset_version`.target_ir_version: The target IR version to convert to.target_opset_version: The target OPSET version to convert to.@@ -78,7 +79,8 @@ class ONNXSequential(ONNXMixin, ONNXRuntimeMixin):"""Automatic conversion of the model's IR/OPSET version to the given target version.If `target_ir_version` is not provided, the model is converted to 9 by default.- If `target_opset_version` is not provided, the model is converted to 17 by default.+ If `target_opset_version` is not provided, the models are converted to the highest OPSET version among+ them.Args:args: List of operations to convert.@@ -86,11 +88,11 @@ class ONNXSequential(ONNXMixin, ONNXRuntimeMixin):target_opset_version: The target OPSET version to convert to."""- # TODO: maybe another logic for versioning.if target_ir_version is None:target_ir_version = 9if target_opset_version is None:- target_opset_version = 17+ versions = [version for version in map(self._opset_version, args) if version is not None]+ target_opset_version = max(versions) if versions else Noneop_list = []for op in args:diff --git a/kornia/onnx/utils.py b/kornia/onnx/utils.pyindex 8d8480166..b2d2a4b28 100644--- a/kornia/onnx/utils.py+++ b/kornia/onnx/utils.py@@ -212,12 +212,16 @@ def add_metadata("""Add metadata to an ONNX model.The metadata includes the source library (set to "kornia"), the version of kornia,- and any additional metadata provided as a list of key-value pairs.+ and any additional metadata provided as a list of key-value pairs. A key that is already+ present in the model (or earlier in the list) is overwritten rather than repeated, since+ ``onnx.checker.check_model`` rejects duplicate keys. Duplicate keys already in the model, as+ earlier kornia versions wrote them, are merged into one entry with the last value, the one+ onnxruntime reads.Args:onnx_model: The ONNX model to add metadata to.additional_metadata: A list of tuples, where each tuple contains a key and a value- for the additional metadata to add to the ONNX model.+ for the additional metadata to add to the ONNX model. Values are stored as strings.Returns:The ONNX model with the added metadata.@@ -225,14 +229,19 @@ def add_metadata("""if additional_metadata is None:additional_metadata = []+ # Rebuilt from a mapping, which keeps each key at its first position with its last value.+ metadata = {metadata_props.key: metadata_props.value for metadata_props in onnx_model.metadata_props}for key, value in [("source", "kornia"),("version", kornia.__version__),*additional_metadata,]:+ metadata[key] = str(value)+ del onnx_model.metadata_props[:]+ for key, value in metadata.items():metadata_props = onnx_model.metadata_props.add()metadata_props.key = key- metadata_props.value = str(value)+ metadata_props.value = valuereturn onnx_modeldiff --git a/tests/contrib/test_super_resolution.py b/tests/contrib/test_super_resolution.pyindex 4c45fca3e..0b626352a 100644--- a/tests/contrib/test_super_resolution.py+++ b/tests/contrib/test_super_resolution.py@@ -128,6 +128,16 @@ class TestSuperResolutionBuilders(BaseTester):assert out.shape[-2] == model.output_image_sizeassert model.output_image_size == 224 * upscale_factor+ def test_to_onnx_with_only_an_input_size_uses_it_for_the_dummy_input(self):+ """A fixed ``input_image_size`` without a ``pseudo_image_size`` is also the size of the dummy input."""+ pytest.importorskip("onnx")+ pytest.importorskip("onnxscript")+ model = SuperResolution(torch.nn.Conv2d(3, 3, 3, padding=1), torch.nn.Identity(), torch.nn.Identity())+ model.input_image_size = 64+ exported = model.to_onnx(save=False, include_pre_and_post_processor=False)+ dims = exported.graph.input[0].type.tensor_type.shape.dim+ assert [d.dim_value for d in dims[1:]] == [3, 64, 64]+def test_onnx_export_shape_matches_the_real_forward(self):"""The static size handed to ``to_onnx`` must be the one the graph produces."""pytest.importorskip("onnx")diff --git a/tests/core/test_onnx_mixin.py b/tests/core/test_onnx_mixin.pynew file mode 100644index 000000000..bb33aabf9--- /dev/null+++ b/tests/core/test_onnx_mixin.py@@ -0,0 +1,247 @@+# LICENSE HEADER MANAGED BY add-license-header+#+# Copyright 2018 Kornia Team+#+# Licensed under the Apache License, Version 2.0 (the "License");+# you may not use this file except in compliance with the License.+# You may obtain a copy of the License at+#+# http://www.apache.org/licenses/LICENSE-2.0+#+# Unless required by applicable law or agreed to in writing, software+# distributed under the License is distributed on an "AS IS" BASIS,+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+# See the License for the specific language governing permissions and+# limitations under the License.+#++"""Export and runtime contract of the ONNX mixins, checked end to end through onnxruntime."""++import copy++import pytest+import torch+from torch import nn++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++onnx = pytest.importorskip("onnx")+ort = pytest.importorskip("onnxruntime")+if torch_version_ge(2, 9, 0):+ # From torch 2.9 ``torch.onnx.export`` defaults to the dynamo exporter, which needs onnxscript.+ pytest.importorskip("onnxscript")++# The opset ``to_onnx`` documents and requests.+DOCUMENTED_OPSET = 18++_RGB = {"input_shape": [-1, 3, -1, -1], "output_shape": [-1, 3, -1, -1]}+++def _default_domain_opset(op):+ return next(entry.version for entry in op.opset_import if entry.domain in ("", "ai.onnx"))+++def _input_dims(op):+ return [d.dim_param or d.dim_value for d in op.graph.input[0].type.tensor_type.shape.dim]+++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])++[email protected]_agnostic+class TestONNXExportMixin(BaseTester):+ def test_train_mode_model_exports_the_eval_graph(self):+ torch.manual_seed(0)+ model = ImageSequential(nn.Conv2d(3, 3, 3, padding=1), nn.BatchNorm2d(3), nn.Dropout(0.5))+ model.train()+ model[1].eval() # a mixed state, which must come back exactly+ op = model.to_onnx(save=False, **_RGB)++ assert "Dropout" not in {node.op_type for node in op.graph.node}+ assert [m.training for m in (model, *model)] == [True, True, False, True]++ x = torch.rand(2, 3, 8, 8)+ with torch.no_grad():+ expected = copy.deepcopy(model).eval()(x)+ self.assert_close(_run(op, x), expected)++ def test_failed_export_restores_the_training_mode(self, monkeypatch):+ model = ImageSequential(nn.Conv2d(3, 3, 1), nn.Dropout(0.5))+ model.train()+ model[0].eval() # a mixed state: ``model.train(True)`` in place of an exact restore would lose it++ def _fail(*args, **kwargs):+ raise RuntimeError("export failed")++ monkeypatch.setattr(torch.onnx, "export", _fail)+ with pytest.raises(RuntimeError, match="export failed"):+ model.to_onnx(save=False, **_RGB)+ assert [m.training for m in (model, *model)] == [True, False, True]++ 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.+ model = ImageSequential(nn.Conv2d(3, 3, 1), nn.Dropout(0.5))+ model[0].eval()+ op = model.to_onnx(save=False, dynamo=False, training=torch.onnx.TrainingMode.TRAINING, **_RGB)++ assert "Dropout" in {node.op_type for node in op.graph.node}+ assert [m.training for m in (model, *model)] == [True, False, True]++ @pytest.mark.skipif(+ not torch_version_ge(2, 9, 0), reason="the torch.export-based exporter is the default from torch 2.9"+ )+ def test_default_exporter_from_torch_2_9_ignores_the_training_keyword(self):+ model = ImageSequential(nn.Conv2d(3, 3, 1), nn.Dropout(0.5))+ model.train()+ op = model.to_onnx(save=False, training=torch.onnx.TrainingMode.TRAINING, **_RGB)++ assert "Dropout" not in {node.op_type for node in op.graph.node}+ assert model.training++ @pytest.mark.parametrize(+ "channels, module",+ [(3, lambda: nn.Conv2d(3, 3, 1)), (1, lambda: GaussianBlur2d((3, 3), (1.5, 1.5)))],+ ids=["conv", "gaussian_blur"],+ )+ def test_saved_model_has_the_documented_opset(self, tmp_path, channels, module):+ # The dynamo exporter builds opset 18 and down-converts a lower request only when every op has an adapter, which+ # a convolution has and the blur's ``Pad`` has not. Static shapes: the legacy exporter cannot export+ # GaussianBlur2d with a dynamic dimension, even the batch alone (#5222).+ path = tmp_path / "model.onnx"+ shape = [2, channels, 16, 16]+ op = ImageSequential(module()).to_onnx(onnx_name=str(path), input_shape=shape, output_shape=shape)+ assert _default_domain_opset(op) == DOCUMENTED_OPSET+ assert _default_domain_opset(onnx.load(str(path))) == DOCUMENTED_OPSET++ def test_default_input_shape_exports_a_fixed_channel_model(self):+ model = ImageSequential(nn.Conv2d(3, 3, 1))+ op = model.to_onnx(save=False)++ dims = _input_dims(op)+ assert dims[1] == 3+ assert all(isinstance(d, str) for d in (dims[0], dims[2], dims[3]))++ x = torch.rand(2, 3, 5, 7)+ with torch.no_grad():+ expected = model(x)+ self.assert_close(_run(op, x), expected)++ def test_pseudo_shape_alone_sets_the_channel_count(self):+ # Without input_shape, the default's fixed channel count follows an explicit pseudo shape.+ model = ImageSequential(nn.Conv2d(1, 1, 1))+ op = model.to_onnx(save=False, pseudo_shape=[1, 1, 32, 32])++ x = torch.rand(2, 1, 5, 7)+ with torch.no_grad():+ expected = model(x)+ self.assert_close(_run(op, x), expected)++ dims = _input_dims(op)+ assert dims[1] == 1+ assert all(isinstance(d, str) for d in (dims[0], dims[2], dims[3]))++ def test_input_shape_must_agree_with_an_explicit_pseudo_shape(self):+ with pytest.raises(ValueError, match="input_shape"):+ ImageSequential(nn.Sigmoid()).to_onnx(save=False, input_shape=[-1, 3, -1, -1], pseudo_shape=[1, 1, 32, 32])++ def test_input_shape_rank_must_match_the_pseudo_shape(self):+ with pytest.raises(ValueError, match="pseudo shape"):+ ImageSequential(nn.Identity()).to_onnx(save=False, input_shape=[-1, 3, -1, -1, -1])++ def test_missing_output_directory_is_reported_before_exporting(self, tmp_path, monkeypatch):+ def _must_not_export(*args, **kwargs):+ raise AssertionError("the export ran before the output directory was checked")++ monkeypatch.setattr(torch.onnx, "export", _must_not_export)+ with pytest.raises(FileNotFoundError, match="no_such_dir"):+ ImageSequential(nn.Identity()).to_onnx(onnx_name=str(tmp_path / "no_such_dir" / "x.onnx"), **_RGB)+++class _ChannelAffine(nn.Module):+ """A per-channel affine map, with its weights as parameters or as buffers.++ Its ops run in float16, float32 and float64 on onnxruntime's CPU provider.+ """++ def __init__(self, as_buffers: bool = False) -> None:+ super().__init__()+ weight = torch.linspace(0.5, 1.5, 3).view(1, 3, 1, 1)+ bias = torch.linspace(-0.25, 0.25, 3).view(1, 3, 1, 1)+ if as_buffers:+ self.register_buffer("weight", weight)+ self.register_buffer("bias", bias)+ else:+ self.weight = nn.Parameter(weight)+ self.bias = nn.Parameter(bias)++ def forward(self, x: torch.Tensor) -> torch.Tensor:+ return x * self.weight + self.bias+++class TestONNXExportMixinDtypeDevice(BaseTester):+ @pytest.mark.parametrize("as_buffers", [False, True], ids=["parameters", "buffers"])+ def test_dummy_input_follows_the_model_dtype_and_device(self, device, dtype, as_buffers):+ model = ImageSequential(_ChannelAffine(as_buffers)).to(device, dtype)+ assert len(list(model.parameters())) == (0 if as_buffers else 2)+ op = model.to_onnx(save=False, **_RGB)++ elem_types = {+ torch.float16: onnx.TensorProto.FLOAT16,+ torch.bfloat16: onnx.TensorProto.BFLOAT16,+ torch.float32: onnx.TensorProto.FLOAT,+ torch.float64: onnx.TensorProto.DOUBLE,+ }+ assert op.graph.input[0].type.tensor_type.elem_type == elem_types[dtype]+ if dtype == torch.bfloat16:+ return # onnxruntime's CPU provider has no bfloat16 Mul, and numpy no bfloat16 to feed it++ x = torch.linspace(0, 1, 2 * 3 * 5 * 7, device=device, dtype=dtype).view(2, 3, 5, 7)+ with torch.no_grad():+ expected = model(x)+ self.assert_close(_run(op, x.cpu()), expected.cpu())++[email protected]_agnostic+class TestONNXRuntimeMixin(BaseTester):+ @pytest.fixture+ def op(self):+ return ImageSequential(nn.Sigmoid()).to_onnx(save=False, **_RGB)++ def test_session_options_are_used(self, op):+ from kornia.onnx import ONNXModule, ONNXSequential++ def _options():+ options = ort.SessionOptions()+ options.graph_optimization_level = ort.GraphOptimizationLevel.ORT_DISABLE_ALL+ return options++ sessions = [+ ONNXRuntimeMixin()._create_session(op, session_options=_options()),+ ONNXSequential(op, session_options=_options()).get_session(),+ ONNXModule(op, session_options=_options()).get_session(),+ ]+ for session in sessions:+ level = session.get_session_options().graph_optimization_level+ assert level == ort.GraphOptimizationLevel.ORT_DISABLE_ALL++ x = torch.rand(1, 3, 4, 5)+ self.assert_close(torch.from_numpy(ONNXSequential(op, session_options=_options())(x.numpy())[0]), x.sigmoid())++ def test_add_metadata_overwrites_existing_keys(self, op):+ keys = [prop.key for prop in op.metadata_props]+ assert sorted(keys) == ["source", "version"]++ again = ONNXMixin()._add_metadata(copy.deepcopy(op), [("date", "20240909")])+ again = ONNXMixin()._add_metadata(again, [("date", "20260930")])++ assert sorted(prop.key for prop in again.metadata_props) == ["date", "source", "version"]+ assert {prop.key: prop.value for prop in again.metadata_props}["date"] == "20260930"+ onnx.checker.check_model(again)diff --git a/tests/onnx/test_sequential.py b/tests/onnx/test_sequential.pyindex 5b4a9f057..a01458e52 100644--- a/tests/onnx/test_sequential.py+++ b/tests/onnx/test_sequential.py@@ -16,6 +16,11 @@#import pytest+import torch++from kornia.core._compat import torch_version_ge++from testing.base import assert_close# Every test in this module must stay device-free: the mark deselects the whole file on non-CPU devices.pytestmark = pytest.mark.device_agnostic@@ -108,3 +113,53 @@ class TestONNXSequential:mock_session = MagicMock(spec=ort.InferenceSession)onnx_sequential.set_session(mock_session)assert onnx_sequential.get_session() == mock_session+++def _opsets(op):+ # merge_models can repeat an opset import, so compare the set of default-domain versions.+ return {entry.version for entry in op.opset_import if entry.domain in ("", "ai.onnx")}+++class TestONNXSequentialOfKorniaExports:+ """Chains of graphs exported by ``to_onnx``, run in onnxruntime against eager."""++ @pytest.fixture(autouse=True)+ def _exporter(self):+ pytest.importorskip("onnxruntime")+ if torch_version_ge(2, 9, 0):+ pytest.importorskip("onnxscript") # the dynamo exporter, the default from torch 2.9++ def test_auto_version_conversion_accepts_kornia_exports(self):+ from kornia.core import ImageSequential+ from kornia.filters import GaussianBlur2d++ # Static shapes: the legacy exporter cannot export GaussianBlur2d with a dynamic dimension, even the batch+ # alone (#5222).+ shapes = {"input_shape": [2, 1, 16, 16], "output_shape": [2, 1, 16, 16]}+ blur = ImageSequential(GaussianBlur2d((3, 3), (1.5, 1.5)))+ sigmoid = ImageSequential(torch.nn.Sigmoid())+ ops = [blur.to_onnx(save=False, **shapes), sigmoid.to_onnx(save=False, **shapes)]++ seq = ONNXSequential(*ops, auto_ir_version_conversion=True)++ x = torch.rand(2, 1, 16, 16)+ assert_close(torch.from_numpy(seq(x.numpy())[0]), sigmoid(blur(x)))+ assert _opsets(seq._combined_op) == _opsets(ops[0]) == _opsets(ops[1])++ def test_default_target_opset_is_the_highest_among_the_models(self):+ from onnx import version_converter++ from kornia.core import ImageSequential++ op = ImageSequential(torch.nn.Sigmoid()).to_onnx(+ save=False, input_shape=[-1, 3, -1, -1], output_shape=[-1, 3, -1, -1]+ )+ (version,) = _opsets(op)+ newer = version_converter.convert_version(op, version + 1)++ seq = ONNXSequential(op, newer, auto_ir_version_conversion=True)++ # The older graph is brought up to the newer one's opset rather than both to a fixed one.+ assert _opsets(seq._combined_op) == {version + 1}+ x = torch.rand(1, 3, 4, 5)+ assert_close(torch.from_numpy(seq(x.numpy())[0]), x.sigmoid().sigmoid())diff --git a/tests/onnx/test_utils.py b/tests/onnx/test_utils.pyindex dd7dfc04a..692cf2680 100644--- a/tests/onnx/test_utils.py+++ b/tests/onnx/test_utils.py@@ -194,27 +194,65 @@ def test_io_name_conversion():def test_add_metadata():- from unittest import mock+ from onnx.helper import make_graph, make_model, make_node, make_tensor_value_info+ import korniafrom kornia.onnx.utils import add_metadata- with mock.patch("kornia.core.external.onnx.ModelProto") as mock_model_proto:- # Arrange- mock_model = mock_model_proto()- mock_metadata_props = mock.Mock()- mock_model.metadata_props.add.return_value = mock_metadata_props-- # Act- add_metadata(mock_model, [("test_key", "test_value")])+ graph = make_graph(+ [make_node("Identity", ["input"], ["output"])],+ "identity",+ [make_tensor_value_info("input", onnx.TensorProto.FLOAT, [1])],+ [make_tensor_value_info("output", onnx.TensorProto.FLOAT, [1])],+ )+ model = add_metadata(make_model(graph), [("test_key", "test_value")])+ assert [(p.key, p.value) for p in model.metadata_props] == [+ ("source", "kornia"),+ ("version", kornia.__version__),+ ("test_key", "test_value"),+ ]++ # A second call overwrites the existing keys instead of appending duplicates, which check_model rejects.+ model = add_metadata(model, [("test_key", 2)])+ assert [(p.key, p.value) for p in model.metadata_props] == [+ ("source", "kornia"),+ ("version", kornia.__version__),+ ("test_key", "2"),+ ]+ onnx.checker.check_model(model)+++def test_add_metadata_merges_duplicate_keys_already_in_the_model():+ from onnx.helper import make_graph, make_model, make_node, make_tensor_value_info++ import kornia+ from kornia.onnx.utils import add_metadata- # Assert- calls = [- mock.call(), # for "source"- mock.call(), # for "version"- mock.call(), # for "test_key"- ]- mock_model.metadata_props.add.assert_has_calls(calls)- assert mock_model.metadata_props.add.call_count == 3- # Check if version was added- # (Since it's a mock, we just check if any call set value to kornia.__version__)- # Metadata logic: metadata_props.key = key; metadata_props.value = str(value)+ graph = make_graph(+ [make_node("Identity", ["input"], ["output"])],+ "identity",+ [make_tensor_value_info("input", onnx.TensorProto.FLOAT, [1])],+ [make_tensor_value_info("output", onnx.TensorProto.FLOAT, [1])],+ )+ model = make_model(graph)+ # Earlier versions appended on every call, so a model exported and then tagged again repeats its keys. A key the+ # call does not set keeps its last value, the one onnxruntime reads.+ for key, value in [+ ("source", "kornia"),+ ("version", "0.8.0"),+ ("author", "a"),+ ("source", "kornia"),+ ("version", "0.8.0"),+ ("author", "b"),+ ]:+ entry = model.metadata_props.add()+ entry.key, entry.value = key, value++ model = add_metadata(model, [("date", "20261001")])+ assert [(p.key, p.value) for p in model.metadata_props] == [+ ("source", "kornia"),+ ("version", kornia.__version__),+ ("author", "b"),+ ("date", "20261001"),+ ]+ onnx.checker.check_model(model)