π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
docs(onnx): correct the ONNX docstrings and pages the batch 17 audit found false (#6160)
Dmytro Mishkine1fe3f61bc07
diff --git a/docs/source/augmentation.rst b/docs/source/augmentation.rstindex c1b6e69b3..6092c2b1b 100644--- a/docs/source/augmentation.rst+++ b/docs/source/augmentation.rst@@ -93,8 +93,12 @@ Kornia augmentations are plain ``nn.Module`` s and are exportable for deployment``AugmentationSequential`` fuses the pointwise chain end to end. See the per-op ``test_dynamo``tests for the compile-clean set.-- **ONNX.** Export a pipeline with :class:`kornia.onnx.ONNXSequential`; pre-built ONNX models are- published under the ``kornia/ONNX_models`` Hugging Face repo.+- **ONNX.** :class:`~kornia.onnx.sequential.ONNXSequential` chains ONNX graphs; it does not take an augmentation+ module. The :ref:`export survey <export-support>` records which individual augmentations exported. Without+ ``dynamic_shapes``, a pipeline exported with ``torch.onnx.export(..., dynamo=True)`` gets a graph of the input shape+ it was exported with, and some augmentations (``Resize``, for one) keep that shape fixed even with it. Some+ augmentations fail to export. The exported file can be chained with ``ONNXSequential``. Pre-built ONNX+ models are published under the ``kornia/ONNX_models`` Hugging Face repo... currentmodule:: kornia.augmentationdiff --git a/docs/source/get-started/onnx.rst b/docs/source/get-started/onnx.rstindex 4cd130d00..abdc0c339 100644--- a/docs/source/get-started/onnx.rst+++ b/docs/source/get-started/onnx.rst@@ -165,6 +165,9 @@ Then move a sequence between devices with ``as_cuda()`` / ``as_cpu()``:onnx_seq(inp)print("--- CPU %s seconds ---" % (time.time() - start_time))+On an onnxruntime build without CUDA, ``as_cuda()`` only warns and the sequence keeps running on the CPU;+``get_session().get_providers()`` shows which provider runs.+A typical result:.. code-block:: console@@ -185,7 +188,10 @@ Use the ``io_maps`` argument to say which output feeds which input: one list ofjoint, as in step 4.**Can I use custom ONNX Runtime session options?**-Yes, pass your own session options to the ``create_session`` method.+Yes. Pass them as ``session_options=`` to the constructor of+:class:`~kornia.onnx.sequential.ONNXSequential`, or replace the session of an existing object with+``seq.set_session(seq.create_session(session_options=...))``. ``create_session`` alone returns a new session and leaves+the object on the one it already has.**Which operators export?**The :ref:`ONNX, torch.compile and torch.export survey <export-support>` lists every surveyed operator withdiff --git a/docs/source/onnx.rst b/docs/source/onnx.rstindex c3f871219..fd51c61ca 100644--- a/docs/source/onnx.rst+++ b/docs/source/onnx.rst@@ -14,6 +14,8 @@ ONNX graphs (local files, ``onnx.ModelProto`` objects, or pre-exported Kornia op.. autoclass:: kornia.onnx.module.ONNXModule:members:+.. autofunction:: kornia.onnx.load+.. autoclass:: kornia.onnx.sequential.ONNXSequential:members:@@ -26,5 +28,15 @@ ONNX graphs (local files, ``onnx.ModelProto`` objects, or pre-exported Kornia op# Load a Hugging Face operatorONNXLoader.load_model("hf://operators/kornia.color.gray.GrayscaleToRgb")- # Load a local converted/downloaded operator- ONNXLoader.load_model("operators/kornia.color.gray.GrayscaleToRgb")+ # Load a downloaded operator from the cache: the same name, served from the cache directory+ # (".kornia_hub/onnx_models" by default) without a download+ ONNXLoader.load_model("hf://operators/kornia.color.gray.GrayscaleToRgb", download=False)+ # Load a local file by its path+ ONNXLoader.load_model(".kornia_hub/onnx_models/operators/kornia.color.gray.GrayscaleToRgb.onnx")++.. autofunction:: kornia.onnx.utils.add_metadata++.. autofunction:: kornia.onnx.utils.io_name_conversion++.. autoclass:: kornia.onnx.download.CachedDownloader+ :members:diff --git a/kornia/augmentation/base.py b/kornia/augmentation/base.pyindex 29c88447f..d4f4afbc1 100644--- a/kornia/augmentation/base.py+++ b/kornia/augmentation/base.py@@ -92,11 +92,9 @@ class _BasicAugmentationBase(nn.Module):"""- # Flag for whether this augmentation supports ONNX export. Override to False in subclasses- # that use ops the legacy tracer can't lower (e.g. ``torch.histc``,- # ``torch.distributions.Beta``).- # Users can introspect via ``aug.exportable``; CI iterates the known-exportable- # subset in ``tests/augmentation/test_onnx_export.py``.+ # A class-level flag that ``aug.exportable`` returns. It is True unless a subclass sets it, and no subclass does.+ # Nothing in kornia reads it, and it does not say whether an export works: the augmentations that+ # ``tests/augmentation/test_onnx_export.py`` exports are listed in that file, not selected by this flag.ONNX_EXPORTABLE = Truedef __init_subclass__(cls, **kwargs: Any) -> None:@@ -121,13 +119,10 @@ class _BasicAugmentationBase(nn.Module):@propertydef exportable(self) -> bool:- """Whether this augmentation supports ONNX export via the legacy tracer at opset 20.+ """The class-level ``ONNX_EXPORTABLE`` flag, ``True`` unless a subclass sets it.- Reflects the class-level ``ONNX_EXPORTABLE`` flag. Note that ``True`` here- means *the graph traces and exports* β it does not guarantee the resulting- ONNX runtime output is bit-equivalent to eager. See the categorisation in- ``tests/augmentation/test_onnx_export.py`` for the numerical-correctness- signal per augmentation.+ Nothing in kornia reads the flag, and it makes no statement about whether, or with which exporter, an+ augmentation exports."""return bool(self.ONNX_EXPORTABLE)diff --git a/kornia/contrib/edge_detection.py b/kornia/contrib/edge_detection.pyindex fc0a38555..90ab094a8 100644--- a/kornia/contrib/edge_detection.py+++ b/kornia/contrib/edge_detection.py@@ -238,18 +238,18 @@ class EdgeDetector(ModelBase, ONNXExportMixin):Args:onnx_name:The name of the output ONNX file. If not provided, ``"kornia_<name>_<image_size>.onnx"``, for- example ``"kornia_dexined_352.onnx"``.+ example ``"kornia_dexined_352.onnx"`` (``"kornia_dexined_None.onnx"`` for ``image_size=None``).image_size:The height and width of the graph's input, which the returned maps have too. If None, both are- dynamic. The pre-processor keeps the size it was built with, so the model runs at that size- whatever ``image_size`` is.+ dynamic. With the pre- and post-processor, the pre-processor resizes the input to the size it was+ built with, whatever ``image_size`` is; without them, the model runs at the size of its input.include_pre_and_post_processor:Whether to include the pre-processor and post-processor in the exported model.save:If True, write the model to ``onnx_name``; it is returned either way.additional_metadata:Additional metadata to add to the ONNX model.- kwargs: Additional arguments to convert to onnx.+ kwargs: Additional keyword arguments of :func:`torch.onnx.export`.Raises:ValueError: With the pre- and post-processor, if the ``ResizePostProcessor`` resizes with ``"area"``:diff --git a/kornia/contrib/object_detection.py b/kornia/contrib/object_detection.pyindex 8e52de393..9a746e018 100644--- a/kornia/contrib/object_detection.py+++ b/kornia/contrib/object_detection.py@@ -260,19 +260,21 @@ class ObjectDetector(ModelBase, ONNXExportMixin):Args:onnx_name:- The name of the output ONNX file. If not provided, a default name in the- format "Kornia-<ClassName>.onnx" will be used.+ The name of the output ONNX file. If not provided, ``"kornia_<name>_<image_size>.onnx"``, with+ the detector's ``name``, for example ``"kornia_detection_640.onnx"``+ (``"kornia_detection_None.onnx"`` for ``image_size=None``).image_size:- The size to which input images will be resized during preprocessing.- If None, image_size will be dynamic.+ The height and width of the exported graph's input. If None, both are dynamic. With the pre- and+ post-processor, the pre-processor resizes the input to the size it was built with, whatever+ ``image_size`` is; without them, the model runs at the size of its input.For RTDETR, recommended scales include [480, 512, 544, 576, 608, 640, 672, 704, 736, 768, 800].include_pre_and_post_processor:Whether to include the pre-processor and post-processor in the exported model.save:- If to save the model or load it.+ If True, write the model to ``onnx_name``; it is returned either way.additional_metadata:Additional metadata to add to the ONNX model.- kwargs: Additional arguments to convert to onnx.+ kwargs: Additional keyword arguments of :func:`torch.onnx.export`.Note:With a post-processor that returns a list of per-image detections, as adiff --git a/kornia/contrib/super_resolution.py b/kornia/contrib/super_resolution.pyindex b83328f11..4142c7673 100644--- a/kornia/contrib/super_resolution.py+++ b/kornia/contrib/super_resolution.py@@ -224,15 +224,15 @@ class SuperResolution(ModelBase[SuperResolutionConfig], ONNXExportMixin):Args:onnx_name:- The name of the output ONNX file. If not provided, a default name in the- format "Kornia-<ClassName>.onnx" will be used.+ The name of the output ONNX file. If not provided, ``"kornia_<name>.onnx"``, with the model's+ ``name``, for example ``"kornia_small_sr.onnx"``.include_pre_and_post_processor:Whether to include the pre-processor and post-processor in the exported model.save:- If to save the model or load it.+ If True, write the model to ``onnx_name``; it is returned either way.additional_metadata:Additional metadata to add to the ONNX model.- kwargs: Additional arguments for converting to onnx.+ kwargs: Additional keyword arguments of :func:`torch.onnx.export`."""if onnx_name is None:diff --git a/kornia/core/mixin/onnx.py b/kornia/core/mixin/onnx.pyindex a5abcf9fa..eedae77db 100644--- a/kornia/core/mixin/onnx.py+++ b/kornia/core/mixin/onnx.py@@ -278,8 +278,8 @@ class ONNXExportMixin:Args:onnx_name:- The name of the output ONNX file. If not provided, a default name in the- format "Kornia-<ClassName>.onnx" will be used.+ The name of the output ONNX file. If not provided, ``"Kornia-<ClassName>.onnx"`` is used, with the+ name of the object's class. Classes that override ``to_onnx`` can use another default.input_shape:The input shape for the model as a list of integers. If None,`ONNX_DEFAULT_INPUTSHAPE` will be used, with its fixed entries (the channel count) taken@@ -298,7 +298,7 @@ class ONNXExportMixin:model:The model to export. If not provided, the current object will be used.save:- If to save the model or load it.+ If True, write the model to ``onnx_name``; it is returned either way. If False, nothing is written.additional_metadata:Additional metadata to add to the ONNX model. A key that is already present is overwritten.**kwargs:@@ -455,6 +455,8 @@ class ONNXRuntimeMixin:op: Onnx operation.providers:Execution providers for ONNXRuntime (e.g., ['CUDAExecutionProvider', 'CPUExecutionProvider']).+ A provider that the installed onnxruntime build does not offer is skipped with onnxruntime's+ ``UserWarning``, and the session runs on the CPU if none is left.session_options:Optional ONNXRuntime session options for session configuration and optimizations, used as given.If None, the session uses ``ORT_ENABLE_EXTENDED`` graph optimizations.@@ -498,7 +500,8 @@ class ONNXRuntimeMixin:def as_cuda(self, device_id: int = 0, **kwargs: Any) -> None:"""Set the session to run on CUDA.- We set the ONNX runtime session to use CUDAExecutionProvider.+ We set the ONNX runtime session to use CUDAExecutionProvider. If the installed onnxruntime build does not+ offer it, nothing raises: onnxruntime warns and the session runs on the CPU.For other CUDAExecutionProvider configurations, or CUDA/cuDNN/ONNX version issues,you may refer to https://onnxruntime.ai/docs/execution-providers/CUDA-ExecutionProvider.html.@@ -517,7 +520,8 @@ class ONNXRuntimeMixin:def as_tensorrt(self, device_id: int = 0, **kwargs: Any) -> None:"""Set the session to run on TensorRT.- We set the ONNX runtime session to use TensorrtExecutionProvider.+ We set the ONNX runtime session to use TensorrtExecutionProvider. If the installed onnxruntime build does not+ offer it, nothing raises: onnxruntime warns and the session runs on the CPU.For other TensorrtExecutionProvider configurations, or CUDA/cuDNN/ONNX/TensorRT version issues,you may refer to https://onnxruntime.ai/docs/execution-providers/TensorRT-ExecutionProvider.html.@@ -533,7 +537,8 @@ class ONNXRuntimeMixin:def as_openvino(self, device_type: str = "GPU", **kwargs: Any) -> None:"""Set the session to run on OpenVINO.- We set the ONNX runtime session to use OpenVINOExecutionProvider.+ We set the ONNX runtime session to use OpenVINOExecutionProvider. If the installed onnxruntime build does not+ offer it, nothing raises: onnxruntime warns and the session runs on the CPU.For other OpenVINOExecutionProvider configurations, or CUDA/cuDNN/ONNX/TensorRT version issues,you may refer to https://onnxruntime.ai/docs/execution-providers/OpenVINO-ExecutionProvider.html.diff --git a/kornia/models/_hf_models/hf_onnx_community.py b/kornia/models/_hf_models/hf_onnx_community.pyindex 6904300ac..9bd1d062c 100644--- a/kornia/models/_hf_models/hf_onnx_community.py+++ b/kornia/models/_hf_models/hf_onnx_community.py@@ -243,11 +243,11 @@ class HFONNXComunnityModel(ONNXSequential, ModelBaseMixin):``resize`` stage runs in torch and is in neither graph: for a model that has one, the exportedgraph takes an image that is already resized, such as ``model.resize(image)``.save:- If to save the model or load it.+ If True, write the model to ``onnx_name``; it is returned either way.additional_metadata:Additional metadata to add to the exported model. It goes on a copy: the stored graphs, and a``ModelProto`` the model was built from, are left as they are.- kwargs: Additional arguments to convert to onnx.+ kwargs: Additional keyword arguments of ``onnx.save``, used when ``save`` is True.Returns:A copy of the model or of the combined graph, with ``source``, ``version`` and ``additional_metadata``.diff --git a/kornia/models/sam/model.py b/kornia/models/sam/model.pyindex d683b980e..1d8142c5b 100644--- a/kornia/models/sam/model.py+++ b/kornia/models/sam/model.py@@ -280,9 +280,14 @@ class Sam(ONNXExportMixin, ModelBase[SamConfig]):which cannot be directly exported via :func:`torch.onnx.export`.This override exports only the **image encoder** subgraph- (``self.image_encoder``), which is a pure ``(B, 3, H, W) -> (B, C, H', W')``- tensor-to-tensor module and fully ONNX-compatible. The encoder embeddings- can then be fed into a separate prompt-encoder / mask-decoder pipeline.+ (``self.image_encoder``), a ``(B, 3, H, W) -> (B, C, H', W')`` tensor-to-tensor+ module whose graph input is named ``input`` and output ``image_embeddings``. The prompt+ encoder and the mask decoder are not exported. The encoder embeddings+ can be fed into a separate prompt-encoder / mask-decoder pipeline.++ On torch 2.14, whose default exporter is the dynamo exporter, a ViT image encoder (SAM ViT-B, ViT-L, ViT-H)+ needs ``onnxscript`` 0.7.2 or later: with 0.7.1 the export raises :class:`torch.onnx.OnnxExporterError`+ (https://github.com/kornia/kornia/issues/5947). A TinyViT encoder (MobileSAM) exports with 0.7.1.Args:onnx_name: Path for the saved ``.onnx`` file. Defaults todiff --git a/kornia/onnx/module.py b/kornia/onnx/module.pyindex 729c30d30..829073ef4 100644--- a/kornia/onnx/module.py+++ b/kornia/onnx/module.py@@ -39,7 +39,9 @@ class ONNXModule(ONNXMixin, ONNXRuntimeMixin):For Hugging Face-hosted models, use the format 'hf://model_name'. Valid `model_name` can be found onhttps://huggingface.co/kornia/ONNX_models. Or a URL to the ONNX model.providers: A list of execution providers for ONNXRuntime- (e.g., ['CUDAExecutionProvider', 'CPUExecutionProvider']).+ (e.g., ['CUDAExecutionProvider', 'CPUExecutionProvider']). A provider that the installed onnxruntime+ build does not offer is skipped with onnxruntime's ``UserWarning``; the session runs on the CPU if none+ is left. If None, the CPU.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.@@ -49,6 +51,12 @@ class ONNXModule(ONNXMixin, ONNXRuntimeMixin):when it is cached. By default a cached file is used as it is, however old, and one that does not loadfails every time until it is deleted. It has no effect on a model object or a path to a local file.+ Note:+ Given an ``onnx.ModelProto``, the module holds that object itself, not a copy, unless a target version+ converts it: with no target, or with a target the model already has, ``module.op is op``. Whatever edits the+ wrapped graph in place, such as :meth:`add_metadata`, then changes the caller's model too. Pass a copy+ (``copy.deepcopy(op)``) to keep the original unchanged.+"""def __init__(@@ -103,6 +111,9 @@ class ONNXModule(ONNXMixin, ONNXRuntimeMixin):def add_metadata(self, additional_metadata: Optional[list[tuple[str, str]]] = None) -> onnx.ModelProto:"""Attach metadata entries to the wrapped ONNX model graph.+ The metadata is written into the wrapped graph in place. When the module was built from an+ ``onnx.ModelProto``, that can be the caller's own object; see the note of :class:`ONNXModule`.+Args:additional_metadata: Optional list of ``(key, value)`` string pairsto store in the ONNX model metadata properties.@@ -126,5 +137,8 @@ def load(model_name: Union[onnx.ModelProto, str, os.PathLike], *, force_downloadhttps://huggingface.co/kornia/ONNX_models. Or a URL to the ONNX model.force_download: If True, download the model again and replace the cached file, even when it is cached.+ Note:+ Given an ``onnx.ModelProto``, the module holds that object itself; see the note of :class:`ONNXModule`.+"""return ONNXModule(model_name, force_download=force_download)diff --git a/kornia/onnx/sequential.py b/kornia/onnx/sequential.pyindex 1101531d3..8d3bceead 100644--- a/kornia/onnx/sequential.py+++ b/kornia/onnx/sequential.py@@ -41,7 +41,9 @@ class ONNXSequential(ONNXMixin, ONNXRuntimeMixin):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']).+ (e.g., ['CUDAExecutionProvider', 'CPUExecutionProvider']). A provider that the installed onnxruntime+ build does not offer is skipped with onnxruntime's ``UserWarning``; the session runs on the CPU if none+ is left. If None, the CPU.session_options: Optional ONNXRuntime session options for optimizing the session.io_maps: An optional list with one list of ``(output, input)`` name pairs per joint between consecutivemodels: ``io_maps[0]`` connects outputs of the first model to inputs of the second, ``io_maps[1]`` thediff --git a/kornia/onnx/utils.py b/kornia/onnx/utils.pyindex 23bce6181..e9bdc026f 100644--- a/kornia/onnx/utils.py+++ b/kornia/onnx/utils.py@@ -399,7 +399,7 @@ def add_metadata(for the additional metadata to add to the ONNX model. Values are stored as strings.Returns:- The ONNX model with the added metadata.+ ``onnx_model`` itself, with the added metadata: the metadata is written in place."""if additional_metadata is None: