Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

fix(onnx): ONNXSequential chains models with differing metadata, applies target versions, accepts paths and CPU tensors (#6134)

Dmytro Mishkin7c4e73261bf3
diff --git a/changelog.d/6134.breaking.md b/changelog.d/6134.breaking.md
new file mode 100644
index 000000000..9e23e9490
--- /dev/null
+++ b/changelog.d/6134.breaking.md
@@ -0,0 +1,6 @@
+`ONNXSequential` given `target_opset_version` or `target_ir_version` without `auto_ir_version_conversion=True` now
+converts the models; the targets used to be ignored, and the call ran on the models as loaded. Where the conversion
+fails, the call now raises its error: the ONNX version converter's where it has no adapter for an operator (for example
+`Resize` or `Pad` from opset 18 to 17), `onnx.checker`'s where the converted graph is invalid (for example
+`Unrecognized attribute: noop_with_empty_axes for operator ReduceMean` from opset 18 to 17), or ONNX Runtime's where it
+does not support the target (an IR version above its own).
diff --git a/changelog.d/6134.fixed.md b/changelog.d/6134.fixed.md
new file mode 100644
index 000000000..be64f43db
--- /dev/null
+++ b/changelog.d/6134.fixed.md
@@ -0,0 +1,43 @@
+`kornia.onnx` composition and loading:
+
+- `ONNXSequential`, and `HFONNXComunnityModel` / `DepthEstimation` built on it, chain models whose metadata differ for
+ a key: a graph exported by another kornia release (its `version`), exports given different `additional_metadata`
+ values, or an onnx-community model whose `source` differs from the kornia pre-processor's. They used to raise
+ `ValueError: Can't merge models with different values for the same model metadata property`. The combined model
+ holds one entry per key, at its first position, with the value of the last model that sets it; the models passed in
+ are not modified.
+- `ONNXSequential` applies `target_ir_version` and `target_opset_version` without `auto_ir_version_conversion=True`,
+ as `ONNXModule` does; it used to ignore them silently. Without the flag, only the versions given are changed, and a
+ model that already has them is not converted again (`ONNXModule` as well).
+- A conversion to a target version, by `ONNXModule` or `ONNXSequential` with or without the flag, accepts a model that
+ lists a metadata key twice, as kornia 0.9.0rc1 wrote after `add_metadata`, and keeps one entry per key with its last
+ value, the one ONNX Runtime reads; it used to raise `ValidationError: Your model has duplicate keys in
+ metadata_props`. A combined model lists each operator-set domain once, so it can be converted and chained again; the
+ conversion used to update only one of the repeated entries, and the next merge raised `Can't merge two models with
+ different operator set ids`.
+- `ONNXSequential` warns (`UserWarning`) when the tensor element types of an output and the input it feeds differ at
+ a joint: the merged graph does not check a later model's declared input types, so such a chain runs on the earlier
+ model's type, or fails later with ONNX Runtime's `Type Error`, as before. Declared dimensions are not compared.
+- A malformed `io_maps` raises a `ValueCheckError` (a `ValueError`) that says `io_maps` holds one list of
+ `(output, input)` name pairs per joint, where it used to raise `IndexError` (an entry missing) or
+ `ValueError: Output K00-m is not present in g1` (a flat list of pairs, the form the ONNX guide showed). A pair with
+ more than two names, whose extra names were ignored, now raises it too. An entry may still be any iterable of pairs
+ (a `zip`, `dict.items()`, a generator, a numpy array) and `io_maps` anything indexed by the joint, and entries past
+ the last joint are still not read. The `io_maps` annotations of `ONNXSequential`, `ONNXSequential.combine` and
+ `HFONNXComunnityModel` are now `list[list[tuple[str, str]]]`, and the guide's example is a list of lists.
+- `ONNXModule`, `ONNXSequential`, `kornia.onnx.load`, `ONNXLoader.load_model` and `ONNXLoader.load_config` take
+ file paths as `os.PathLike` objects such as `pathlib.Path` (always a local file), and expand a leading `~` in a
+ local path. A path object used to raise `ValueError: Invalid argument type` (`AttributeError` from the two loaders).
+ An argument of another type now raises a `TypeError` that names what is accepted, instead of `ValueError`
+ (`AttributeError` from the two loaders); for `bytes`, which ONNX Runtime reads as a serialized model, it says to pass
+ `onnx.load_model_from_string(data)`.
+- Calling `ONNXModule` or `ONNXSequential` takes CPU torch tensors of a dtype numpy has (not bfloat16 or the float8
+ types) as well as numpy arrays, and still returns numpy arrays; a tensor used to raise ONNX Runtime's `RuntimeError:
+ Input must be a list of dictionaries or a single numpy array`. A tensor on another device raises a `ValueError` that
+ says to move it to the CPU, and a sparse tensor or one of a dtype numpy lacks a `TypeError` that names the input and
+ how to convert it.
+- `ONNXLoader.load_config` reads an existing local JSON file, which it used to report as not found ("You may set
+ `download=True`"). An argument that is neither an HTTP(S) URL nor an existing file (a directory, for one) raises a
+ `RuntimeError` that says so.
+- The `ONNXModule` docstring documents its parameter `op`, one model, and `io_name_conversion` documents that it
+ applies any mapping in place, returns the same model, and leaves initializers, `value_info` and subgraphs alone.
diff --git a/docs/source/get-started/onnx.rst b/docs/source/get-started/onnx.rst
index d718d4aec..4cd130d00 100644
--- a/docs/source/get-started/onnx.rst
+++ b/docs/source/get-started/onnx.rst
@@ -11,7 +11,8 @@ runs it with ONNX Runtime. It is useful when you have pre-exported operators or
- **Model chaining**: combine multiple ONNX models into one graph, with control over how the outputs of one model
feed the inputs of the next.
- **Export**: save the combined model as a single ONNX file.
-- **PyTorch-like interface**: call the sequence directly, like an ``nn.Sequential``.
+- **PyTorch-like interface**: call the sequence directly, like an ``nn.Sequential``, on numpy arrays or CPU torch
+ tensors of a dtype numpy has (not bfloat16 or float8). It returns numpy arrays.
- **Execution providers**: run on CPU, CUDA, TensorRT or OpenVINO through ONNX Runtime, with control over the
session options.
@@ -97,11 +98,18 @@ Quickstart
4. **Map inputs and outputs between models**
+ ``io_maps`` holds one list of ``(output, input)`` name pairs per joint between consecutive models:
+ ``io_maps[0]`` connects the first model to the second, ``io_maps[1]`` the second to the third, and so on.
+
.. code-block:: python
- io_maps = [("model1_output_0", "model2_input_0"), ("model1_output_1", "model2_input_1")]
+ # one joint, which feeds two outputs of model1 to two inputs of model2
+ io_maps = [[("model1_output_0", "model2_input_0"), ("model1_output_1", "model2_input_1")]]
onnx_seq = ONNXSequential("model1.onnx", "model2.onnx", io_maps=io_maps)
+ The merged graph does not check a later model's declared input types: ``ONNXSequential`` warns when the tensor
+ element types of an output and the input it feeds differ at a joint.
+
5. **Export the combined model**
.. code-block:: python
@@ -173,7 +181,8 @@ Yes. Models can come from ONNX files, ``onnx.ModelProto`` objects or ``hf://`` r
differ, as a fresh export and a Hub operator do, pass ``auto_ir_version_conversion=True``.
**What if the input/output names of two models do not match?**
-Use the ``io_maps`` argument to say which output feeds which input.
+Use the ``io_maps`` argument to say which output feeds which input: one list of ``(output, input)`` name pairs per
+joint, as in step 4.
**Can I use custom ONNX Runtime session options?**
Yes, pass your own session options to the ``create_session`` method.
diff --git a/kornia/core/mixin/onnx.py b/kornia/core/mixin/onnx.py
index 536f0f164..4d0d101fe 100644
--- a/kornia/core/mixin/onnx.py
+++ b/kornia/core/mixin/onnx.py
@@ -35,15 +35,136 @@ from torch import nn
import kornia
from kornia.core._compat import torch_version_ge
+from kornia.core.exceptions import ValueCheckError
from kornia.core.external import numpy as np
from kornia.core.external import onnx
from kornia.core.external import onnxruntime as ort
+from kornia.core.utils import _warn_at_caller
# 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 _host_array(value: Any, index: int) -> Any:
+ """Return ``value`` for an ONNX Runtime session: a torch tensor on the CPU as a numpy array sharing its memory."""
+ if not isinstance(value, torch.Tensor):
+ return value
+ if value.device.type != "cpu":
+ raise ValueError(
+ f"ONNX input {index} is a torch tensor on {value.device}, but the ONNX Runtime session is run on arrays "
+ "in host memory, whatever its execution provider. Move it to the CPU first, with .cpu()."
+ )
+ if value.layout != torch.strided:
+ raise TypeError(
+ f"ONNX input {index} is a {value.layout} tensor, which a numpy array cannot hold: convert it with "
+ ".to_dense() first."
+ )
+ try:
+ # resolve_conj and resolve_neg return the tensor itself unless a conjugate or negative view needs materializing
+ return value.detach().resolve_conj().resolve_neg().numpy()
+ except TypeError as error: # a dtype numpy has no equivalent of: bfloat16, the float8 types, quantized types
+ raise TypeError(
+ f"ONNX input {index} is a {value.dtype} tensor, a dtype numpy has no equivalent of: convert it, e.g. "
+ "with .float() for a float32 graph."
+ ) from error
+
+
+def _prefix(index: int) -> str:
+ """Return the prefix that ``ONNXMixin._combine`` gives the names of the model at ``index``."""
+ return f"K{str(index).zfill(2)}-"
+
+
+def _name_pairs(entry: Any) -> Optional[list[tuple[Any, Any]]]:
+ """Return the ``(output, input)`` pairs of one ``io_maps`` entry as a list, or None if it is not pairs.
+
+ The entry may be any iterable of pairs (a list, a ``zip``, a set, ``dict.items()``, a generator, a numpy array),
+ which is read once; a pair is any sequence of two names that is not itself a string (so a string entry, whose
+ items are its characters, is not pairs either).
+ """
+ try:
+ pairs = []
+ for pair in entry:
+ if isinstance(pair, (str, bytes)) or len(pair) != 2:
+ return None
+ pairs.append((pair[0], pair[1]))
+ except (TypeError, KeyError, IndexError):
+ return None
+ return pairs
+
+
+def _io_map_pairs(io_maps: Any, joints: int, models: int) -> list[list[tuple[Any, Any]]]:
+ """Return the pairs of each joint of ``io_maps``, reading ``io_maps[i]`` for joint ``i`` as the merge always did.
+
+ Any container indexed by the joint works, a dict keyed by it too; entries past the last joint are not read.
+
+ Raises:
+ ValueCheckError: If ``io_maps`` has no entry for a joint, or an entry is not an iterable of name pairs.
+ """
+ pairs_per_joint = []
+ for joint in range(joints):
+ try:
+ entry = io_maps[joint]
+ except (IndexError, KeyError):
+ raise ValueCheckError(
+ f"io_maps needs one list of (output, input) name pairs per joint, {joints} for {models} models, and "
+ f"has no entry for joint {joint}."
+ ) from None
+ pairs = _name_pairs(entry)
+ if pairs is None:
+ raise ValueCheckError(
+ f"io_maps[{joint}] must be a list of (output, input) name pairs: io_maps holds one such list per joint "
+ f"between consecutive models, as in [[('output', 'input')]] for two models. Got {entry!r}."
+ )
+ pairs_per_joint.append(pairs)
+ return pairs_per_joint
+
+
+def _warn_on_joint_element_types(
+ combined: onnx.ModelProto, following: onnx.ModelProto, pairs: list[tuple[Any, Any]], joint: int
+) -> None:
+ """Warn if an output of model ``joint`` and the input of the next model it feeds differ in tensor element type.
+
+ ``merge_models`` drops the declared inputs it connects, so ONNX Runtime no longer checks them: the later model
+ runs on the earlier one's type, which a model whose first nodes take any type (a ``Cast``, a ``Shape``) accepts,
+ and any other fails with ONNX Runtime's own message. The merge goes on either way. Only tensor element types are
+ compared, where both ends declare one; the declared dimensions are not, since a graph can declare fixed sizes where
+ it accepts others.
+ """
+ outputs = {value.name: value.type for value in combined.graph.output}
+ inputs = {value.name: value.type for value in following.graph.input}
+ for output_name, input_name in pairs:
+ output_type = outputs.get(f"{_prefix(joint)}{output_name}")
+ input_type = inputs.get(f"{_prefix(joint + 1)}{input_name}")
+ if output_type is None or input_type is None: # merge_models names the missing one
+ continue
+ # a type that is not a tensor (a sequence, an optional), or none at all, reads as UNDEFINED (0) here
+ output_elem, input_elem = output_type.tensor_type.elem_type, input_type.tensor_type.elem_type
+ if output_elem and input_elem and output_elem != input_elem:
+ _warn_at_caller(
+ f"The output {str(output_name)!r} of model {joint} is {onnx.TensorProto.DataType.Name(output_elem)}, "
+ f"but it feeds the input {str(input_name)!r} of model {joint + 1}, which is "
+ f"{onnx.TensorProto.DataType.Name(input_elem)}. The merged graph does not check a later model's "
+ "declared input types, so the chain runs on the earlier model's type, or fails in ONNX Runtime: the "
+ "tensor element types at each joint should agree. Convert one of the models, unless the later one "
+ "accepts both types."
+ )
+
+
+def _merge_opset_imports(model: onnx.ModelProto) -> None:
+ """Keep one ``opset_import`` entry per domain, in place.
+
+ ``onnx.compose.merge_models`` concatenates the entries of both models after checking that they agree, so a chain
+ of ``n`` models lists each domain ``n`` times; the version converter then updates only one of them, and the
+ converted graph no longer merges with a model of the target version. Entries that disagree, which the checker and
+ ONNX Runtime accept, keep the last version, the one both of them read and :meth:`ONNXMixin._opset_version`
+ returns; the version converter refuses such a model.
+ """
+ versions = {entry.domain: entry.version for entry in model.opset_import}
+ del model.opset_import[:]
+ model.opset_import.extend(onnx.helper.make_opsetid(domain, version) for domain, version in versions.items())
+
+
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):
@@ -419,23 +540,33 @@ class ONNXRuntimeMixin:
["OpenVINOExecutionProvider"], provider_options=[{"device_type": device_type, **kwargs}]
)
- def __call__(self, *inputs: np.ndarray) -> list[np.ndarray]:
+ def __call__(self, *inputs: Union[np.ndarray, torch.Tensor]) -> list[np.ndarray]:
"""Perform inference using the combined ONNX model.
Args:
- *inputs: Inputs to the ONNX model. The number of inputs must match the expected inputs of the session.
+ *inputs: Inputs to the ONNX model, in the order of ``get_session().get_inputs()``: numpy arrays, or
+ strided torch tensors on the CPU of a dtype numpy has (not bfloat16 or float8). A tensor is passed as
+ ``tensor.detach().numpy()``, which shares its memory (a conjugate or negative view is materialized
+ first). The number of inputs must match the expected inputs of the session.
Returns:
- list: The outputs from the ONNX model inference.
+ list: The outputs from the ONNX model inference, as numpy arrays for numpy and torch inputs alike.
Raises:
- ValueError: If the number of inputs differs from the length of ``get_session().get_inputs()``.
+ ValueError: If the number of inputs differs from the length of ``get_session().get_inputs()``, or an
+ input is a torch tensor on another device than the CPU: the session is run on arrays in host memory,
+ whatever its execution provider, so move such a tensor with ``.cpu()`` first.
+ TypeError: If an input is a bfloat16 tensor, which numpy has no dtype for (convert it, e.g. with
+ ``.float()``), or a sparse tensor (convert it with ``.to_dense()``).
"""
ort_inputs = self._session.get_inputs()
if len(inputs) != len(ort_inputs):
raise ValueError(f"Expected {len(ort_inputs)} ONNX inputs, got {len(inputs)}.")
- ort_input_values = {ort_input.name: input_value for ort_input, input_value in zip(ort_inputs, inputs)}
+ ort_input_values = {
+ ort_input.name: _host_array(input_value, index)
+ for index, (ort_input, input_value) in enumerate(zip(ort_inputs, inputs))
+ }
return self._session.run(None, ort_input_values)
@@ -444,35 +575,45 @@ class ONNXMixin:
def _load_op(
self,
- arg: Union[onnx.ModelProto, str],
+ arg: Union[onnx.ModelProto, str, os.PathLike],
cache_dir: Optional[str] = None,
) -> onnx.ModelProto:
"""Load an ONNX model, either from a file path or use the provided ONNX ModelProto.
Args:
- arg: Either an ONNX ModelProto object or a file path to an ONNX model.
+ arg: An ONNX ModelProto object; a ``str`` file path, ``hf://`` name or URL of an ONNX model; or an
+ :class:`os.PathLike` file path, which always names a local file. A local path may start with ``~``.
cache_dir: Where to read onnx objects from if stored on disk.
Returns:
onnx.ModelProto: The loaded ONNX model.
+ Raises:
+ TypeError: If ``arg`` is of another type, ``bytes`` included: ONNX Runtime reads ``bytes`` as a serialized
+ model, which ``onnx.load_model_from_string`` turns into a ModelProto.
+
"""
- if isinstance(arg, str):
- return kornia.onnx.utils.ONNXLoader.load_model(arg, cache_dir=cache_dir)
if isinstance(arg, onnx.ModelProto):
return arg
- raise ValueError(f"Invalid argument type. Got {type(arg)}")
+ if isinstance(arg, (str, os.PathLike)):
+ return kornia.onnx.utils.ONNXLoader.load_model(arg, cache_dir=cache_dir)
+ hint = " For a serialized model, pass onnx.load_model_from_string(data)." if isinstance(arg, bytes) else ""
+ raise TypeError(
+ "Expected an onnx.ModelProto, a str (a file path, an 'hf://' name or a URL), or an os.PathLike file path, "
+ f"got {type(arg).__name__}.{hint}"
+ )
def _load_ops(
self,
- *args: Union[onnx.ModelProto, str],
+ *args: Union[onnx.ModelProto, str, os.PathLike],
cache_dir: Optional[str] = None,
) -> list[onnx.ModelProto]:
"""Load multiple ONNX models or operators and returns them as a list.
Args:
- *args: A variable number of ONNX models (either ONNX ModelProto objects or file paths).
- For Hugging Face-hosted models, use the format 'hf://model_name'. Valid `model_name` can be found on
+ *args: A variable number of ONNX models, each as :meth:`_load_op` takes it: ONNX ModelProto objects, or
+ file paths (``str`` or :class:`os.PathLike`). For Hugging Face-hosted models, use the format
+ 'hf://model_name' (a ``str``). Valid `model_name` can be found on
https://huggingface.co/kornia/ONNX_models. Or a URL to the ONNX model.
cache_dir: Where to read operations from if stored on disk.
@@ -487,37 +628,60 @@ class ONNXMixin:
def _combine(
self,
- *args: list[onnx.ModelProto],
- io_maps: Optional[list[tuple[str, str]]] = None,
+ *args: onnx.ModelProto,
+ io_maps: Optional[list[list[tuple[str, str]]]] = None,
) -> onnx.ModelProto:
"""Combine the provided ONNX models into a single ONNX graph.
- Optionally, map inputs and outputs between operators using the `io_map`.
+ The names in model ``i`` are prefixed with ``K<i>-`` (``K00-``, ``K01-``, ...) in the combined graph. The
+ metadata of the models are merged into one entry per key, which keeps its first position and takes the value
+ of the last model that sets it, as :func:`kornia.onnx.utils.add_metadata` overwrites a key. The models passed
+ in are not modified.
Args:
- args: list of onnx operations.
+ args: The ONNX models, in the order they run.
io_maps:
- A list of list of tuples representing input-output mappings for combining the models.
- Example: [[(model1_output_name, model2_input_name)], [(model2_output_name, model3_input_name)]].
+ One list of ``(output, input)`` name pairs per joint: ``io_maps[i]`` connects outputs of model ``i``
+ to inputs of model ``i + 1``. Example: ``[[(model1_output_name, model2_input_name)],
+ [(model2_output_name, model3_input_name)]]``. Each entry may be any iterable of pairs (a ``zip``,
+ ``dict.items()``, ...), and ``io_maps`` anything indexed by the joint; entries past the last joint are
+ not read. If None, each joint connects ``"output"`` to ``"input"``.
Returns:
onnx.ModelProto: The combined ONNX model as a single ONNX graph.
+ Raises:
+ ValueError: If no model is given.
+ ValueCheckError: If ``io_maps`` has no entry for a joint, or an entry is not an iterable of name pairs.
+ It is a :exc:`ValueError` too.
+
+ Warns:
+ UserWarning: If an output and the input it feeds have different tensor element types. The merged graph
+ does not check a later model's declared input types, so the chain then runs on the earlier model's
+ type, or fails in ONNX Runtime.
+
"""
if len(args) == 0:
raise ValueError("No operators found.")
+ joints = len(args) - 1
+ pairs_per_joint = None if io_maps is None else _io_map_pairs(io_maps, joints, len(args))
- combined_op = args[0]
- combined_op = onnx.compose.add_prefix(combined_op, prefix=f"K{str(0).zfill(2)}-")
+ # merge_models refuses models whose metadata differ for a key, such as the "version" every kornia export
+ # carries. The metadata are merged here instead, and cleared on the prefixed copies that add_prefix returns.
+ metadata = {entry.key: entry.value for op in args for entry in op.metadata_props}
+ combined_op = onnx.compose.add_prefix(args[0], prefix=_prefix(0))
+ del combined_op.metadata_props[:]
for i, op in enumerate(args[1:]):
- next_op = onnx.compose.add_prefix(op, prefix=f"K{str(i + 1).zfill(2)}-")
- if io_maps is None:
- io_map = [(f"K{str(i).zfill(2)}-output", f"K{str(i + 1).zfill(2)}-input")]
- else:
- io_map = [(f"K{str(i).zfill(2)}-{it[0]}", f"K{str(i + 1).zfill(2)}-{it[1]}") for it in io_maps[i]]
+ next_op = onnx.compose.add_prefix(op, prefix=_prefix(i + 1))
+ del next_op.metadata_props[:]
+ pairs = [("output", "input")] if pairs_per_joint is None else pairs_per_joint[i]
+ _warn_on_joint_element_types(combined_op, next_op, pairs, i)
+ io_map = [(f"{_prefix(i)}{output}", f"{_prefix(i + 1)}{input_}") for output, input_ in pairs]
combined_op = onnx.compose.merge_models(combined_op, next_op, io_map=io_map)
+ onnx.helper.set_model_props(combined_op, metadata)
+ _merge_opset_imports(combined_op)
return combined_op
def _export(
@@ -570,11 +734,20 @@ class ONNXMixin:
target_opset_version: The target OPSET version to convert to.
"""
- if op.ir_version != target_ir_version or self._opset_version(op) != target_opset_version:
+ # only the targets given are compared: converting re-checks the model, so one that already has them is kept
+ ir_differs = target_ir_version is not None and op.ir_version != target_ir_version
+ opset_differs = target_opset_version is not None and self._opset_version(op) != target_opset_version
+ if ir_differs or opset_differs:
# Check if all ops are supported in the current IR version
model_bytes = io.BytesIO()
onnx.save_model(op, model_bytes)
loaded_model = onnx.load_model_from_string(model_bytes.getvalue())
+ # check_model rejects duplicate metadata keys, which files that kornia 0.9.0rc1 tagged twice hold: keep one
+ # entry per key with its last value, the one ONNX Runtime reads, as _combine does
+ metadata = {entry.key: entry.value for entry in loaded_model.metadata_props}
+ del loaded_model.metadata_props[:]
+ onnx.helper.set_model_props(loaded_model, metadata)
+ _merge_opset_imports(loaded_model) # a graph combined by an earlier release lists each domain per model
if target_opset_version is not None:
loaded_model = onnx.version_converter.convert_version(loaded_model, target_opset_version)
onnx.checker.check_model(loaded_model)
@@ -586,8 +759,9 @@ class ONNXMixin:
@staticmethod
def _opset_version(op: onnx.ModelProto) -> Optional[int]:
- """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 None
+ """Return the version of the default (``ai.onnx``) operator set that ``op`` imports, or None.
+
+ Of several entries, the last one is returned, the one ``onnx.checker`` and ONNX Runtime read.
+ """
+ versions = [entry.version for entry in op.opset_import if entry.domain in ("", "ai.onnx")]
+ return versions[-1] if versions else None
diff --git a/kornia/core/utils.py b/kornia/core/utils.py
index 9927c6761..a89822dd4 100644
--- a/kornia/core/utils.py
+++ b/kornia/core/utils.py
@@ -19,6 +19,7 @@
import importlib.util
import platform
import sys
+import warnings
from collections.abc import Mapping, Sequence
from contextlib import AbstractContextManager, nullcontext
from dataclasses import asdict, fields, is_dataclass
@@ -731,6 +732,19 @@ def _in_torch_or_kornia(frame: FrameType) -> bool:
return str(frame.f_globals.get("__name__", "")).split(".", 1)[0] in ("torch", "kornia")
+def _warn_at_caller(message: str) -> None:
+ """Warn with a ``UserWarning`` attributed to the first frame outside kornia and torch.
+
+ For a warning raised where no fixed ``stacklevel`` names the user's line: inside a ``forward`` that
+ ``nn.Module.__call__`` reaches through torch frames, or in code that other kornia classes call too.
+ """
+ level = 2 # warnings.warn's stacklevel for the frame that called this function
+ frame: Optional[FrameType] = sys._getframe(1)
+ while frame is not None and _in_torch_or_kornia(frame):
+ frame, level = frame.f_back, level + 1
+ warnings.warn(message, UserWarning, stacklevel=level if frame is not None else 2)
+
+
@torch.jit.unused
def is_compiling() -> bool:
"""Whether execution is inside ``torch.compile`` or ``torch.export`` capture.
diff --git a/kornia/models/_hf_models/hf_onnx_community.py b/kornia/models/_hf_models/hf_onnx_community.py
index 4fa882b20..35d479767 100644
--- a/kornia/models/_hf_models/hf_onnx_community.py
+++ b/kornia/models/_hf_models/hf_onnx_community.py
@@ -147,8 +147,9 @@ class HFONNXComunnityModel(ONNXSequential, ModelBaseMixin):
name: Optional human-readable model name used for export filenames.
auto_ir_version_conversion: Whether to allow automatic ONNX IR version
conversion when composing the sequence.
- io_maps: Optional list of input/output name mappings used when connecting the
- ONNX graphs together.
+ io_maps: Optional list with one list of ``(output, input)`` name pairs per joint between
+ consecutive graphs (pre-processor, model, post-processor, of those given), as for
+ :class:`~kornia.onnx.sequential.ONNXSequential`.
resize: Optional torch module that resizes an image before the ONNX graphs, for a
resize whose output size depends on the input size and so cannot be part of a
graph with dynamic height and width. It is kept as ``self.resize``; the subclass
@@ -165,7 +166,7 @@ class HFONNXComunnityModel(ONNXSequential, ModelBaseMixin):
post_processor: Optional[onnx.ModelProto] = None,
name: Optional[str] = None,
auto_ir_version_conversion: bool = True,
- io_maps: Optional[list[tuple[str, str]]] = None,
+ io_maps: Optional[list[list[tuple[str, str]]]] = None,
resize: Optional[nn.Module] = None,
) -> None:
model_list = [] if pre_processor is None else [pre_processor]
diff --git a/kornia/models/processors/naflex.py b/kornia/models/processors/naflex.py
index 07e984471..fed7d3920 100644
--- a/kornia/models/processors/naflex.py
+++ b/kornia/models/processors/naflex.py
@@ -17,9 +17,6 @@
from __future__ import annotations
import math
-import sys
-import warnings
-from types import FrameType
from typing import Callable, Optional, Union
import torch
@@ -28,7 +25,7 @@ from torch.nn import functional as F
from kornia.core._compat import torch_version_lt
from kornia.core.check import KORNIA_CHECK
-from kornia.core.utils import _in_torch_or_kornia, is_compiling
+from kornia.core.utils import _warn_at_caller, is_compiling
__all__ = ["NaFlex"]
@@ -210,16 +207,3 @@ class NaFlex(nn.Module):
"NaFlex (which also silences this warning), or make the patch embedding return (B, C, h, w)."
)
return side, side
-
-
-def _warn_at_caller(message: str) -> None:
- """Warn with a ``UserWarning`` attributed to the first frame outside kornia and torch.
-
- NaFlex warns from inside its ``forward``, which ``nn.Module.__call__`` reaches through torch frames and which may
- run inside another kornia model, so no fixed ``stacklevel`` names the line that needs ``patch_size``.
- """
- level = 2 # warnings.warn's stacklevel for the frame that called this function
- frame: Optional[FrameType] = sys._getframe(1)
- while frame is not None and _in_torch_or_kornia(frame):
- frame, level = frame.f_back, level + 1
- warnings.warn(message, UserWarning, stacklevel=level if frame is not None else 2)
diff --git a/kornia/onnx/module.py b/kornia/onnx/module.py
index 077bfbabb..55d58265a 100644
--- a/kornia/onnx/module.py
+++ b/kornia/onnx/module.py
@@ -17,6 +17,7 @@
from __future__ import annotations
+import os
from typing import Any, Optional, Union
from kornia.core.external import onnx
@@ -29,8 +30,12 @@ __all__ = ["ONNXModule", "load"]
class ONNXModule(ONNXMixin, ONNXRuntimeMixin):
"""ONNXModule to wrap an ONNX operator.
+ Calling the object runs the graph on numpy arrays or CPU torch tensors of a dtype numpy has (not bfloat16 or
+ float8) and returns a list of numpy arrays; see ``ONNXRuntimeMixin.__call__``.
+
Args:
- arg: A variable number of ONNX models (either ONNX ModelProto objects or file paths).
+ op: One ONNX model: an ONNX ModelProto object, or a file path as ``str`` or :class:`os.PathLike` (a path
+ object always names a local file).
For Hugging Face-hosted models, use the format 'hf://model_name'. Valid `model_name` can be found on
https://huggingface.co/kornia/ONNX_models. Or a URL to the ONNX model.
providers: A list of execution providers for ONNXRuntime
@@ -38,14 +43,14 @@ class ONNXModule(ONNXMixin, ONNXRuntimeMixin):
session_options: Optional ONNXRuntime session options for optimizing the session.
cache_dir: The directory where downloaded ONNX models (``hf://`` names and URLs) are cached locally.
Defaults to None, which will use a default `kornia.config.hub_onnx_dir` directory.
- target_ir_version: The target IR version to convert to.
- target_opset_version: The target OPSET version to convert to.
+ target_ir_version: The IR version to convert the model to. If None, the model keeps its IR version.
+ target_opset_version: The OPSET version to convert the model to. If None, the model keeps its OPSET version.
"""
def __init__(
self,
- op: Union[onnx.ModelProto, str],
+ op: Union[onnx.ModelProto, str, os.PathLike],
providers: Optional[list[str]] = None,
session_options: Optional[ort.SessionOptions] = None,
cache_dir: Optional[str] = None,
@@ -103,14 +108,15 @@ class ONNXModule(ONNXMixin, ONNXRuntimeMixin):
return super()._add_metadata(self.op, additional_metadata)
-def load(model_name: Union[onnx.ModelProto, str]) -> ONNXModule:
+def load(model_name: Union[onnx.ModelProto, str, os.PathLike]) -> ONNXModule:
"""Load an ONNX model from either a file path or HuggingFace.
The loaded model is an ONNXModule object, of which you may run the model with
the `__call__` method, with less boilerplate.
Args:
- model_name: The name of the model to load. For Hugging Face-hosted models,
+ model_name: The name of the model to load: a file path as ``str`` or :class:`os.PathLike` (a path object
+ always names a local file), or an ONNX ModelProto object. For Hugging Face-hosted models,
use the format 'hf://model_name'. Valid `model_name` can be found on
https://huggingface.co/kornia/ONNX_models. Or a URL to the ONNX model.
diff --git a/kornia/onnx/sequential.py b/kornia/onnx/sequential.py
index 48b77b2d8..420215edb 100644
--- a/kornia/onnx/sequential.py
+++ b/kornia/onnx/sequential.py
@@ -17,6 +17,7 @@
from __future__ import annotations
+import os
from typing import Any, Optional, Union
from kornia.core.external import onnx
@@ -29,33 +30,51 @@ __all__ = ["ONNXSequential"]
class ONNXSequential(ONNXMixin, ONNXRuntimeMixin):
"""ONNXSequential to chain multiple ONNX operators together.
+ Calling the object runs the combined graph on numpy arrays or CPU torch tensors of a dtype numpy has (not
+ bfloat16) and returns a list of numpy arrays; see ``ONNXRuntimeMixin.__call__``. The metadata of the models are
+ merged into the combined model with one entry per key: each key keeps its first position and takes the value of
+ the last model that sets it. The models passed in are not modified.
+
Args:
- *args: A variable number of ONNX models (either ONNX ModelProto objects or file paths).
- For Hugging Face-hosted models, use the format 'hf://model_name'. Valid `model_name` can be found on
- https://huggingface.co/kornia/ONNX_models. Or a URL to the ONNX model.
+ *args: A variable number of ONNX models (ONNX ModelProto objects, or file paths as ``str`` or
+ :class:`os.PathLike`; a path object always names a local file). For Hugging Face-hosted models, use the
+ format 'hf://model_name'. Valid `model_name` can be found on https://huggingface.co/kornia/ONNX_models.
+ Or a URL to the ONNX model.
providers: A list of execution providers for ONNXRuntime
(e.g., ['CUDAExecutionProvider', 'CPUExecutionProvider']).
session_options: Optional ONNXRuntime session options for optimizing the session.
- io_maps: An optional list of list of tuples specifying input-output mappings for combining models.
+ io_maps: An optional list with one list of ``(output, input)`` name pairs per joint between consecutive
+ models: ``io_maps[0]`` connects outputs of the first model to inputs of the second, ``io_maps[1]`` the
+ second to the third, and so on, as in ``[[("out_a", "in_b")], [("out_b", "in_c")]]`` for three models.
+ Each entry may be any iterable of pairs (a ``zip``, ``dict.items()``, ...), and ``io_maps`` anything
+ indexed by the joint; entries past the last joint are not read.
If None, we assume the default input name and output name are "input" and "output" accordingly, and
only one input and output node for each graph.
- If not None, `io_maps[0]` shall represent the `io_map` for combining the first and second ONNX models.
+ The merged graph does not check a later model's declared input types: a ``UserWarning`` says so when the
+ tensor element types of an output and the input it feeds differ. Declared dimensions are not compared.
cache_dir: The directory where downloaded ONNX models (``hf://`` names and URLs) are cached locally.
Defaults to None, which will use a default `kornia.config.hub_onnx_dir` directory.
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.
+ target_ir_version: The IR version to convert every model to before combining them, whether or not
+ `auto_ir_version_conversion` is set. If None, the models keep their IR versions, unless
+ `auto_ir_version_conversion` converts them to 9.
+ target_opset_version: The OPSET version to convert every model to before combining them, whether or not
+ `auto_ir_version_conversion` is set. If None, the models keep their OPSET versions, unless
+ `auto_ir_version_conversion` converts them to the highest among them. A conversion that fails raises its
+ error: the ONNX version converter's where it has no adapter for an operator (for example ``Resize`` or
+ ``Pad`` from opset 18 to 17), ``onnx.checker``'s where the converted graph is invalid (for example a
+ ``ReduceMean`` from opset 18 to 17), or ONNX Runtime's where it does not support the target IR version.
"""
def __init__(
self,
- *args: Union[onnx.ModelProto, str],
+ *args: Union[onnx.ModelProto, str, os.PathLike],
providers: Optional[list[str]] = None,
session_options: Optional[ort.SessionOptions] = None,
- io_maps: Optional[list[tuple[str, str]]] = None,
+ io_maps: Optional[list[list[tuple[str, str]]]] = None,
cache_dir: Optional[str] = None,
auto_ir_version_conversion: bool = False,
target_ir_version: Optional[int] = None,
@@ -66,6 +85,14 @@ class ONNXSequential(ONNXMixin, ONNXRuntimeMixin):
self.operators = self._auto_version_conversion(
*self.operators, target_ir_version=target_ir_version, target_opset_version=target_opset_version
)
+ elif target_ir_version is not None or target_opset_version is not None:
+ # as ONNXModule does: only the versions given are changed
+ self.operators = [
+ self._onnx_version_conversion(
+ op, target_ir_version=target_ir_version, target_opset_version=target_opset_version
+ )
+ for op in self.operators
+ ]
self._combined_op = self.combine(io_maps=io_maps)
session = self.create_session(providers=providers, session_options=session_options)
self.set_session(session=session)
@@ -102,18 +129,27 @@ class ONNXSequential(ONNXMixin, ONNXRuntimeMixin):
op_list.append(op)
return op_list
- def combine(self, io_maps: list[tuple[str, str]] | None = None) -> onnx.ModelProto:
+ def combine(self, io_maps: Optional[list[list[tuple[str, str]]]] = None) -> onnx.ModelProto:
"""Combine the stored ONNX operators into one executable graph.
Args:
- io_maps: Optional list of ``(source_output, target_input)`` name
- pairs describing how adjacent graphs should be connected. When
- omitted, the helper assumes the default single input/output
- names used by the ONNX composition utility.
+ io_maps: Optional list with one list of ``(output, input)`` name pairs per joint between consecutive
+ operators: ``io_maps[i]`` connects outputs of ``self.operators[i]`` to inputs of
+ ``self.operators[i + 1]``, as in ``[[("out_a", "in_b")], [("out_b", "in_c")]]`` for three
+ operators. Each entry may be any iterable of pairs; entries past the last joint are not read. When
+ omitted, each joint connects the default ``"output"`` to ``"input"``.
Returns:
Combined ONNX model graph containing all operators in
- ``self.operators`` connected in sequence.
+ ``self.operators`` connected in sequence, with their metadata merged (the last value of each key).
+
+ Raises:
+ ValueCheckError: If ``io_maps`` has no entry for a joint, or an entry is not an iterable of name pairs.
+ It is a :exc:`ValueError` too.
+
+ Warns:
+ UserWarning: If an output and the input it feeds have different tensor element types: the merged graph
+ does not check a later model's declared input types.
"""
return super()._combine(*self.operators, io_maps=io_maps)
diff --git a/kornia/onnx/utils.py b/kornia/onnx/utils.py
index 4d1c40e6e..2eccf6c2d 100644
--- a/kornia/onnx/utils.py
+++ b/kornia/onnx/utils.py
@@ -24,7 +24,7 @@ import os
import posixpath
import pprint
import urllib.error
-from typing import Any, Optional
+from typing import Any, Optional, Union
from urllib.parse import quote, urlsplit, urlunsplit
from urllib.request import urlopen
@@ -93,6 +93,19 @@ def _check_keywords(method: str, kwargs: dict[str, Any]) -> None:
raise TypeError(f"{method}() got an unexpected keyword argument {key!r}")
+def _path_text(method: str, value: Any) -> str:
+ """Return the text of ``value``, a ``str`` or an :class:`os.PathLike` naming a ``str`` path.
+
+ Anything else raises ``TypeError``. ``bytes`` are not a path here: ONNX Runtime reads ``bytes`` as a serialized
+ model, so the message names the call for that.
+ """
+ text = os.fspath(value) if isinstance(value, os.PathLike) else value
+ if isinstance(text, str):
+ return text
+ hint = " For a serialized model, pass onnx.load_model_from_string(data)." if isinstance(text, bytes) else ""
+ raise TypeError(f"{method} takes a str or an os.PathLike, got {type(value).__name__}.{hint}")
+
+
def _onnx_data_name(name: str) -> str:
"""Return the name of the ``.onnx_data`` weights stored beside the model ``name``, with or without ``.onnx``."""
return (name[: -len(".onnx")] if name.endswith(".onnx") else name) + ".onnx_data"
@@ -102,12 +115,15 @@ class ONNXLoader(CachedDownloader):
"""Manages ONNX models, handling local caching, downloading from Hugging Face, and loading models."""
@classmethod
- def load_config(cls, url: str, download: bool = True, **kwargs: Any) -> dict[str, Any]:
- """Load JSON config from the specified URL.
+ def load_config(cls, url: Union[str, os.PathLike], download: bool = True, **kwargs: Any) -> dict[str, Any]:
+ """Load JSON config from the specified URL or local file.
Args:
- url: The URL of the preprocessor config to load.
- download: If True, the config will be downloaded if it's not already in the local cache.
+ url: The HTTP(S) URL of the preprocessor config to load, or the path of a local JSON file, which is read
+ as it is: a ``str``, or an :class:`os.PathLike`, which always names a local file. A local path may
+ start with ``~``.
+ download: If True, the config will be downloaded if it's not already in the local cache. A local file
+ is read either way.
kwargs: Keyword arguments of ``CachedDownloader.download_to_cache``. Only ``cache_dir`` applies: the root
the config is stored under, at ``<scheme>/<host>/<directories of the URL's path>/<file name>``, with a
``%3F<hash>`` directory before the file name when the URL has a query, as for ``load_model``. ``None``
@@ -117,28 +133,41 @@ class ONNXLoader(CachedDownloader):
Returns:
dict[str, Any]: The loaded preprocessor config.
+ Raises:
+ RuntimeError: If ``url`` is neither an HTTP(S) URL nor an existing local file.
+ TypeError: If ``url`` is not a ``str`` or an :class:`os.PathLike`; ``bytes`` raise it too.
+
"""
_check_keywords("ONNXLoader.load_config", kwargs)
- if url.startswith(("http:", "https:")):
+ local = isinstance(url, os.PathLike) # a path object names a local file, whatever its text
+ url = _path_text("ONNXLoader.load_config", url)
+ if not local and url.startswith(("http:", "https:")):
kwargs["cache_dir"] = kwargs.get("cache_dir") or None # "" is the default directory, as for load_model
file_path = cls.download_to_cache(url, _url_cache_name(url), download=download, suffix=".json", **kwargs)
with open(file_path) as f:
return json.load(f)
- if not download:
- raise RuntimeError(f"File `{url}` not found. You may set `download=True`.")
+ path = os.path.expanduser(url)
+ if os.path.isfile(path):
+ with open(path, "rb") as f: # json.load decodes UTF-8, -16 or -32 bytes, whatever the locale
+ return json.load(f)
- raise RuntimeError(f"File `{url}` not found.")
+ raise RuntimeError(
+ f"`{url}` is neither an HTTP(S) URL nor an existing local file: ONNXLoader.load_config reads only those."
+ )
@classmethod
- def load_model(cls, model_name: str, download: bool = True, with_data: bool = False, **kwargs) -> onnx.ModelProto:
+ def load_model(
+ cls, model_name: Union[str, os.PathLike], download: bool = True, with_data: bool = False, **kwargs
+ ) -> onnx.ModelProto:
"""Load an ONNX model from the local cache or downloads it from Hugging Face if necessary.
Args:
model_name: The name of the ONNX model or operator. For Hugging Face-hosted models,
use the format 'hf://model_name'. Valid `model_name` can be found on
https://huggingface.co/kornia/ONNX_models.
- Or a URL to the ONNX model.
+ Or a URL to the ONNX model, or the path of a local file. A ``str`` can be any of those; an
+ :class:`os.PathLike` always names a local file. A local path may start with ``~``.
download: If True, the model will be downloaded from Hugging Face if it's not already in the local cache.
cache_dir: The root of the cache. An ``hf://`` model is stored under it at the path of its name after
the folder (``<cache_dir>/a/b.onnx`` for ``hf://models/a/b``): the kornia/ONNX_models names are fully
@@ -158,9 +187,14 @@ class ONNXLoader(CachedDownloader):
Returns:
onnx.ModelProto: The loaded ONNX model.
+ Raises:
+ TypeError: If ``model_name`` is not a ``str`` or an :class:`os.PathLike`; ``bytes`` raise it too.
+
"""
_check_keywords("ONNXLoader.load_model", kwargs)
- if model_name.startswith("hf://"):
+ local = isinstance(model_name, os.PathLike) # a path object names a local file, whatever its text
+ model_name = _path_text("ONNXLoader.load_model", model_name)
+ if not local and model_name.startswith("hf://"):
model_name = model_name[len("hf://") :]
url = f"https://huggingface.co/kornia/ONNX_models/resolve/main/{model_name}.onnx"
if kwargs.get("cache_dir"):
@@ -174,7 +208,7 @@ class ONNXLoader(CachedDownloader):
cls.download_to_cache(url_data, name, download=download, suffix=".onnx_data", **kwargs)
return onnx.load(file_path)
- if model_name.startswith(("http://", "https://")):
+ if not local and model_name.startswith(("http://", "https://")):
name = _url_cache_name(model_name)
kwargs["cache_dir"] = kwargs.get("cache_dir") or kornia_config.hub_onnx_dir # "" is the default too
file_path = cls.download_to_cache(model_name, name, download=download, suffix=".onnx", **kwargs)
@@ -184,8 +218,9 @@ class ONNXLoader(CachedDownloader):
cls.download_to_cache(url_data, _onnx_data_name(name), download=download, suffix=".onnx_data", **kwargs)
return onnx.load(file_path)
- if os.path.exists(model_name):
- return onnx.load(model_name)
+ path = os.path.expanduser(model_name)
+ if os.path.exists(path):
+ return onnx.load(path)
raise ValueError(f"File {model_name} not found")
@@ -231,12 +266,21 @@ def io_name_conversion(
onnx_model: onnx.ModelProto,
io_name_mapping: dict[str, str],
) -> onnx.ModelProto:
- """Convert the input and output names of an ONNX model to 'input' and 'output'.
+ """Rename the inputs and outputs of an ONNX model in place, as ``io_name_mapping`` maps them.
+
+ Any mapping applies, such as ``{"pixel_values": "input", "predicted_depth": "output"}`` for the default names that
+ :class:`~kornia.onnx.sequential.ONNXSequential` connects. The graph's inputs and outputs and every input and
+ output of its nodes with a mapped name are renamed; names absent from the model are ignored. The initializers,
+ the ``value_info`` entries and the nodes of subgraphs (the branches of an ``If``, the body of a ``Loop``) are not
+ renamed, so a mapped name that is also an initializer leaves its consumers reading a name that no longer exists.
Args:
- onnx_model: The ONNX model to convert.
+ onnx_model: The ONNX model to rename, modified in place.
io_name_mapping: A dictionary mapping the original input and output names to the new ones.
+ Returns:
+ The same ``onnx_model`` object, renamed.
+
"""
# Convert I/O nodes
for i in range(len(onnx_model.graph.input)):
diff --git a/tests/core/test_onnx_mixin.py b/tests/core/test_onnx_mixin.py
index dc97682cf..347d48178 100644
--- a/tests/core/test_onnx_mixin.py
+++ b/tests/core/test_onnx_mixin.py
@@ -344,6 +344,66 @@ class TestONNXRuntimeMixin(BaseTester):
assert runtime(b, a)[0].tolist() == [97.0]
with pytest.raises(ValueError, match="Expected 2 ONNX inputs, got 3"):
runtime(a, b, a)
+ # torch tensors on the CPU and numpy arrays mix
+ assert runtime(torch.tensor([2.0]), b)[0].tolist() == [-97.0]
+
+ def test_runtime_takes_cpu_torch_tensors(self, op):
+ import numpy as np
+
+ from kornia.onnx import ONNXModule, ONNXSequential
+
+ x = torch.rand(2, 3, 5, 4)
+ inputs = [
+ x,
+ x.clone().requires_grad_(True),
+ torch.rand(2, 3, 4, 5).transpose(-1, -2), # not contiguous
+ ]
+ for runtime in (ONNXSequential(op), ONNXModule(op)):
+ for value in inputs:
+ (out,) = runtime(value)
+ assert isinstance(out, np.ndarray)
+ assert out.tolist() == runtime(np.ascontiguousarray(value.detach().numpy()))[0].tolist()
+ self.assert_close(torch.from_numpy(out), value.detach().sigmoid())
+
+ def test_runtime_rejects_tensors_off_the_cpu(self, op):
+ from kornia.onnx import ONNXModule, ONNXSequential
+
+ x = torch.empty(1, 3, 4, 5, device="meta")
+ for runtime in (ONNXSequential(op), ONNXModule(op)):
+ with pytest.raises(ValueError, match=r"input 0 is a torch tensor on meta.*Move it to the CPU"):
+ runtime(x)
+
+ @pytest.fixture
+ def subtract(self):
+ from kornia.onnx import ONNXModule
+
+ def _value(name):
+ return onnx.helper.make_tensor_value_info(name, onnx.TensorProto.FLOAT, [2])
+
+ node = onnx.helper.make_node("Sub", ["x", "y"], ["output"])
+ graph = onnx.helper.make_graph([node], "sub", [_value("x"), _value("y")], [_value("output")])
+ return ONNXModule(onnx.helper.make_model(graph, opset_imports=[onnx.helper.make_opsetid("", 17)], ir_version=9))
+
+ def test_runtime_names_the_input_off_the_cpu(self, subtract):
+ with pytest.raises(ValueError, match=r"ONNX input 1 is a torch tensor on meta"):
+ subtract(torch.tensor([3.0, 1.0]), torch.empty(2, device="meta"))
+
+ @pytest.mark.parametrize("dtype_numpy_lacks", [torch.bfloat16, torch.float8_e4m3fn])
+ def test_runtime_rejects_tensors_of_a_dtype_numpy_lacks_naming_the_input(self, subtract, dtype_numpy_lacks):
+ a = torch.tensor([3.0, 1.0])
+ with pytest.raises(TypeError, match=rf"ONNX input 1 is a {dtype_numpy_lacks} tensor, a dtype numpy has no"):
+ subtract(a.numpy(), a.to(dtype_numpy_lacks))
+
+ def test_runtime_rejects_sparse_tensors_naming_the_input(self, subtract):
+ a = torch.tensor([3.0, 0.0])
+ with pytest.raises(TypeError, match=r"ONNX input 0 is a torch.sparse_coo tensor.*\.to_dense\(\)"):
+ subtract(a.to_sparse(), a)
+
+ def test_runtime_reads_a_negative_bit_view(self, subtract):
+ # .conj().imag returns a view with the negative bit set, which .numpy() refuses: [3, 1] - [-2, 1]
+ negative_view = torch.tensor([1 + 2j, 3 - 1j]).conj().imag
+ assert negative_view.is_neg()
+ assert subtract(torch.tensor([3.0, 1.0]), negative_view)[0].tolist() == [5.0, 0.0]
def test_add_metadata_overwrites_existing_keys(self, op):
keys = [prop.key for prop in op.metadata_props]
diff --git a/tests/models/test_hf_onnx_community.py b/tests/models/test_hf_onnx_community.py
index e8b6a71bc..9bd8b807a 100644
--- a/tests/models/test_hf_onnx_community.py
+++ b/tests/models/test_hf_onnx_community.py
@@ -68,6 +68,25 @@ def test_to_onnx_keeps_one_metadata_entry_per_key(include_pre_and_post_processor
onnx.checker.check_model(exported)
+def test_model_with_its_own_source_chains_with_a_kornia_pre_processor():
+ # #6117: the model's "source" differs from the one kornia writes into the pre-processor, which merge_models
+ # refused: "Can't merge models with different values for the same model metadata property".
+ import numpy as np
+
+ model = _identity_model(("source", "optimum"))
+ pre_processor = _identity_model(("source", "kornia"), ("version", kornia.__version__))
+
+ hf_model = HFONNXComunnityModel(model, pre_processor=pre_processor)
+
+ assert hf_model(np.array([3.0], dtype=np.float32))[0].tolist() == [3.0]
+ # the later model's value wins; the caller's graphs keep their own
+ assert [(prop.key, prop.value) for prop in hf_model._combined_op.metadata_props] == [
+ ("source", "optimum"),
+ ("version", kornia.__version__),
+ ]
+ assert [(prop.key, prop.value) for prop in model.metadata_props] == [("source", "optimum")]
+
+
@pytest.mark.parametrize("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
diff --git a/tests/onnx/test_module.py b/tests/onnx/test_module.py
new file mode 100644
index 000000000..23bb7f7e0
--- /dev/null
+++ b/tests/onnx/test_module.py
@@ -0,0 +1,107 @@
+# 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.
+#
+
+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
+
+onnx = pytest.importorskip("onnx")
+pytest.importorskip("onnxruntime")
+if torch_version_ge(2, 9, 0):
+ pytest.importorskip("onnxscript") # the dynamo exporter, the default from torch 2.9
+
+from kornia.core import ImageSequential # noqa: E402
+from kornia.onnx import ONNXModule, ONNXSequential, load # noqa: E402
+
+_RGB = {"input_shape": [-1, 3, -1, -1], "output_shape": [-1, 3, -1, -1]}
+
+
+def _opsets(op):
+ return {entry.version for entry in op.opset_import if entry.domain in ("", "ai.onnx")}
+
+
+def sigmoid():
+ return ImageSequential(torch.nn.Sigmoid())
+
+
+def op(sigmoid):
+ return sigmoid.to_onnx(save=False, **_RGB)
+
+
+class TestONNXModule:
+ @pytest.mark.parametrize(
+ ("targets", "expected"),
+ [
+ ({"target_ir_version": 9}, ({18}, 9)),
+ ({"target_opset_version": 17}, ({17}, None)), # None: the IR version of the export
+ ({"target_ir_version": 9, "target_opset_version": 17}, ({17}, 9)),
+ ],
+ )
+ def test_target_versions(self, sigmoid, op, targets, expected):
+ # IR 10 from the dynamo exporter, 8 from the legacy one (the default before torch 2.9): 9 converts both
+ versions = (_opsets(op), op.ir_version)
+ assert versions[0] == {18}
+ assert versions[1] != 9
+ opsets, ir_version = expected
+ if ir_version is None:
+ ir_version = op.ir_version
+
+ module = ONNXModule(op, **targets)
+
+ assert (_opsets(module.op), module.op.ir_version) == (opsets, ir_version)
+ assert (_opsets(op), op.ir_version) == versions # the caller's graph is converted on a copy
+ x = torch.rand(2, 3, 4, 5)
+ assert_close(torch.from_numpy(module(x.numpy())[0]), sigmoid(x))
+
+ @pytest.mark.parametrize("form", ["Path", "~"])
+ def test_takes_file_paths_as_path_objects_and_with_a_tilde(self, sigmoid, form, monkeypatch, tmp_path):
+ import os
+
+ path = tmp_path / "sigmoid.onnx"
+ sigmoid.to_onnx(str(path), **_RGB)
+ monkeypatch.setenv("HOME", str(tmp_path))
+ monkeypatch.setenv("USERPROFILE", str(tmp_path)) # what os.path.expanduser reads on Windows
+ model = {"Path": path, "~": os.path.join("~", "sigmoid.onnx")}[form]
+
+ x = torch.rand(1, 3, 4, 5)
+ for runtime in (ONNXModule(model), load(model), ONNXSequential(model)):
+ assert_close(torch.from_numpy(runtime(x.numpy())[0]), sigmoid(x))
+
+ def test_bytes_raise_type_error_naming_load_model_from_string(self, sigmoid, tmp_path):
+ # ONNX Runtime reads bytes as a serialized model; kornia does not take them as a path either
+ path = tmp_path / "sigmoid.onnx"
+ sigmoid.to_onnx(str(path), **_RGB)
+ for model in (path.read_bytes(), bytes(path)):
+ for runtime in (ONNXModule, load, ONNXSequential):
+ with pytest.raises(TypeError, match=r"got bytes\. For a serialized model, pass onnx\.load_model_from"):
+ runtime(model)
+
+ @pytest.mark.parametrize("model", [1, None, {"model": "m.onnx"}])
+ def test_other_argument_types_raise_type_error(self, model):
+ message = r"an onnx.ModelProto, a str \(a file path, an 'hf://' name or a URL\), or an os.PathLike file"
+ with pytest.raises(TypeError, match=message):
+ ONNXModule(model)
+ with pytest.raises(TypeError, match=message):
+ ONNXSequential(model)
diff --git a/tests/onnx/test_sequential.py b/tests/onnx/test_sequential.py
index d0bc18f6d..7b429927d 100644
--- a/tests/onnx/test_sequential.py
+++ b/tests/onnx/test_sequential.py
@@ -161,3 +161,431 @@ class TestONNXSequentialOfKorniaExports:
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())
+
+ @pytest.mark.parametrize("auto_ir_version_conversion", [False, True])
+ def test_chains_exports_from_another_kornia_release(self, auto_ir_version_conversion):
+ # #6117: every to_onnx export carries kornia's "version", so a graph exported by another release refused to
+ # chain: "Can't merge models with different values for the same model metadata property".
+ from kornia.core import ImageSequential
+ from kornia.onnx import add_metadata
+
+ sigmoid, tanh = ImageSequential(torch.nn.Sigmoid()), ImageSequential(torch.nn.Tanh())
+ fresh = sigmoid.to_onnx(save=False, **_RGB)
+ older = add_metadata(tanh.to_onnx(save=False, **_RGB), [("version", "0.8.1")])
+
+ seq = ONNXSequential(fresh, older, auto_ir_version_conversion=auto_ir_version_conversion)
+
+ x = torch.rand(2, 3, 5, 7)
+ assert_close(torch.from_numpy(seq(x.numpy())[0]), tanh(sigmoid(x)))
+ assert _props(seq._combined_op) == [("source", "kornia"), ("version", "0.8.1")]
+
+ def test_chains_exports_with_different_additional_metadata(self):
+ from kornia.core import ImageSequential
+
+ sigmoid, tanh = ImageSequential(torch.nn.Sigmoid()), ImageSequential(torch.nn.Tanh())
+ a = sigmoid.to_onnx(save=False, additional_metadata=[("name", "sigmoid")], **_RGB)
+ b = tanh.to_onnx(save=False, additional_metadata=[("name", "tanh")], **_RGB)
+
+ seq = ONNXSequential(a, b)
+
+ x = torch.rand(1, 3, 4, 6)
+ assert_close(torch.from_numpy(seq(x.numpy())[0]), tanh(sigmoid(x)))
+ assert dict(_props(seq._combined_op))["name"] == "tanh"
+ assert dict(_props(a))["name"] == "sigmoid" # the caller's graphs keep their own metadata
+
+ @pytest.mark.parametrize("auto_ir_version_conversion", [False, True])
+ def test_target_versions_are_applied_without_the_conversion_flag(self, auto_ir_version_conversion):
+ # #6118: target_opset_version / target_ir_version were read only with auto_ir_version_conversion=True.
+ from kornia.core import ImageSequential
+
+ sigmoid = ImageSequential(torch.nn.Sigmoid())
+ op = sigmoid.to_onnx(save=False, **_RGB)
+ # IR 10 from the dynamo exporter, 8 from the legacy one (the default before torch 2.9): 9 converts both
+ versions = (_opsets(op), op.ir_version)
+ assert versions[0] == {18}
+ assert versions[1] != 9
+
+ seq = ONNXSequential(
+ op,
+ op,
+ target_opset_version=17,
+ target_ir_version=9,
+ auto_ir_version_conversion=auto_ir_version_conversion,
+ )
+
+ for graph in [*seq.operators, seq._combined_op]:
+ assert (_opsets(graph), graph.ir_version) == ({17}, 9)
+ assert (_opsets(op), op.ir_version) == versions # the caller's graph is converted on a copy
+ x = torch.rand(2, 3, 4, 5)
+ assert_close(torch.from_numpy(seq(x.numpy())[0]), sigmoid(sigmoid(x)))
+
+ def test_one_target_version_without_the_flag_keeps_the_other(self):
+ # as ONNXModule does: without auto_ir_version_conversion, only the versions given are changed
+ from kornia.core import ImageSequential
+
+ op = ImageSequential(torch.nn.Sigmoid()).to_onnx(save=False, **_RGB)
+ assert op.ir_version != 9 # 10 from the dynamo exporter, 8 from the legacy one
+
+ ir_only = ONNXSequential(op, op, target_ir_version=9)._combined_op
+ opset_only = ONNXSequential(op, op, target_opset_version=17)._combined_op
+
+ assert (_opsets(ir_only), ir_only.ir_version) == ({18}, 9)
+ assert (_opsets(opset_only), opset_only.ir_version) == ({17}, op.ir_version)
+
+ def test_takes_file_paths_as_path_objects(self, tmp_path):
+ from kornia.core import ImageSequential
+
+ sigmoid = ImageSequential(torch.nn.Sigmoid())
+ path = tmp_path / "sigmoid.onnx"
+ sigmoid.to_onnx(str(path), **_RGB)
+
+ seq = ONNXSequential(path, path)
+
+ x = torch.rand(1, 3, 4, 5)
+ assert_close(torch.from_numpy(seq(x.numpy())[0]), sigmoid(sigmoid(x)))
+
+
+_RGB = {"input_shape": [-1, 3, -1, -1], "output_shape": [-1, 3, -1, -1]}
+
+
+def _props(op):
+ return [(prop.key, prop.value) for prop in op.metadata_props]
+
+
+def _vector(name, elem_type=None):
+ from onnx.helper import make_tensor_value_info
+
+ return make_tensor_value_info(name, onnx.TensorProto.FLOAT if elem_type is None else elem_type, [2])
+
+
+def _untyped(name):
+ value = onnx.ValueInfoProto()
+ value.name = name
+ return value
+
+
+def _model(nodes, inputs, outputs, initializers=(), metadata=()):
+ from onnx.helper import make_graph, make_model, make_opsetid
+
+ graph = make_graph(nodes, "g", inputs, outputs, initializer=list(initializers))
+ model = make_model(graph, opset_imports=[make_opsetid("", 18)], ir_version=9)
+ for key, value in metadata:
+ model.metadata_props.add(key=key, value=value)
+ return model
+
+
+def _identity(*metadata, elem_type=None, input_type=None, output_type=None):
+ from onnx.helper import make_node
+
+ return _model(
+ [make_node("Identity", ["input"], ["output"])],
+ [_vector("input", elem_type if input_type is None else input_type)],
+ [_vector("output", elem_type if output_type is None else output_type)],
+ metadata=metadata,
+ )
+
+
+def _joint_types_that_are_not_compared():
+ """Joints whose output or input carries no tensor element type to compare, as main merged them."""
+ from onnx.helper import make_node, make_optional_type_proto, make_tensor_type_proto, make_value_info
+ from onnx.helper import make_tensor_sequence_value_info as sequence
+ from onnx.numpy_helper import from_array
+
+ undefined = onnx.TensorProto.UNDEFINED
+ index = from_array(torch.tensor(0).numpy(), "index")
+ sequence_out = _model(
+ [make_node("SequenceConstruct", ["input"], ["output"])],
+ [_vector("input")],
+ [sequence("output", onnx.TensorProto.FLOAT, [2])],
+ )
+ sequence_in = _model(
+ [make_node("SequenceAt", ["input", "index"], ["output"])],
+ [sequence("input", onnx.TensorProto.FLOAT, [2])],
+ [_vector("output")],
+ initializers=[index],
+ )
+ optional = make_optional_type_proto(make_tensor_type_proto(onnx.TensorProto.FLOAT, [2]))
+ optional_out = _model(
+ [make_node("Optional", ["input"], ["output"])], [_vector("input")], [make_value_info("output", optional)]
+ )
+ optional_in = _model(
+ [make_node("OptionalGetElement", ["input"], ["output"])],
+ [make_value_info("input", optional)],
+ [_vector("output")],
+ )
+ identity = make_node("Identity", ["input"], ["output"])
+ return {
+ "untyped output": (_model([identity], [_vector("input")], [_untyped("output")]), _identity()),
+ "untyped input": (_identity(), _model([identity], [_untyped("input")], [_vector("output")])),
+ "UNDEFINED output": (_identity(output_type=undefined), _identity()),
+ "UNDEFINED input": (_identity(), _identity(input_type=undefined)),
+ "sequence": (sequence_out, sequence_in),
+ "optional": (optional_out, optional_in),
+ }
+
+
+class TestONNXSequentialComposition:
+ """Real merges of hand-built graphs: names, metadata and the checks at each joint."""
+
+ @pytest.fixture(autouse=True)
+ def _runtime(self):
+ pytest.importorskip("onnxruntime")
+
+ @pytest.fixture
+ def three_graphs(self):
+ from onnx.helper import make_node
+ from onnx.numpy_helper import from_array
+
+ two = from_array(torch.tensor([2.0, 2.0]).numpy(), "two")
+ first = _model(
+ [make_node("Neg", ["x"], ["neg"]), make_node("Abs", ["x"], ["abs"])],
+ [_vector("x")],
+ [_vector("neg"), _vector("abs")],
+ )
+ second = _model([make_node("Sub", ["p", "q"], ["diff"])], [_vector("p"), _vector("q")], [_vector("diff")])
+ third = _model([make_node("Mul", ["d", "two"], ["y"])], [_vector("d")], [_vector("y")], initializers=[two])
+ return first, second, third
+
+ @pytest.mark.parametrize(
+ ("joint", "expected"),
+ [([("neg", "p"), ("abs", "q")], [-4.0, 0.0]), ([("neg", "q"), ("abs", "p")], [4.0, 0.0])],
+ )
+ def test_io_maps_connect_three_graphs(self, three_graphs, joint, expected):
+ # 2 * (p - q) of neg(x) and abs(x): the pairs of each joint decide which output feeds which input.
+ before = [graph.SerializeToString() for graph in three_graphs]
+
+ seq = ONNXSequential(*three_graphs, io_maps=[joint, [("diff", "d")]])
+
+ assert seq(torch.tensor([1.0, -2.0]).numpy())[0].tolist() == expected
+ assert [value.name for value in seq._combined_op.graph.input] == ["K00-x"]
+ assert [value.name for value in seq._combined_op.graph.output] == ["K02-y"]
+ assert [graph.SerializeToString() for graph in three_graphs] == before
+
+ @pytest.mark.parametrize("auto_ir_version_conversion", [False, True])
+ def test_metadata_are_merged_with_the_later_value_of_each_key(self, auto_ir_version_conversion):
+ # every pair of models disagrees on a key, the second and third one too
+ graphs = [
+ _identity(("a", "1"), ("b", "2")),
+ _identity(("b", "3"), ("c", "4")),
+ _identity(("a", "5"), ("c", "6")),
+ ]
+ before = [graph.SerializeToString() for graph in graphs]
+
+ seq = ONNXSequential(*graphs, auto_ir_version_conversion=auto_ir_version_conversion)
+
+ # each key keeps its first position and takes its last value, as add_metadata writes them
+ assert _props(seq._combined_op) == [("a", "5"), ("b", "3"), ("c", "6")]
+ assert [graph.SerializeToString() for graph in graphs] == before
+ onnx.checker.check_model(seq._combined_op)
+ assert seq(torch.tensor([1.0, 2.0]).numpy())[0].tolist() == [1.0, 2.0]
+
+ def test_element_type_mismatch_at_a_joint_warns_and_the_chain_runs(self):
+ # The merged graph drops the later model's declared input, so ONNX Runtime no longer checks its type. A model
+ # whose first node takes any type (a Cast here) runs as it did on main, with the same result: [2.25, 5.0625].
+ from onnx.helper import make_node
+
+ casts_first = _model(
+ [make_node("Cast", ["input"], ["c"], to=onnx.TensorProto.FLOAT), make_node("Mul", ["c", "c"], ["output"])],
+ [_vector("input", onnx.TensorProto.DOUBLE)],
+ [_vector("output")],
+ )
+ message = (
+ r"output 'output' of model 0 is FLOAT.*input 'input' of model 1, which is DOUBLE.*tensor element types"
+ )
+
+ with pytest.warns(UserWarning, match=message) as record:
+ seq = ONNXSequential(_identity(), casts_first)
+
+ assert [w.filename for w in record if "tensor element types" in str(w.message)] == [__file__]
+ assert seq(torch.tensor([1.5, -2.25]).numpy())[0].tolist() == [2.25, 5.0625]
+
+ def test_element_type_mismatch_at_a_later_joint_warns(self):
+ # main and this branch both fail in ONNX Runtime afterwards: the Identity's declared output is DOUBLE
+ message = r"output 'output' of model 1 is FLOAT.*input 'input' of model 2, which is DOUBLE"
+
+ with pytest.warns(UserWarning, match=message), pytest.raises(Exception, match="Type Error"):
+ ONNXSequential(_identity(), _identity(), _identity(elem_type=onnx.TensorProto.DOUBLE))
+
+ def test_element_types_are_compared_through_io_maps(self, three_graphs):
+ from onnx.helper import make_node
+
+ first, _, third = three_graphs
+ second = _model(
+ [make_node("Cast", ["p"], ["diff"], to=onnx.TensorProto.FLOAT)],
+ [_vector("p", onnx.TensorProto.INT64)],
+ [_vector("diff")],
+ )
+ with pytest.warns(UserWarning, match=r"output 'abs' of model 0 is FLOAT.*input 'p' of model 1, which is INT64"):
+ seq = ONNXSequential(first, second, third, io_maps=[[("abs", "p")], [("diff", "d")]])
+
+ # the unconnected neg(x), then 2 * abs(x), as main computed them
+ assert [out.tolist() for out in seq(torch.tensor([1.0, -2.0]).numpy())] == [[-1.0, 2.0], [2.0, 4.0]]
+
+ @pytest.mark.parametrize("joint", list(_joint_types_that_are_not_compared()))
+ def test_joints_without_two_tensor_element_types_do_not_warn(self, joint):
+ import contextlib
+ import warnings
+
+ models = _joint_types_that_are_not_compared()[joint]
+ # ONNX Runtime refuses a graph with an UNDEFINED type, on main as on this branch
+ refused = None
+ if joint == "UNDEFINED output":
+ refused = pytest.raises(Exception, match="Invalid tensor data type 0")
+ with warnings.catch_warnings(record=True) as record, refused or contextlib.nullcontext():
+ warnings.simplefilter("always")
+ seq = ONNXSequential(*models)
+
+ assert not [w for w in record if "tensor element types" in str(w.message)]
+ if refused is None:
+ assert seq(torch.tensor([1.5, -2.25]).numpy())[0].tolist() == [1.5, -2.25]
+
+ @pytest.mark.parametrize(
+ ("models", "io_maps"),
+ [
+ (2, [("output", "input")]), # the pairs of the only joint, not wrapped in a list
+ (2, [("o1", "i1")]), # the same with two-character names, which have a length of 2 like a pair
+ (3, [("output", "input"), ("output", "input")]), # one pair per joint instead of one list per joint
+ (2, ["output"]),
+ (2, [b"output"]),
+ (2, [None]),
+ (2, [[None]]),
+ (2, [[("output",)]]),
+ (2, [[("output", "input", "input")]]), # extra names used to be ignored
+ (2, [["output", "input"]]),
+ ],
+ )
+ def test_malformed_io_maps_raise_a_corrective_message(self, models, io_maps):
+ from kornia.core.exceptions import ValueCheckError
+
+ # a ValueError, as the merge's own "Output K00-o is not present in g1" was for the flat form
+ with pytest.raises(ValueCheckError, match=r"io_maps\[0\] must be a list of \(output, input\) name pairs"):
+ ONNXSequential(*[_identity() for _ in range(models)], io_maps=io_maps)
+
+ @pytest.mark.parametrize("io_maps", [[[("output", "input")]], {0: [("output", "input")]}], ids=["list", "dict"])
+ def test_io_maps_without_an_entry_for_every_joint_raise(self, io_maps):
+ from kornia.core.exceptions import ValueCheckError
+
+ message = r"one list of \(output, input\) name pairs per joint, 2 for 3 models, and has no entry for joint 1"
+ with pytest.raises(ValueCheckError, match=message):
+ ONNXSequential(_identity(), _identity(), _identity(), io_maps=io_maps)
+
+ def test_io_maps_entries_past_the_last_joint_are_not_used(self):
+ # they were never read, and a chain built with them stays as it was
+ seq = ONNXSequential(_identity(), _identity(), io_maps=[[["output", "input"]], None])
+
+ assert seq(torch.tensor([1.0, 2.0]).numpy())[0].tolist() == [1.0, 2.0]
+
+ @pytest.mark.parametrize(
+ "form",
+ ["zip", "set", "items", "generator", "ndarray", "ndarray entry", "keyed by joint"],
+ )
+ def test_io_maps_entries_of_any_iterable_of_pairs_keep_working(self, form):
+ # main indexed io_maps[i] and iterated the entry, so each of these ran: 2-output model -> Sub -> [-2.0, 0.0]
+ import numpy as np
+ from onnx.helper import make_node
+
+ first = _model(
+ [make_node("Neg", ["x"], ["o0"]), make_node("Abs", ["x"], ["o1"])],
+ [_vector("x")],
+ [_vector("o0"), _vector("o1")],
+ )
+ second = _model([make_node("Sub", ["i0", "i1"], ["y"])], [_vector("i0"), _vector("i1")], [_vector("y")])
+ outputs, inputs = ["o0", "o1"], ["i0", "i1"]
+ io_maps = {
+ "zip": lambda: [zip(outputs, inputs)],
+ "set": lambda: [{("o0", "i0"), ("o1", "i1")}],
+ "items": lambda: [dict(zip(outputs, inputs)).items()],
+ "generator": lambda: [((o, i) for o, i in zip(outputs, inputs))],
+ "ndarray": lambda: np.array([list(zip(outputs, inputs))]),
+ "ndarray entry": lambda: [np.array(list(zip(outputs, inputs)))],
+ "keyed by joint": lambda: {0: list(zip(outputs, inputs))},
+ }[form]()
+
+ seq = ONNXSequential(first, second, io_maps=io_maps)
+
+ assert seq(torch.tensor([1.0, -2.0]).numpy())[0].tolist() == [-2.0, 0.0]
+
+ def test_targets_without_a_converter_adapter_raise_the_converters_error(self):
+ # Breaking: main ignored target_opset_version here and returned the opset-18 graph, which ran.
+ import numpy as np
+ from onnx.helper import make_node
+ from onnx.numpy_helper import from_array
+
+ scales = from_array(np.array([1.0, 1.0, 2.0, 2.0], dtype=np.float32), "scales")
+ resize = _model(
+ [make_node("Resize", ["input", "", "scales"], ["output"], mode="linear")],
+ [_vector("input")],
+ [_vector("output")],
+ initializers=[scales],
+ )
+ for value in (*resize.graph.input, *resize.graph.output):
+ value.type.tensor_type.ClearField("shape") # any rank
+
+ assert ONNXSequential(resize)(np.ones((1, 1, 2, 2), dtype=np.float32))[0].shape == (1, 1, 4, 4)
+ with pytest.raises(RuntimeError, match=r"No Adapter To Version \$17 for Resize"):
+ ONNXSequential(resize, target_opset_version=17)
+
+ @pytest.mark.parametrize(
+ "kwargs",
+ [
+ {"target_opset_version": 19},
+ {"target_ir_version": 8},
+ {"auto_ir_version_conversion": True, "target_ir_version": 8},
+ ],
+ ids=["opset", "ir", "flag"],
+ )
+ def test_a_model_with_duplicate_metadata_keys_converts(self, kwargs):
+ # kornia 0.9.0rc1's add_metadata appended every key, so a file it wrote after ONNXSequential.add_metadata or
+ # ONNXModule.add_metadata holds "source" and "version" twice. The conversion re-checks the model, and
+ # onnx.checker.check_model rejects duplicate keys: they are merged first.
+ model = _identity(("source", "kornia"), ("version", "0.9.0rc1"), ("source", "kornia"), ("version", "0.9.0rc1"))
+
+ seq = ONNXSequential(model, **kwargs)
+
+ assert seq(torch.tensor([1.0, 2.0]).numpy())[0].tolist() == [1.0, 2.0]
+ assert _props(seq._combined_op) == [("source", "kornia"), ("version", "0.9.0rc1")]
+ assert len(model.metadata_props) == 4 # the caller's model is not modified
+
+ def test_a_combined_graph_converts_and_chains_again(self, tmp_path):
+ # merge_models lists each domain once per model, and the version converter updates only one of those entries,
+ # so a combined graph, once converted, did not merge with a model of the target version.
+ path = tmp_path / "combined.onnx"
+ ONNXSequential(_identity(), _identity()).export(str(path))
+ later = _identity()
+ later.opset_import[0].version = 19
+
+ seq = ONNXSequential(path, later, io_maps=[[("K01-output", "input")]], target_opset_version=19)
+
+ assert seq(torch.tensor([1.0, 2.0]).numpy())[0].tolist() == [1.0, 2.0]
+ assert [(entry.domain, entry.version) for entry in seq._combined_op.opset_import] == [("", 19)]
+
+ @pytest.mark.parametrize("target_opset_version", [None, 17])
+ def test_disagreeing_opset_entries_keep_the_last_version(self, target_opset_version):
+ # The checker and ONNX Runtime accept two versions of one domain and read the last one, so these opset 18 nodes
+ # run as on main; the target is compared with that version too, and the graph is converted down from it.
+ from onnx.helper import make_node, make_opsetid, make_tensor, make_tensor_value_info
+
+ model = _model(
+ [make_node("ReduceMean", ["input", "axes"], ["output"], keepdims=0)], # axes is an input from opset 18
+ [_vector("input")],
+ [make_tensor_value_info("output", onnx.TensorProto.FLOAT, [])],
+ initializers=[make_tensor("axes", onnx.TensorProto.INT64, [1], [0])],
+ )
+ del model.opset_import[:]
+ model.opset_import.extend([make_opsetid("", 17), make_opsetid("", 18)])
+
+ seq = ONNXSequential(model, target_opset_version=target_opset_version)
+
+ assert seq(torch.tensor([1.0, 2.0]).numpy())[0].tolist() == 1.5
+ expected = 18 if target_opset_version is None else target_opset_version
+ assert [(entry.domain, entry.version) for entry in seq._combined_op.opset_import] == [("", expected)]
+
+ def test_a_target_the_model_already_has_is_not_converted_again(self):
+ # Converting re-checks the model, which rejects the duplicate metadata keys earlier kornia versions wrote;
+ # an IR 9 model with target_ir_version=9 runs as on main, with its metadata merged into one entry per key.
+ model = _identity(("k", "1"), ("k", "2"))
+
+ seq = ONNXSequential(model, target_ir_version=9)
+
+ assert seq(torch.tensor([1.0, 2.0]).numpy())[0].tolist() == [1.0, 2.0]
+ assert _props(seq._combined_op) == [("k", "2")]
diff --git a/tests/onnx/test_utils.py b/tests/onnx/test_utils.py
index 23fc9db8a..f2c6c9ef4 100644
--- a/tests/onnx/test_utils.py
+++ b/tests/onnx/test_utils.py
@@ -393,6 +393,93 @@ class TestONNXLoader:
"hub/https/b.invalid/preprocessor_config.json",
]
+ @pytest.mark.parametrize("form", ["str", "Path", "~"])
+ @pytest.mark.parametrize("download", [True, False])
+ def test_load_config_reads_a_local_file(self, download, form, monkeypatch, tmp_path):
+ # #6119: an existing local file was reported "not found", with "You may set `download=True`"
+ import json
+ from unittest import mock
+
+ # UTF-8 with a non-ASCII value: a text-mode read decodes it by the locale (cp1252 on Windows) and mangles it.
+ expected = {"do_resize": True, "size": {"height": 518}, "processor_class": "R\u00e9sum\u00e9Processor"}
+ config = tmp_path / "preprocessor_config.json"
+ config.write_bytes(json.dumps(expected, ensure_ascii=False).encode("utf-8"))
+ monkeypatch.setenv("HOME", str(tmp_path))
+ monkeypatch.setenv("USERPROFILE", str(tmp_path)) # what os.path.expanduser reads on Windows
+ url = {
+ "str": str(config),
+ "Path": config,
+ "~": os.path.join("~", "preprocessor_config.json"),
+ }[form]
+
+ with mock.patch("kornia.core.download._download_url_to_file") as mock_download:
+ assert ONNXLoader.load_config(url, download=download) == expected
+ mock_download.assert_not_called()
+
+ @pytest.mark.parametrize("what", ["missing file", "directory"])
+ @pytest.mark.parametrize("download", [True, False])
+ def test_load_config_names_what_it_accepts(self, download, what, tmp_path):
+ url = str(tmp_path / "missing.json") if what == "missing file" else str(tmp_path)
+ with pytest.raises(RuntimeError, match=r"neither an HTTP\(S\) URL nor an existing local file") as info:
+ ONNXLoader.load_config(url, download=download)
+ assert "download=True" not in str(info.value)
+
+ def test_path_like_names_are_local_paths(self, monkeypatch, tmp_path):
+ # a PathLike names a local file, never an hf:// model or a URL, whatever its text
+ from unittest import mock
+
+ monkeypatch.chdir(tmp_path) # a default cache directory, if one were reached, is relative to it
+
+ class _Name:
+ def __init__(self, text):
+ self.text = text
+
+ def __fspath__(self):
+ return self.text
+
+ with (
+ mock.patch.object(ONNXLoader, "download") as mock_download,
+ mock.patch("kornia.core.download._download_url_to_file") as mock_fetch,
+ ):
+ with pytest.raises(ValueError, match=r"File hf://operators/some_model not found"):
+ ONNXLoader.load_model(_Name("hf://operators/some_model"))
+ with pytest.raises(ValueError, match=r"File https://example\.invalid/m\.onnx not found"):
+ ONNXLoader.load_model(_Name("https://example.invalid/m.onnx"))
+ with pytest.raises(RuntimeError, match="neither an HTTP"):
+ ONNXLoader.load_config(_Name("https://example.invalid/cfg.json"))
+ mock_download.assert_not_called()
+ mock_fetch.assert_not_called()
+
+ @pytest.mark.parametrize("form", ["Path", "~"])
+ def test_load_model_reads_a_local_path_object_and_a_tilde(self, form, monkeypatch, tmp_path):
+ from onnx.helper import make_graph, make_model, make_node, make_tensor_value_info
+
+ 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])],
+ )
+ path = tmp_path / "identity.onnx"
+ onnx.save(make_model(graph), str(path))
+ monkeypatch.setenv("HOME", str(tmp_path))
+ monkeypatch.setenv("USERPROFILE", str(tmp_path))
+ name = {"Path": path, "~": os.path.join("~", "identity.onnx")}[form]
+
+ assert [node.op_type for node in ONNXLoader.load_model(name).graph.node] == ["Identity"]
+
+ @pytest.mark.parametrize("value", [b"model.onnx", 1, None])
+ def test_loaders_take_a_str_or_a_path_object_only(self, value):
+ # bytes too: ONNX Runtime reads them as a serialized model, and the message says how to load one
+ hint = (
+ r" For a serialized model, pass onnx\.load_model_from_string\(data\)\." if isinstance(value, bytes) else ""
+ )
+ message = rf" takes a str or an os\.PathLike, got {type(value).__name__}\.{hint}$"
+ with pytest.raises(TypeError, match=r"ONNXLoader\.load_model" + message):
+ ONNXLoader.load_model(value)
+ with pytest.raises(TypeError, match=r"ONNXLoader\.load_config" + message):
+ ONNXLoader.load_config(value)
+
@pytest.mark.parametrize(
"url", ["https://example.invalid", "https://example.invalid/", "https://example.invalid/d/"]
)
@@ -567,6 +654,40 @@ def test_io_name_conversion():
assert converted_model.graph.node[0].output[0] == "output"
+def test_io_name_conversion_on_a_real_model_runs_in_onnxruntime():
+ # the names a model from onnx-community carries, renamed to the ones ONNXSequential connects by default
+ import numpy as np
+
+ ort = pytest.importorskip("onnxruntime")
+ from onnx.helper import make_graph, make_model, make_node, make_opsetid, make_tensor_value_info
+
+ from kornia.onnx import ONNXSequential
+ from kornia.onnx.utils import io_name_conversion
+
+ def _vector(name):
+ return make_tensor_value_info(name, onnx.TensorProto.FLOAT, [2])
+
+ graph = make_graph(
+ [make_node("Neg", ["pixel_values"], ["mid"]), make_node("Relu", ["mid"], ["predicted_depth"])],
+ "g",
+ [_vector("pixel_values")],
+ [_vector("predicted_depth")],
+ )
+ model = make_model(graph, opset_imports=[make_opsetid("", 18)], ir_version=9)
+
+ converted = io_name_conversion(model, {"pixel_values": "input", "predicted_depth": "output", "absent": "x"})
+
+ assert converted is model # in place
+ assert [v.name for v in model.graph.input] == ["input"]
+ assert [v.name for v in model.graph.output] == ["output"]
+ assert [list(node.input) for node in model.graph.node] == [["input"], ["mid"]]
+ onnx.checker.check_model(model)
+ x = np.array([-1.0, 2.0], dtype=np.float32)
+ session = ort.InferenceSession(model.SerializeToString(), providers=["CPUExecutionProvider"])
+ assert session.run(None, {"input": x})[0].tolist() == [1.0, 0.0]
+ assert ONNXSequential(model, model)(x)[0].tolist() == [0.0, 0.0]
+
+
def test_add_metadata():
from onnx.helper import make_graph, make_model, make_node, make_tensor_value_info