π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
fix(onnx): export EdgeDetector and SuperResolution with a per-image list output for one image (#6197)
Dmytro Mishkin4a476f499a49
diff --git a/changelog.d/6197.fixed.md b/changelog.d/6197.fixed.mdnew file mode 100644index 000000000..83e4efef7--- /dev/null+++ b/changelog.d/6197.fixed.md@@ -0,0 +1 @@+`EdgeDetector.to_onnx` and `SuperResolution.to_onnx` with the pre- and post-processor export a model whose output is a list with one item per image for a batch of one image, as `ObjectDetector.to_onnx` does for per-image detections. A tuple with one item per image, which the output kind's reading tells from a fixed set of batched outputs by its length at two batch sizes, counts as such a list, as for `ObjectDetector` (#6192). Such a list comes from a post-processor that returns one, or, for `SuperResolution`, from the network itself or a pre-processor that returns a list of images, which `forward` runs one at a time. Both used to declare a dynamic batch, and the TorchScript exporter (`dynamo=False`) turned the list into one graph output per traced image: the graph returned two maps for a batch of three images, and two maps, one of them empty, for a single image. From torch 2.9 the dynamo exporter failed on such a model, and now exports it as well. A `dynamic_axes` or `dynamic_shapes` argument that makes the batch of such an export dynamic raises a `ValueError` after the export, before anything is saved. The kind of output is first read from a one-image forward pass outside the export, so a `ResizePostProcessor` subclass whose own `forward` returns a list eagerly is now exported for one image too, even if it returns a tensor under export, and a dynamic override of it raises. `EdgeDetector` with a `ResizePostProcessor` that keeps its own `forward` (under the class's own `forward`, without forward hooks), `SuperResolution` with known tensor-output networks and the builders' pre- and post-processors (with unchanged forwards), and a model that returns one tensor keep the dynamic batch. The check after the export reuses a positive list reading. A tensor reading is checked again at the actual tracing batch, so batch-dependent per-image outputs cannot silently produce a dynamic graph that drops images.diff --git a/kornia/contrib/edge_detection.py b/kornia/contrib/edge_detection.pyindex 90ab094a8..4c0b1eb16 100644--- a/kornia/contrib/edge_detection.py+++ b/kornia/contrib/edge_detection.py@@ -26,7 +26,7 @@ from kornia.color.gray import grayscale_to_rgbfrom kornia.color.rgb import RgbToBgrfrom kornia.core.external import PILImage as Imagefrom kornia.core.external import onnx-from kornia.core.mixin.onnx import ONNXExportMixin+from kornia.core.mixin.onnx import ONNXExportMixin, _has_forward_hooks, _preserved_rng, _returns_per_image_outputsfrom kornia.enhance.normalize import Normalizefrom kornia.geometry.transform import resizefrom kornia.models.base import ModelBase@@ -152,6 +152,20 @@ class EdgeDetector(ModelBase, ONNXExportMixin):and type(self.post_processor).forward is ResizePostProcessor.forward)+ def _returns_one_tensor_on_export(self) -> bool:+ """Whether an export returns the maps of the batch as one tensor, so ``to_onnx`` reads no output kind.++ That holds for a post-processor the export replaces (:meth:`_resizes_back_on_export`) under this class's own+ :meth:`forward`, with no forward hook on the detector, on a module inside it or on all modules. Any other+ detector is probed; with such a post-processor the probe reads the eager per-image list and the detector is+ exported for one image.+ """+ return (+ self._resizes_back_on_export()+ and getattr(self.forward, "__func__", None) is EdgeDetector.forward+ and not _has_forward_hooks(self)+ )+def _export_interpolation(self) -> str:"""The post-processor's interpolation mode, which an export resizes the maps back with.@@ -253,31 +267,77 @@ class EdgeDetector(ModelBase, ONNXExportMixin):Raises:ValueError: With the pre- and post-processor, if the ``ResizePostProcessor`` resizes with ``"area"``:- adaptive average pooling cannot be exported with the input's size.+ adaptive average pooling cannot be exported with the input's size; or if the post-processor returns+ a list (or tuple) with one map per image and the exported batch is dynamic, from a ``dynamic_axes`` or+ ``dynamic_shapes`` argument or, with the TorchScript exporter, because the list comes only for more+ than one image.++ Note:+ With the pre- and post-processor, a detector whose post-processor returns a list with one map per image,+ or a tuple as long as the batch at two batch sizes, is exported for a batch of one image: the exporters+ turn such a sequence into one graph output per traced image, so a dynamic batch would return the traced+ batch's maps at any batch size. A ``ResizePostProcessor`` that keeps+ its own ``forward`` is not such a post-processor, since the export replaces it, as long as the detector+ keeps :meth:`forward` as this class defines it and no forward hook applies to it. Which kind of output+ any other detector returns is read from one forward pass of the detector for one image at the export+ size, in eval mode, without gradients and outside the export. A ``forward`` that returns a list there is+ therefore exported for one image even if it returns a tensor under export, as a ``ResizePostProcessor``+ subclass whose own ``forward`` calls ``ResizePostProcessor.forward`` does. A tensor there is read again at+ the batch a dynamic export traces, since the kind can depend on the batch size. Return the maps of the+ batch as one tensor to export a batch of any size. A ``dynamic_axes`` or ``dynamic_shapes`` argument that+ makes the batch of such an export dynamic raises a ``ValueError`` after the export, before anything is+ saved. A post-processor that returns a list only for more than one image has no dynamic export either: the+ TorchScript exporter's graph raises that ``ValueError``, the dynamo exporter of torch 2.9 and later fails to+ trace it, and that of torch 2.5.1 fixes the batch at the two images it traces."""if onnx_name is None:onnx_name = f"kornia_{self.name}_{image_size}.onnx"if include_pre_and_post_processor and self._resizes_back_on_export():self._export_interpolation() # raises before the export for a mode it cannot export+ pseudo_shape = [1, 3, image_size or 352, image_size or 352]previous = self._exporting_to_onnxself._exporting_to_onnx = Truetry:- return ONNXExportMixin.to_onnx(- self,- onnx_name,- input_shape=[-1, 3, image_size or -1, image_size or -1],- output_shape=[-1, 1, image_size or -1, image_size or -1],- pseudo_shape=[1, 3, image_size or 352, image_size or 352],- model=self if include_pre_and_post_processor else self.model,- save=save,- additional_metadata=additional_metadata,- **kwargs,- )+ # Exported for a dynamic batch, a list of per-image maps comes out as the traced batch's maps, or the+ # export fails: such a detector is exported for one image.+ per_image = None+ if include_pre_and_post_processor and not self._returns_one_tensor_on_export():+ # The probe's input draws from the global generator, as the export's dummy does, and gives back what+ # it drew.+ with _preserved_rng():+ per_image = _returns_per_image_outputs(self, torch.rand(pseudo_shape))+ batch = 1 if per_image else -1+ with self._onnx_output_kind_kept(per_image):+ return ONNXExportMixin.to_onnx(+ self,+ onnx_name,+ input_shape=[batch, 3, image_size or -1, image_size or -1],+ output_shape=[batch, 1, image_size or -1, image_size or -1],+ pseudo_shape=pseudo_shape,+ model=self if include_pre_and_post_processor else self.model,+ save=save,+ additional_metadata=additional_metadata,+ **kwargs,+ )finally:self._exporting_to_onnx = previous+ def _onnx_fixed_batch_hint(self, module: Any, dummy_input: Any) -> Optional[str]:+ # The export replaces a ``ResizePostProcessor`` with one resize of the batch, a tensor: only another detector+ # is read, from what ``to_onnx`` read before the export.+ if (+ module is not self+ or self._returns_one_tensor_on_export()+ or not self._onnx_returns_per_image_outputs(dummy_input)+ ):+ return None+ return (+ "Use a post-processor that returns the maps of the batch as one tensor, or a ResizePostProcessor, which "+ "the export replaces with one resize of the batch, to export a dynamic batch."+ )+class EdgeDetectorBuilder:"""EdgeDetectorBuilder is a class that builds an edge detection model.diff --git a/kornia/contrib/object_detection.py b/kornia/contrib/object_detection.pyindex 3c274865b..cba5289dd 100644--- a/kornia/contrib/object_detection.py+++ b/kornia/contrib/object_detection.py@@ -28,15 +28,7 @@ from kornia.constants import _get_by_namefrom kornia.core.check import KORNIA_CHECK_SHAPEfrom kornia.core.external import PILImage as Imagefrom kornia.core.external import onnx-from kornia.core.mixin.onnx import (- ONNXExportMixin,- _eval_mode,- _first_floating_tensor,- _preserved_call_state,- _preserved_rng,- _to_floating,- _uses_dynamic_shapes,-)+from kornia.core.mixin.onnx import ONNXExportMixin, _preserved_rng, _returns_per_image_outputs, _uses_dynamic_shapesfrom kornia.image.draw import draw_rectanglefrom kornia.models.base import ModelBasefrom kornia.models.processors import ResizePreProcessor@@ -134,31 +126,6 @@ def results_from_detections(return results-def _returns_detections_per_image(detector: nn.Module, images: torch.Tensor) -> bool:- """Return whether ``detector`` returns a sequence of per-image detections rather than batched tensors.-- The detector runs in eval mode and without gradients, on ``images`` moved to the dtype and device of its first- floating tensor, as the export's dummy input is. A tuple is checked at a second batch size: its length must- follow the batch, rather than name a fixed set of batched outputs such as ``(boxes, scores)``. The- attributes that ``to_onnx`` keeps, such as an image module's output cache, hold what they held before, in every- module inside the detector, and so does the global random state.- """- reference = _first_floating_tensor(detector)- if reference is not None:- images = _to_floating(images, reference)- # The run must not leave its output or parameters in a module inside the detector, nor consume the global random- # state, as the export's own run does not.- with _eval_mode(detector), _preserved_call_state(detector), _preserved_rng(), torch.no_grad():- output = detector(images)- if isinstance(output, list):- return True- if not isinstance(output, tuple) or len(output) != images.shape[0]:- return False- other_batch = 2 if images.shape[0] == 1 else 1- other_output = detector(images[:1].expand(other_batch, *images.shape[1:]).contiguous())- return isinstance(other_output, tuple) and len(other_output) == other_batch--class ObjectDetector(ModelBase, ONNXExportMixin):"""Wrap an object detection model and perform pre-processing and post-processing."""@@ -290,11 +257,13 @@ class ObjectDetector(ModelBase, ONNXExportMixin):With a post-processor that returns a list or tuple of per-image detections, as a``kornia.models.rt_detr.DETRPostProcessor`` that filters by confidence does, the model isexported for a batch of one image: no ONNX output holds a list as long as the batch. Which kind of output- the detector returns is read at the export size, in eval mode and without gradients. A tuple requires- two forward passes with different batch sizes to distinguish per-image results from batched outputs.- Build an RT-DETR detector with ``confidence_filtering=False`` to export a batch of any size. A- ``dynamic_axes`` or ``dynamic_shapes`` argument that makes the batch of such an export dynamic raises a- ``ValueError`` after the export, before anything is saved.+ the detector returns is read from one forward pass for one image at the export size, in eval mode and+ without gradients, and a tuple as long as the batch from a second one at another batch size, which tells+ per-image results from a fixed set of batched outputs such as ``(boxes, scores)``. A per-image result+ requires a fixed batch; a tensor result is checked again at the actual tracing batch before accepting a+ dynamic graph. Build an RT-DETR detector with ``confidence_filtering=False`` to export a batch of any+ size. A ``dynamic_axes`` or ``dynamic_shapes`` argument that makes the batch of such an export dynamic+ raises a ``ValueError`` after the export, before anything is saved.Without the pre- and post-processor, a model that declares ``ONNX_OUTPUT_NAMES``, as:class:`~kornia.models.rt_detr.RTDETR` does (``pred_logits`` and ``pred_boxes``), has its outputs exported@@ -306,11 +275,13 @@ class ObjectDetector(ModelBase, ONNXExportMixin):pseudo_shape = [1, 3, image_size or 352, image_size or 352]# Exported for a dynamic batch, a per-image sequence comes out as the traced batch's detections, or the export# fails: such a detector is exported for one image.- batch = -1- # The probe's input draws from the global generator, as the export's dummy does, and gives back what it drew.- with _preserved_rng():- if include_pre_and_post_processor and _returns_detections_per_image(self, torch.rand(pseudo_shape)):- batch = 1+ per_image = None+ if include_pre_and_post_processor:+ # The probe's input draws from the global generator, as the export's dummy does, and gives back what it+ # drew.+ with _preserved_rng():+ per_image = _returns_per_image_outputs(self, torch.rand(pseudo_shape))+ batch = 1 if per_image else -1input_shape = [batch, 3, image_size or -1, image_size or -1]output_names = None if include_pre_and_post_processor else getattr(self.model, "ONNX_OUTPUT_NAMES", None)@@ -325,20 +296,21 @@ class ObjectDetector(ModelBase, ONNXExportMixin):output_axes = {name: {0: "dim_0"} for name in kwargs["output_names"]}kwargs["dynamic_axes"] = {"input": input_axes, **output_axes}- return ONNXExportMixin.to_onnx(- self,- onnx_name,- input_shape=input_shape,- output_shape=[-1, -1, 6],- pseudo_shape=pseudo_shape,- model=self if include_pre_and_post_processor else self.model,- save=save,- additional_metadata=additional_metadata,- **kwargs,- )+ with self._onnx_output_kind_kept(per_image):+ return ONNXExportMixin.to_onnx(+ self,+ onnx_name,+ input_shape=input_shape,+ output_shape=[-1, -1, 6],+ pseudo_shape=pseudo_shape,+ model=self if include_pre_and_post_processor else self.model,+ save=save,+ additional_metadata=additional_metadata,+ **kwargs,+ )def _onnx_fixed_batch_hint(self, module: Any, dummy_input: Any) -> Optional[str]:- if module is not self or not _returns_detections_per_image(self, dummy_input):+ if module is not self or not self._onnx_returns_per_image_outputs(dummy_input):return Nonereturn ("Use a post-processor that returns one tensor for the batch, such as a DETRPostProcessor with "diff --git a/kornia/contrib/super_resolution.py b/kornia/contrib/super_resolution.pyindex 4142c7673..bc85563cd 100644--- a/kornia/contrib/super_resolution.py+++ b/kornia/contrib/super_resolution.py@@ -24,7 +24,7 @@ from torch import nnfrom kornia.core.download import load_state_dict_from_urlfrom kornia.core.external import PILImage as Imagefrom kornia.core.external import onnx-from kornia.core.mixin.onnx import ONNXExportMixin+from kornia.core.mixin.onnx import ONNXExportMixin, _has_forward_hooks, _preserved_rng, _returns_per_image_outputsfrom kornia.models.base import ModelBasefrom kornia.models.processors import OutputRangePostProcessor, ResizePreProcessorfrom kornia.models.rrdbnet import RRDBNet@@ -234,23 +234,86 @@ class SuperResolution(ModelBase[SuperResolutionConfig], ONNXExportMixin):Additional metadata to add to the ONNX model.kwargs: Additional keyword arguments of :func:`torch.onnx.export`.+ Raises:+ ValueError: With the pre- and post-processor, if the output is a list (or tuple) with one image per input+ image and the exported batch is dynamic, from a ``dynamic_axes`` or ``dynamic_shapes`` argument or,+ with the TorchScript exporter, because the list comes only for more than one image.++ Note:+ With the pre- and post-processor, an output that is a list with one image per input image, or a tuple as+ long as the batch at two batch sizes, is exported for a batch of one image: the exporters turn such a+ sequence into one graph output per traced image, so a dynamic batch would return the traced batch's+ images at any batch size. The list comes from a post-processor that+ returns one, from the network itself, or from a pre-processor that returns a list of images, which+ :meth:`forward` runs through the network one at a time. Known tensor-output networks (the builders'+ RRDB and SmallSR networks, ``nn.Identity`` and ``nn.Conv2d``) with ``nn.Identity`` or ``ResizePreProcessor``+ before them and ``nn.Identity`` or ``OutputRangePostProcessor`` after them keep a dynamic batch without a+ probe, provided the wrapper and each component retain their known ``forward`` implementations and no+ forward hook applies to them, a global one included. Other combinations are probed on one image at the+ export size in eval mode, without gradients and outside the export. A list result requires a fixed batch;+ a tensor result is checked again on the actual tracing batch before accepting a dynamic graph. A dynamic+ graph with per-image outputs raises a ``ValueError`` after the export, before anything is saved.+"""if onnx_name is None:onnx_name = f"kornia_{self.name}.onnx"# The dummy input must agree with a fixed input size, which ``to_onnx`` checks.pseudo_size = self.pseudo_image_size or self.input_image_size or 352+ pseudo_shape = [1, 3, pseudo_size, pseudo_size]+ # Exported for a dynamic batch, a list of per-image outputs comes out as the traced batch's images, or the+ # export fails: such a model is exported for one image.+ per_image = None+ if include_pre_and_post_processor and not self._returns_one_tensor_without_a_probe():+ # The probe's input draws from the global generator, as the export's dummy does, and gives back what it+ # drew.+ with _preserved_rng():+ per_image = _returns_per_image_outputs(self, torch.rand(pseudo_shape))+ batch = 1 if per_image else -1++ with self._onnx_output_kind_kept(per_image):+ return ONNXExportMixin.to_onnx(+ self,+ onnx_name,+ input_shape=[batch, 3, self.input_image_size or -1, self.input_image_size or -1],+ output_shape=[batch, 3, self.output_image_size or -1, self.output_image_size or -1],+ pseudo_shape=pseudo_shape,+ model=self if include_pre_and_post_processor else self.model,+ save=save,+ additional_metadata=additional_metadata,+ **kwargs,+ )++ def _returns_one_tensor_without_a_probe(self) -> bool:+ """Whether the wrapper, network and processors have known tensor-batch forward implementations.++ Unknown networks and overridden forwards need a probe even with the builders' processors. The builders'+ RRDB and SmallSR networks avoid an expensive extra forward when all implementations are unchanged.+ """+ # A plain callable as a processor has no ``forward``: it is probed.+ forward = getattr(self.forward, "__func__", None)+ network = getattr(getattr(self.model, "forward", None), "__func__", None)+ pre = getattr(getattr(self.pre_processor, "forward", None), "__func__", None)+ post = getattr(getattr(self.post_processor, "forward", None), "__func__", None)+ return (+ not _has_forward_hooks(self)+ and forward is SuperResolution.forward+ and network in (nn.Identity.forward, nn.Conv2d.forward, RRDBNet.forward, SmallSRNetWrapper.forward)+ and pre in (nn.Identity.forward, ResizePreProcessor.forward)+ and post in (nn.Identity.forward, OutputRangePostProcessor.forward)+ )- return ONNXExportMixin.to_onnx(- self,- onnx_name,- input_shape=[-1, 3, self.input_image_size or -1, self.input_image_size or -1],- output_shape=[-1, 3, self.output_image_size or -1, self.output_image_size or -1],- pseudo_shape=[1, 3, pseudo_size, pseudo_size],- model=self if include_pre_and_post_processor else self.model,- save=save,- additional_metadata=additional_metadata,- **kwargs,+ def _onnx_fixed_batch_hint(self, module: Any, dummy_input: Any) -> Optional[str]:+ if (+ module is not self+ or self._returns_one_tensor_without_a_probe()+ or not self._onnx_returns_per_image_outputs(dummy_input)+ ):+ return None+ return (+ "Use a network that returns one tensor for the batch, with a pre-processor that hands it one tensor and "+ "a post-processor that keeps it one, such as nn.Identity or ResizePreProcessor and "+ "OutputRangePostProcessor, to export a dynamic batch.")diff --git a/kornia/core/mixin/onnx.py b/kornia/core/mixin/onnx.pyindex 5817fd75b..fecf75395 100644--- a/kornia/core/mixin/onnx.py+++ b/kornia/core/mixin/onnx.py@@ -306,6 +306,53 @@ def _removed_buffer_hooks() -> Iterator[None]:del hooks[key]+def _has_forward_hooks(module: nn.Module) -> bool:+ """Return whether a forward hook or pre-hook can change what ``module`` returns.++ One on ``module`` or a module inside it counts, and so does a global one, which+ ``torch.nn.modules.module.register_module_forward_hook`` and ``register_module_forward_pre_hook`` add for every+ module. The export wrappers that skip reading their output kind for known modules read it whenever one is set.+ """+ hooks = torch.nn.modules.module+ if hooks._global_forward_hooks or hooks._global_forward_pre_hooks:+ return True+ return any(child._forward_hooks or child._forward_pre_hooks for child in module.modules())+++def _returns_per_image_outputs(module: Any, inputs: Any) -> bool:+ """Return whether ``module`` returns one output per image for ``inputs``, from eager runs.++ One output per image is a Python list, or a tuple whose length follows the batch: a tuple as long as the batch is+ read again at another batch size, so a fixed set of batched outputs such as ``(boxes, scores)`` is not one. The+ export wrappers whose output can be one item per image (from a post-processor, or for ``SuperResolution`` from the+ network or a pre-processor) read the kind of their output with it: the exporters turn such a sequence into one+ graph output per traced image. The module runs in eval mode and without gradients, on ``inputs`` moved to the+ dtype and device of its first floating tensor, as the export's dummy input is. Its output decides, so any+ post-processor is covered. The attributes that ``to_onnx`` keeps, such as an image module's output cache, hold+ what they held before, in every module inside ``module``, and so does the global random state; a buffer that+ ``forward`` itself updates is updated by these runs too.+ """+ reference = _first_floating_tensor(module)+ if reference is not None:+ inputs = _to_floating(inputs, reference)+ # The runs must not leave their output or parameters in a module inside ``module``, nor consume the global random+ # state, as the export's own run does not.+ with _eval_mode(module), _preserved_call_state(module), _preserved_rng(), torch.no_grad():+ output = module(inputs)+ if isinstance(output, list):+ return True+ if not isinstance(output, tuple) or len(output) != inputs.shape[0]:+ return False+ other_batch = 2 if inputs.shape[0] == 1 else 1+ other_output = module(inputs[:1].expand(other_batch, *inputs.shape[1:]).contiguous())+ return isinstance(other_output, tuple) and len(other_output) == other_batch+++# The instance attribute in which ``ONNXExportMixin._onnx_output_kind_kept`` keeps a wrapper's output kind for the+# duration of its export. It is written to ``__dict__`` and removed afterwards, so no class declares it.+_ONNX_PER_IMAGE_OUTPUT = "_onnx_per_image_output"++def _has_dynamic_batch(onnx_model: onnx.ModelProto) -> bool:"""Return whether the first graph input of ``onnx_model`` has a batch dimension without a fixed size."""if not onnx_model.graph.input:@@ -388,9 +435,10 @@ class ONNXExportMixin:RuntimeError: If `ONNX_EXPORTABLE` is False.ValueError: If `input_shape` has a dynamic dimension and a rank other than the pseudo shape's, ora fixed entry of `input_shape` differs from the explicit `pseudo_shape`; or if the model declares one- output per image, as ``ObjectDetector`` with a per-image post-processor and ``BoxFiltering`` without- ``filter_as_zero`` do, and the exported batch is dynamic. That check runs after the export and before- anything is saved.+ output per image, as an ``ObjectDetector``, ``EdgeDetector`` or ``SuperResolution`` exported with its+ pre- and post-processor whose output is a per-image list or tuple and ``BoxFiltering`` without+ ``filter_as_zero`` do, and the exported batch is dynamic.+ That check runs after the export and before anything is saved.FileNotFoundError: If `save` is True and the directory of `onnx_name` does not exist. This ischecked before the export runs.@@ -422,11 +470,12 @@ class ONNXExportMixin:- The dimensions marked `-1` are exported as dynamic: through `dynamic_shapes` on the dynamo exporterfrom torch 2.9, through `dynamic_axes` otherwise. A `dynamic_axes` or `dynamic_shapes` keywordargument replaces them.- - The exporters turn a list output into a fixed number of graph outputs, one per item of the traced- batch. ``ObjectDetector`` with a per-image post-processor and ``BoxFiltering`` without+ - The exporters turn a list or tuple output into a fixed number of graph outputs, one per item of the+ traced batch. An ``ObjectDetector``, ``EdgeDetector`` or ``SuperResolution`` exported with its pre- and+ post-processor whose output is a per-image list or tuple and ``BoxFiltering`` without``filter_as_zero`` declare such an output: their own ``to_onnx`` fixes the batch, and an export whosebatch comes out dynamic raises. Other models are not checked: the default ``_onnx_fixed_batch_hint``- declares nothing, so a list output keeps the traced batch's number of outputs at any batch size.+ declares nothing, so a per-image output keeps the traced batch's number of outputs at any batch size.- The model is exported with `torch.onnx.export`, with constant folding enabled."""@@ -541,6 +590,34 @@ class ONNXExportMixin:"""return None+ @contextlib.contextmanager+ def _onnx_output_kind_kept(self, per_image: Optional[bool]) -> Iterator[None]:+ """Keep ``per_image``, the output kind a wrapper's ``to_onnx`` read before its export, for the block.++ A per-image reading is enough to require a fixed batch. A tensor reading must be checked again on the+ actual tracing input, since the output kind can depend on the batch size. ``None`` keeps nothing. What was+ kept before comes back after the block, also when the export fails.+ """+ missing = object()+ previous = self.__dict__.get(_ONNX_PER_IMAGE_OUTPUT, missing)+ self.__dict__[_ONNX_PER_IMAGE_OUTPUT] = per_image+ try:+ yield+ finally:+ if previous is missing:+ del self.__dict__[_ONNX_PER_IMAGE_OUTPUT]+ else:+ self.__dict__[_ONNX_PER_IMAGE_OUTPUT] = previous++ def _onnx_returns_per_image_outputs(self, inputs: Any) -> bool:+ """Require a fixed batch if an earlier probe read one output per image, or if this run on ``inputs`` does.++ A tensor result at batch one does not establish the output kind at the export's tracing batch.+ A direct call of :meth:`ONNXExportMixin.to_onnx` on a wrapper keeps nothing, so its check runs the model.+ """+ kept = self.__dict__.get(_ONNX_PER_IMAGE_OUTPUT)+ return kept is True or _returns_per_image_outputs(self, inputs)+def _create_dummy_input(self, input_shape: list[int], pseudo_shape: Optional[list[int]] = None) -> Union[tuple[Any, ...], torch.Tensor]:diff --git a/tests/contrib/test_edge_detector.py b/tests/contrib/test_edge_detector.pyindex 300645e47..f256a0a22 100644--- a/tests/contrib/test_edge_detector.py+++ b/tests/contrib/test_edge_detector.py@@ -15,6 +15,7 @@# limitations under the License.#+import importlibfrom typing import Optionalimport pytest@@ -24,6 +25,7 @@ from torch import nnimport korniafrom kornia.contrib.edge_detection import EdgeDetector, EdgeDetectorBuilderfrom kornia.core._compat import torch_version_ge, torch_version_lt+from kornia.core.mixin.onnx import ONNXExportMixinfrom kornia.models.dexined import DexiNedfrom kornia.models.processors import ResizePostProcessor, ResizePreProcessor@@ -70,6 +72,89 @@ class _NearestPostProcessor(ResizePostProcessor):super().__init__("nearest")+class _DelegatingPostProcessor(ResizePostProcessor):+ """A ``ResizePostProcessor`` subclass whose own ``forward`` delegates: a list eagerly, the maps under export."""++ def forward(self, imgs, original_sizes):+ return super().forward(imgs, original_sizes)+++class _PerImageMaps(nn.Module):+ """A post-processor that returns a list with one ``(1, 1, h, w)`` map per image, at the model's size (#6161)."""++ def forward(self, imgs, original_sizes):+ return [imgs[i : i + 1] for i in range(imgs.shape[0])]+++class _TupleMaps(nn.Module):+ """A post-processor that returns a tuple: one map per image, or a fixed pair of batched maps (#6192, #6197)."""++ def __init__(self, per_image: bool) -> None:+ super().__init__()+ self.per_image = per_image++ def forward(self, imgs, original_sizes):+ return tuple(imgs.split(1)) if self.per_image else (imgs, 2 * imgs)+++class _DrawingNormalisedModel(nn.Module):+ """A convolution behind a batch norm, which a forward pass in training mode would update, drawing in any mode."""++ def __init__(self) -> None:+ super().__init__()+ self.conv = nn.Conv2d(3, 1, 3, padding=1)+ self.norm = nn.BatchNorm2d(1)++ def forward(self, x):+ return self.norm(self.conv(x + 0.0 * torch.rand_like(x)))+++# One exporter per ID. conftest.py deselects IDs that contain "dynamo" unless KORNIA_TEST_OPTIMIZER is set.+_EACH_EXPORTER = [+ pytest.param({"dynamo": False}, id="torchscript"),+ pytest.param(+ {"dynamo": True},+ id="torch_export",+ marks=pytest.mark.skipif(not dynamo_is_available(), reason=DYNAMO_UNAVAILABLE_REASON),+ ),+]++# A caller's dynamic batch: the TorchScript exporter reads ``dynamic_axes``, the dynamo exporter ``dynamic_shapes``+# from torch 2.9, where ``to_onnx`` declares its own dynamic dimensions with it.+_DYNAMIC_BATCH = [+ pytest.param({"dynamo": False, "dynamic_axes": {"input": {0: "batch"}}}, id="torchscript_batch_override"),+ pytest.param(+ {"dynamo": True, "dynamic_shapes": ({0: "batch"},)},+ id="torch_export_batch_override",+ marks=[+ pytest.mark.skipif(not dynamo_is_available(), reason=DYNAMO_UNAVAILABLE_REASON),+ pytest.mark.skipif(torch_version_lt(2, 9, 0), reason="to_onnx uses dynamic_shapes from torch 2.9"),+ ],+ ),+]+++def _count_probes(monkeypatch):+ """Count the runs that read the detector's output kind, wherever ``to_onnx`` or its check makes them."""+ mixin = importlib.import_module("kornia.core.mixin.onnx")+ probe = mixin._returns_per_image_outputs+ calls = []++ def _counting(module, inputs):+ calls.append(type(module).__name__)+ return probe(module, inputs)++ monkeypatch.setattr(kornia.contrib.edge_detection, "_returns_per_image_outputs", _counting)+ monkeypatch.setattr(mixin, "_returns_per_image_outputs", _counting)+ return calls+++def _importorskip_exporter(export_kwargs):+ pytest.importorskip("onnx")+ if export_kwargs.get("dynamo", torch_version_ge(2, 9, 0)):+ pytest.importorskip("onnxscript")++class TestEdgeDetector(BaseTester):def test_builder_feeds_dexined_bgr_minus_bgr_mean(self, device, dtype):# DexiNed was trained on ``cv2.imread`` images (BGR, 0-255) minus ``mean_bgr``: xavysp/DexiNed@d944b70@@ -391,6 +476,273 @@ class TestEdgeDetector(BaseTester):assert error is not None, f"no ValueError behind {info.value!r}"assert '"area"' in str(error)+ @pytest.mark.device_agnostic+ @pytest.mark.timeout(120)+ @pytest.mark.parametrize("export_kwargs", _EACH_EXPORTER)+ def test_onnx_with_a_per_image_post_processor_exports_one_image_6161(self, export_kwargs):+ # The exporters turn a list into one graph output per traced image. Exported for a dynamic batch, the+ # TorchScript graph returned the traced batch's two maps at any batch size, and the dynamo exporter failed;+ # such a detector is exported for one image, a batch that ONNX Runtime enforces.+ _importorskip_exporter(export_kwargs)+ ort = pytest.importorskip("onnxruntime")+ det = _small_edge_detector(_PerImageMaps())+ images = torch.rand(3, 3, 24, 24, generator=torch.Generator().manual_seed(0))+ assert len(det(images)) == 3++ op = det.to_onnx(image_size=24, save=False, **export_kwargs)++ assert op.graph.input[0].type.tensor_type.shape.dim[0].dim_value == 1+ assert op.graph.output[0].type.tensor_type.shape.dim[0].dim_value == 1+ session = ort.InferenceSession(op.SerializeToString(), providers=["CPUExecutionProvider"])+ outputs = session.run(None, {"input": images[:1].numpy()})+ assert len(outputs) == 1+ with torch.no_grad():+ expected = det(images[:1])+ self.assert_close(torch.from_numpy(outputs[0]), expected[0], rtol=0.0, atol=1e-5)+ with pytest.raises(_OrtInvalidArgument):+ session.run(None, {"input": images.numpy()})+ assert det._exporting_to_onnx is False++ @pytest.mark.device_agnostic+ @pytest.mark.timeout(120)+ @pytest.mark.parametrize("override", _DYNAMIC_BATCH)+ def test_onnx_with_a_per_image_post_processor_rejects_a_dynamic_batch_6161(self, override, tmp_path):+ # A caller's dynamic batch would give back the traced batch's maps at any batch size: the export raises after+ # it runs, before anything is saved, and names the cause.+ _importorskip_exporter(override)+ det = _small_edge_detector(_PerImageMaps())+ path = tmp_path / "edges.onnx"++ with pytest.raises(ValueError, match="EdgeDetector returns one output per image") as info:+ det.to_onnx(onnx_name=str(path), image_size=24, **override)++ assert "ResizePostProcessor" in str(info.value)+ assert not path.exists()+ assert det._exporting_to_onnx is False++ @pytest.mark.device_agnostic+ @pytest.mark.timeout(120)+ @pytest.mark.parametrize("per_image", [True, False], ids=["per_image_tuple", "batched_pair"])+ def test_onnx_with_a_tuple_post_processor_6197(self, per_image):+ # A tuple as long as the batch at two batch sizes is one map per image, as ObjectDetector reads it (#6192), and+ # is exported for one image; a fixed pair of batched maps keeps a dynamic batch.+ pytest.importorskip("onnx")+ det = _small_edge_detector(_TupleMaps(per_image))++ op = det.to_onnx(image_size=24, save=False, dynamo=False)++ batch = op.graph.input[0].type.tensor_type.shape.dim[0]+ if per_image:+ assert batch.dim_value == 1+ assert len(op.graph.output) == 1+ else:+ assert batch.dim_param+ assert len(op.graph.output) == 2++ @pytest.mark.device_agnostic+ @pytest.mark.timeout(120)+ def test_onnx_with_a_batch_dependent_post_processor_rejects_a_dynamic_export_6197(self, tmp_path):+ # A list only for more than one image: the one-image reading is a tensor, so the export is dynamic, and the+ # check after it reads the traced batch of two.+ pytest.importorskip("onnx")++ class _ListBeyondOneImage(ResizePostProcessor):+ def forward(self, imgs, original_sizes):+ return imgs if imgs.shape[0] == 1 else list(imgs.split(1))++ det = _small_edge_detector(_ListBeyondOneImage())+ path = tmp_path / "edges.onnx"++ with pytest.raises(ValueError, match="EdgeDetector returns one output per image"):+ det.to_onnx(onnx_name=str(path), image_size=24, dynamo=False)++ assert not path.exists()++ @pytest.mark.device_agnostic+ @pytest.mark.timeout(120)+ @pytest.mark.parametrize("change", ["forward", "hook", "global_hook"])+ def test_onnx_of_a_detector_whose_own_output_is_a_list_exports_one_image_6197(self, change):+ # A ResizePostProcessor alone skips the probe, but a detector whose forward, or a hook on it, turns the maps+ # into a per-image list is probed, and exported for one image.+ pytest.importorskip("onnx")++ class _ListDetector(EdgeDetector):+ def forward(self, images):+ return list(super().forward(images))++ if change == "forward":+ small = _small_edge_detector()+ det = _ListDetector(small.model, small.pre_processor, small.post_processor)+ elif change == "hook":+ det = _small_edge_detector()+ det.register_forward_hook(lambda module, inputs, output: list(output))+ else:+ det = _small_edge_detector()++ def _listed(module, inputs, output):+ return list(output) if module is det else output++ handle = nn.modules.module.register_module_forward_hook(_listed)+ try:+ assert not det._returns_one_tensor_on_export()+ op = det.to_onnx(image_size=24, save=False, dynamo=False)+ finally:+ if change == "global_hook":+ handle.remove()++ assert op.graph.input[0].type.tensor_type.shape.dim[0].dim_value == 1+ assert len(op.graph.output) == 1++ @pytest.mark.device_agnostic+ @pytest.mark.timeout(120)+ @pytest.mark.parametrize("export_kwargs", [*_EACH_EXPORTER, *_DYNAMIC_BATCH])+ def test_onnx_with_a_resize_post_processor_keeps_a_dynamic_batch_without_a_probe_6161(+ self, export_kwargs, monkeypatch+ ):+ # The export replaces a ResizePostProcessor with one resize of the batch, so its output is one tensor: no+ # forward pass reads the output kind, before the export or after it, and a caller's dynamic batch exports too.+ _importorskip_exporter(export_kwargs)++ def _no_probe(module, inputs):+ raise AssertionError("to_onnx ran the detector to read its output kind")++ monkeypatch.setattr(kornia.contrib.edge_detection, "_returns_per_image_outputs", _no_probe)+ monkeypatch.setattr(importlib.import_module("kornia.core.mixin.onnx"), "_returns_per_image_outputs", _no_probe)+ det = _small_edge_detector()++ op = det.to_onnx(image_size=24, save=False, **export_kwargs)++ assert op.graph.input[0].type.tensor_type.shape.dim[0].dim_param+ generator = torch.Generator().manual_seed(0)+ for batch in (1, 3):+ images = torch.rand(batch, 3, 24, 24, generator=generator)+ with torch.no_grad():+ expected = torch.cat(det(images))+ self.assert_close(_run_onnx(op, images), expected, rtol=0.0, atol=1e-5)++ @pytest.mark.device_agnostic+ @pytest.mark.timeout(120)+ @pytest.mark.parametrize("export_kwargs", [*_EACH_EXPORTER, *_DYNAMIC_BATCH])+ def test_onnx_with_a_tensor_post_processor_keeps_a_dynamic_batch_6161(self, export_kwargs):+ # A post-processor of the caller's own that returns one tensor for the batch is read as such: the batch stays+ # dynamic, also through a caller's dynamic batch.+ _importorskip_exporter(export_kwargs)+ det = _small_edge_detector(_DoubledPostProcessor())++ op = det.to_onnx(image_size=24, save=False, **export_kwargs)++ assert op.graph.input[0].type.tensor_type.shape.dim[0].dim_param+ images = torch.rand(3, 3, 24, 24, generator=torch.Generator().manual_seed(0))+ with torch.no_grad():+ expected = det(images)+ self.assert_close(_run_onnx(op, images), expected, rtol=0.0, atol=1e-5)++ @pytest.mark.device_agnostic+ @pytest.mark.timeout(120)+ @pytest.mark.parametrize("export_kwargs", _EACH_EXPORTER)+ def test_onnx_model_only_of_a_per_image_detector_keeps_a_dynamic_batch_6161(self, export_kwargs):+ # Without the pre- and post-processor, the model's tensor output follows any batch, whatever the+ # post-processor returns.+ _importorskip_exporter(export_kwargs)+ det = _small_edge_detector(_PerImageMaps())++ op = det.to_onnx(image_size=24, include_pre_and_post_processor=False, save=False, **export_kwargs)++ assert op.graph.input[0].type.tensor_type.shape.dim[0].dim_param+ images = torch.rand(3, 3, 24, 24, generator=torch.Generator().manual_seed(0))+ with torch.no_grad():+ expected = det.model(images)+ self.assert_close(_run_onnx(op, images), expected, rtol=0.0, atol=1e-5)++ @pytest.mark.device_agnostic+ @pytest.mark.timeout(120)+ @pytest.mark.parametrize("export_kwargs", _EACH_EXPORTER)+ def test_onnx_with_a_delegating_resize_post_processor_exports_one_image_6161(self, export_kwargs):+ # A subclass whose own ``forward`` calls ``ResizePostProcessor.forward`` returns a list eagerly and the maps+ # unchanged under export. The output kind is read outside the export, so it is exported for one image.+ _importorskip_exporter(export_kwargs)+ det = _small_edge_detector(_DelegatingPostProcessor())++ op = det.to_onnx(image_size=16, save=False, **export_kwargs)++ assert op.graph.input[0].type.tensor_type.shape.dim[0].dim_value == 1+ images = torch.rand(1, 3, 16, 16, generator=torch.Generator().manual_seed(0))+ with torch.no_grad():+ expected = det(images)+ self.assert_close(_run_onnx(op, images), expected[0], rtol=0.0, atol=1e-5)++ @pytest.mark.device_agnostic+ @pytest.mark.timeout(120)+ @pytest.mark.parametrize(+ ("post_processor", "override"),+ [+ pytest.param(_DoubledPostProcessor, {"dynamo": False}, id="tensor_torchscript"),+ pytest.param(_PerImageMaps, {"dynamo": False}, id="list_torchscript"),+ pytest.param(+ _PerImageMaps,+ {"dynamo": False, "dynamic_axes": {"input": {0: "batch"}}},+ id="list_torchscript_batch_override",+ ),+ ],+ )+ def test_onnx_rechecks_tensor_output_at_the_tracing_batch_6161(self, post_processor, override, monkeypatch):+ # A list result already requires a fixed batch. A tensor result is checked again on the tracing batch.+ # Neither reading is kept after the export.+ _importorskip_exporter(override)+ calls = _count_probes(monkeypatch)+ det = _small_edge_detector(post_processor())++ if "dynamic_axes" in override:+ with pytest.raises(ValueError, match="returns one output per image"):+ det.to_onnx(image_size=24, save=False, **override)+ else:+ det.to_onnx(image_size=24, save=False, **override)++ assert calls == ["EdgeDetector"] * (2 if post_processor is _DoubledPostProcessor else 1)+ assert "_onnx_per_image_output" not in det.__dict__++ @pytest.mark.device_agnostic+ @pytest.mark.timeout(120)+ def test_direct_mixin_export_of_a_per_image_detector_reads_the_output_kind_6161(self, monkeypatch):+ # ``ONNXExportMixin.to_onnx`` called directly reads nothing before the export, so the check after it runs the+ # detector itself, and rejects the dynamic batch.+ pytest.importorskip("onnx")+ calls = _count_probes(monkeypatch)+ det = _small_edge_detector(_PerImageMaps())++ with pytest.raises(ValueError, match="EdgeDetector returns one output per image"):+ ONNXExportMixin.to_onnx(+ det, input_shape=[-1, 3, 24, 24], pseudo_shape=[1, 3, 24, 24], save=False, dynamo=False+ )++ assert calls == ["EdgeDetector"]++ @pytest.mark.device_agnostic+ @pytest.mark.timeout(120)+ def test_onnx_output_probe_leaves_the_detector_as_it_was_6161(self):+ # The run that reads the output kind is in eval mode, on the model's dtype, without gradients: the batch norm+ # keeps its statistics, each submodule its training flag, and the global random state is given back.+ pytest.importorskip("onnx")++ def _draws_after(export):+ torch.manual_seed(0)+ model = _DrawingNormalisedModel()+ det = EdgeDetector(model, ResizePreProcessor(16, 16), _PerImageMaps()).double().train()+ det.pre_processor.eval() # a mixed state, which ``train()`` would not restore+ running_mean = model.norm.running_mean.clone()+ if export:+ op = det.to_onnx(image_size=24, save=False, dynamo=False)+ assert op.graph.input[0].type.tensor_type.shape.dim[0].dim_value == 1+ assert torch.equal(model.norm.running_mean, running_mean)+ assert model.norm.num_batches_tracked.item() == 0+ assert det.training+ assert model.training+ assert model.norm.training+ assert not det.pre_processor.training+ return torch.rand(8)++ self.assert_close(_draws_after(True), _draws_after(False))+def test_dynamo_returns_the_eager_list(self, device, dtype, torch_optimizer):# Only an export returns the stacked tensor: a compiled detector keeps the per-image list. Under# ``torch.compile`` on torch 2.5.1, ``is_exporting()`` is True (#5037), so it cannot select the export branch.diff --git a/tests/contrib/test_super_resolution.py b/tests/contrib/test_super_resolution.pyindex b8dc36e89..04569916a 100644--- a/tests/contrib/test_super_resolution.py+++ b/tests/contrib/test_super_resolution.py@@ -15,12 +15,16 @@# limitations under the License.#+import importlibimport reimport sys+from typing import Optionalimport pytestimport torch+from torch import nn+import korniafrom kornia.contrib.super_resolution import (RRDBNetBuilder,SmallSRBuilder,@@ -28,8 +32,10 @@ from kornia.contrib.super_resolution import (SuperResolutionConfig,)from kornia.core._compat import torch_version_ge, torch_version_lt+from kornia.models.processors import OutputRangePostProcessor, ResizePreProcessor+from kornia.models.rrdbnet import RRDBNet-from testing.base import BaseTester+from testing.base import DYNAMO_UNAVAILABLE_REASON, BaseTester, dynamo_is_availableclass TestSuperResolutionBuilders(BaseTester):@@ -217,6 +223,427 @@ class TestSuperResolutionBuilders(BaseTester):assert out_dim.dim_value == model.output_image_size+class _PerImageOutputs(nn.Module):+ """A post-processor that returns a list with one ``(1, C, H, W)`` image per input image (#6161)."""++ def forward(self, imgs):+ return [imgs[i : i + 1] for i in range(imgs.shape[0])]+++class _TupleImages(nn.Module):+ """A post-processor that returns a tuple: one image per input image, or a fixed pair of batched images (#6197)."""++ def __init__(self, per_image: bool) -> None:+ super().__init__()+ self.per_image = per_image++ def forward(self, imgs):+ return tuple(imgs.split(1)) if self.per_image else (imgs, 2 * imgs)+++class _ImagesOneByOne(nn.Module):+ """A pre-processor that returns a list of ``(C, H, W)`` images, which ``forward`` runs one at a time (#6161)."""++ def forward(self, imgs):+ return [imgs[i] for i in range(imgs.shape[0])]+++class _Doubled(nn.Module):+ """A post-processor of the caller's own that returns one tensor for the batch."""++ def forward(self, imgs):+ return 2 * imgs+++class _DrawingNormalisedModel(nn.Module):+ """A convolution behind a batch norm, which a forward pass in training mode would update, drawing in any mode."""++ def __init__(self) -> None:+ super().__init__()+ self.conv = nn.Conv2d(3, 3, 3, padding=1)+ self.norm = nn.BatchNorm2d(3)++ def forward(self, x):+ return self.norm(self.conv(x + 0.0 * torch.rand_like(x)))+++def _small_super_resolution(post_processor: nn.Module, pre_processor: Optional[nn.Module] = None) -> SuperResolution:+ """A one-convolution model behind the RRDB builder's identity pre-processor, at a fixed 16 x 16 input."""+ torch.manual_seed(0)+ model = SuperResolution(nn.Conv2d(3, 3, 3, padding=1), pre_processor or nn.Identity(), post_processor)+ model.input_image_size = model.output_image_size = 16+ return model+++def _count_probes(monkeypatch):+ """Count the runs that read the model's output kind, wherever ``to_onnx`` or its check makes them."""+ mixin = importlib.import_module("kornia.core.mixin.onnx")+ probe = mixin._returns_per_image_outputs+ calls = []++ def _counting(module, inputs):+ calls.append(type(module).__name__)+ return probe(module, inputs)++ monkeypatch.setattr(kornia.contrib.super_resolution, "_returns_per_image_outputs", _counting)+ monkeypatch.setattr(mixin, "_returns_per_image_outputs", _counting)+ return calls+++def _run_onnx(op, images):+ ort = pytest.importorskip("onnxruntime")+ session = ort.InferenceSession(op.SerializeToString(), providers=["CPUExecutionProvider"])+ return session.run(None, {"input": images.numpy()})+++def _importorskip_exporter(export_kwargs):+ pytest.importorskip("onnx")+ if export_kwargs.get("dynamo", torch_version_ge(2, 9, 0)):+ pytest.importorskip("onnxscript")+++# One exporter per ID. conftest.py deselects IDs that contain "dynamo" unless KORNIA_TEST_OPTIMIZER is set.+_EACH_EXPORTER = [+ pytest.param({"dynamo": False}, id="torchscript"),+ pytest.param(+ {"dynamo": True},+ id="torch_export",+ marks=pytest.mark.skipif(not dynamo_is_available(), reason=DYNAMO_UNAVAILABLE_REASON),+ ),+]++# A caller's dynamic batch: the TorchScript exporter reads ``dynamic_axes``, the dynamo exporter ``dynamic_shapes``+# from torch 2.9, where ``to_onnx`` declares its own dynamic dimensions with it.+_DYNAMIC_BATCH = [+ pytest.param({"dynamo": False, "dynamic_axes": {"input": {0: "batch"}}}, id="torchscript_batch_override"),+ pytest.param(+ {"dynamo": True, "dynamic_shapes": ({0: "batch"},)},+ id="torch_export_batch_override",+ marks=[+ pytest.mark.skipif(not dynamo_is_available(), reason=DYNAMO_UNAVAILABLE_REASON),+ pytest.mark.skipif(torch_version_lt(2, 9, 0), reason="to_onnx uses dynamic_shapes from torch 2.9"),+ ],+ ),+]++[email protected]_agnostic+class TestSuperResolutionONNXBatch(BaseTester):+ """A post-processor that returns one image per input image fixes the exported batch (#6161)."""++ @pytest.mark.timeout(120)+ @pytest.mark.parametrize("export_kwargs", _EACH_EXPORTER)+ def test_per_image_network_exports_one_image_6197(self, export_kwargs):+ _importorskip_exporter(export_kwargs)+ if export_kwargs["dynamo"] and torch_version_lt(2, 9, 0):+ # As in test_per_image_pre_processor_exports_one_image_6161: on torch 2.5.1 the probe's eager call+ # followed by this dynamo export broke every later dynamo export in the process.+ pytest.skip("torch < 2.9: the dynamo exporter's PythonDispatcher state can break on this graph")+ ort = pytest.importorskip("onnxruntime")+ model = SuperResolution(_PerImageOutputs(), nn.Identity(), nn.Identity())+ model.input_image_size = model.output_image_size = 16+ op = model.to_onnx(save=False, **export_kwargs)+ assert op.graph.input[0].type.tensor_type.shape.dim[0].dim_value == 1+ images = torch.rand(3, 3, 16, 16)+ outputs = _run_onnx(op, images[:1])+ assert len(outputs) == 1+ self.assert_close(torch.from_numpy(outputs[0]), images[:1])+ with pytest.raises(ort.capi.onnxruntime_pybind11_state.InvalidArgument):+ _run_onnx(op, images)++ @pytest.mark.timeout(120)+ @pytest.mark.parametrize("override", _DYNAMIC_BATCH)+ def test_per_image_network_rejects_dynamic_export_6197(self, override, tmp_path):+ _importorskip_exporter(override)+ model = SuperResolution(_PerImageOutputs(), nn.Identity(), nn.Identity())+ model.input_image_size = model.output_image_size = 16+ path = tmp_path / "sr.onnx"+ with pytest.raises(ValueError, match="returns one output per image"):+ model.to_onnx(onnx_name=str(path), **override)+ assert not path.exists()++ @pytest.mark.timeout(120)+ @pytest.mark.parametrize("per_image", [True, False], ids=["per_image_tuple", "batched_pair"])+ def test_tuple_post_processor_6197(self, per_image):+ # A tuple as long as the batch at two batch sizes is one image per input image (#6192) and is exported for+ # one image; a fixed pair of batched images keeps a dynamic batch.+ pytest.importorskip("onnx")+ model = _small_super_resolution(_TupleImages(per_image))++ op = model.to_onnx(save=False, dynamo=False)++ batch = op.graph.input[0].type.tensor_type.shape.dim[0]+ if per_image:+ assert batch.dim_value == 1+ assert len(op.graph.output) == 1+ else:+ assert batch.dim_param+ assert len(op.graph.output) == 2++ @pytest.mark.timeout(120)+ def test_batch_dependent_output_rejects_dynamic_export_6197(self, tmp_path):+ pytest.importorskip("onnx")++ class BatchDependentOutputs(nn.Module):+ def forward(self, images):+ return images if images.shape[0] == 1 else list(images.split(1))++ model = _small_super_resolution(BatchDependentOutputs())+ path = tmp_path / "sr.onnx"+ with pytest.raises(ValueError, match="returns one output per image"):+ model.to_onnx(onnx_name=str(path), dynamo=False)+ assert not path.exists()++ @pytest.mark.parametrize("component", ["model", "pre_processor", "post_processor", "wrapper"])+ @pytest.mark.parametrize("override", ["subclass", "instance"])+ def test_forward_overrides_disable_tensor_shortcut_6197(self, component, override):+ class ListIdentity(nn.Identity):+ def forward(self, images):+ return list(images.split(1))++ class ListSuperResolution(SuperResolution):+ def forward(self, images):+ return list(images.split(1))++ model = SuperResolution(nn.Identity(), nn.Identity(), nn.Identity())+ if component == "wrapper":+ if override == "subclass":+ model = ListSuperResolution(nn.Identity(), nn.Identity(), nn.Identity())+ else:+ model.forward = ListIdentity().forward+ elif override == "subclass":+ setattr(model, component, ListIdentity())+ else:+ getattr(model, component).forward = ListIdentity().forward+ assert not model._returns_one_tensor_without_a_probe()++ @pytest.mark.parametrize("component", ["model", "pre_processor", "post_processor", "wrapper", "nested"])+ @pytest.mark.parametrize("kind", ["forward", "forward_pre"])+ def test_forward_hooks_disable_tensor_shortcut_6197(self, component, kind):+ network = RRDBNet(num_in_ch=3, num_out_ch=3, num_feat=4, num_block=1, num_grow_ch=4, scale=4)+ model = SuperResolution(network, nn.Identity(), nn.Identity())+ assert model._returns_one_tensor_without_a_probe()+ targets = {"wrapper": model, "nested": network.conv_first}+ target = targets.get(component) or getattr(model, component)+ if kind == "forward":+ target.register_forward_hook(lambda module, inputs, output: list(output.split(1)))+ else:+ target.register_forward_pre_hook(lambda module, inputs: inputs)+ assert not model._returns_one_tensor_without_a_probe()++ @pytest.mark.parametrize("kind", ["forward", "forward_pre"])+ def test_global_hooks_disable_tensor_shortcut_6197(self, kind):+ # register_module_forward_hook applies to every module, so it can turn the output into a list too.+ model = SuperResolution(nn.Identity(), nn.Identity(), nn.Identity())+ assert model._returns_one_tensor_without_a_probe()+ if kind == "forward":+ handle = nn.modules.module.register_module_forward_hook(lambda module, inputs, output: output)+ else:+ handle = nn.modules.module.register_module_forward_pre_hook(lambda module, inputs: inputs)+ try:+ assert not model._returns_one_tensor_without_a_probe()+ finally:+ handle.remove()+ assert model._returns_one_tensor_without_a_probe()++ @pytest.mark.parametrize("builder", [RRDBNetBuilder, SmallSRBuilder])+ def test_builders_take_the_tensor_shortcut_6197(self, builder):+ # A builder's model is exported without a probe, which for an RRDB model costs more than the export.+ assert builder.build(pretrained=False)._returns_one_tensor_without_a_probe()++ @pytest.mark.timeout(120)+ def test_plain_callable_processor_is_probed_6197(self):+ # A processor without ``forward`` is not a known one: the model is probed and, returning one tensor, keeps+ # a dynamic batch.+ pytest.importorskip("onnx")+ model = SuperResolution(nn.Conv2d(3, 3, 1), lambda images: images * 1.0, nn.Identity())+ model.input_image_size = model.output_image_size = 16+ assert not model._returns_one_tensor_without_a_probe()++ op = model.to_onnx(save=False, dynamo=False)++ assert op.graph.input[0].type.tensor_type.shape.dim[0].dim_param++ @pytest.mark.timeout(120)+ @pytest.mark.parametrize("export_kwargs", _EACH_EXPORTER)+ def test_per_image_post_processor_exports_one_image_6161(self, export_kwargs):+ # The exporters turn a list into one graph output per traced image. Exported for a dynamic batch, the+ # TorchScript graph returned the traced batch's two images at any batch size, and the dynamo exporter failed;+ # such a model is exported for one image, a batch that ONNX Runtime enforces.+ _importorskip_exporter(export_kwargs)+ ort = pytest.importorskip("onnxruntime")+ model = _small_super_resolution(_PerImageOutputs())+ images = torch.rand(3, 3, 16, 16, generator=torch.Generator().manual_seed(0))++ op = model.to_onnx(save=False, **export_kwargs)++ assert op.graph.input[0].type.tensor_type.shape.dim[0].dim_value == 1+ assert op.graph.output[0].type.tensor_type.shape.dim[0].dim_value == 1+ outputs = _run_onnx(op, images[:1])+ assert len(outputs) == 1+ with torch.no_grad():+ expected = model(images[:1])+ self.assert_close(torch.from_numpy(outputs[0]), expected[0], rtol=0.0, atol=1e-5)+ with pytest.raises(ort.capi.onnxruntime_pybind11_state.InvalidArgument):+ _run_onnx(op, images)++ @pytest.mark.timeout(120)+ @pytest.mark.parametrize("override", _DYNAMIC_BATCH)+ def test_per_image_post_processor_rejects_a_dynamic_batch_6161(self, override, tmp_path):+ # A caller's dynamic batch would give back the traced batch's images at any batch size: the export raises+ # after it runs, before anything is saved, and names the cause.+ _importorskip_exporter(override)+ model = _small_super_resolution(_PerImageOutputs())+ path = tmp_path / "sr.onnx"++ with pytest.raises(ValueError, match="SuperResolution returns one output per image") as info:+ model.to_onnx(onnx_name=str(path), **override)++ assert "OutputRangePostProcessor" in str(info.value)+ assert not path.exists()++ @pytest.mark.timeout(120)+ @pytest.mark.parametrize("export_kwargs", _EACH_EXPORTER)+ @pytest.mark.parametrize(+ "post_processor", [nn.Identity, OutputRangePostProcessor], ids=["identity", "output_range"]+ )+ def test_per_image_pre_processor_exports_one_image_6161(self, post_processor, export_kwargs):+ # A pre-processor that returns a list of images makes ``forward`` run the network one image at a time, and+ # the builders' post-processors pass the list on: such a model is exported for one image too.+ _importorskip_exporter(export_kwargs)+ if export_kwargs["dynamo"] and torch_version_lt(2, 9, 0):+ # Measured on torch 2.5.1 (2.6 to 2.8 not checked), on main as well: after other exports in the process, an+ # eager call of this model followed by its dynamo export can fail with "Hit PythonDispatcher dispatch key+ # but PythonDispatcherTLS was not set", and later dynamo exports in the process with it. Which+ # parametrization fails depends on what ran before, so both are skipped.+ pytest.skip("torch < 2.9: the dynamo exporter's PythonDispatcher state can break on this graph")+ model = _small_super_resolution(post_processor(), _ImagesOneByOne())+ images = torch.rand(3, 3, 16, 16, generator=torch.Generator().manual_seed(0))++ op = model.to_onnx(save=False, **export_kwargs)++ assert op.graph.input[0].type.tensor_type.shape.dim[0].dim_value == 1+ outputs = _run_onnx(op, images[:1])+ assert len(outputs) == 1+ with torch.no_grad():+ expected = model(images[:1])+ self.assert_close(torch.from_numpy(outputs[0]), expected[0], rtol=0.0, atol=1e-5)++ @pytest.mark.timeout(120)+ @pytest.mark.parametrize("override", _DYNAMIC_BATCH)+ @pytest.mark.parametrize(+ "post_processor", [nn.Identity, OutputRangePostProcessor], ids=["identity", "output_range"]+ )+ def test_per_image_pre_processor_rejects_a_dynamic_batch_6161(self, post_processor, override):+ _importorskip_exporter(override)+ model = _small_super_resolution(post_processor(), _ImagesOneByOne())++ with pytest.raises(ValueError, match="SuperResolution returns one output per image"):+ model.to_onnx(save=False, **override)++ @pytest.mark.timeout(120)+ @pytest.mark.parametrize("export_kwargs", [*_EACH_EXPORTER, *_DYNAMIC_BATCH])+ @pytest.mark.parametrize(+ "post_processor", [nn.Identity, OutputRangePostProcessor], ids=["identity", "output_range"]+ )+ @pytest.mark.parametrize(+ "pre_processor", [nn.Identity, lambda: ResizePreProcessor(16, 16)], ids=["identity", "resize"]+ )+ def test_builders_processors_keep_a_dynamic_batch_without_a_probe_6161(+ self, pre_processor, post_processor, export_kwargs, monkeypatch+ ):+ # The builders' pre-processors hand the network one tensor and their post-processors keep it one: no forward+ # pass reads the output kind, before the export or after it, which for an RRDB model would cost more than the+ # export.+ _importorskip_exporter(export_kwargs)++ def _no_probe(module, inputs):+ raise AssertionError("to_onnx ran the model to read its output kind")++ monkeypatch.setattr(kornia.contrib.super_resolution, "_returns_per_image_outputs", _no_probe)+ monkeypatch.setattr(importlib.import_module("kornia.core.mixin.onnx"), "_returns_per_image_outputs", _no_probe)+ model = _small_super_resolution(post_processor(), pre_processor())++ op = model.to_onnx(save=False, **export_kwargs)++ assert op.graph.input[0].type.tensor_type.shape.dim[0].dim_param+ images = torch.rand(3, 3, 16, 16, generator=torch.Generator().manual_seed(0))+ with torch.no_grad():+ expected = model(images)+ self.assert_close(torch.from_numpy(_run_onnx(op, images)[0]), expected, rtol=0.0, atol=1e-5)++ @pytest.mark.timeout(120)+ @pytest.mark.parametrize("export_kwargs", [*_EACH_EXPORTER, *_DYNAMIC_BATCH])+ def test_tensor_post_processor_keeps_a_dynamic_batch_6161(self, export_kwargs):+ # A post-processor of the caller's own that returns one tensor for the batch is read as such: the batch stays+ # dynamic, also through a caller's dynamic batch.+ _importorskip_exporter(export_kwargs)+ model = _small_super_resolution(_Doubled())++ op = model.to_onnx(save=False, **export_kwargs)++ assert op.graph.input[0].type.tensor_type.shape.dim[0].dim_param+ images = torch.rand(3, 3, 16, 16, generator=torch.Generator().manual_seed(0))+ with torch.no_grad():+ expected = model(images)+ self.assert_close(torch.from_numpy(_run_onnx(op, images)[0]), expected, rtol=0.0, atol=1e-5)++ @pytest.mark.timeout(120)+ @pytest.mark.parametrize(+ ("post_processor", "override"),+ [+ pytest.param(_Doubled, {"dynamo": False}, id="tensor_torchscript"),+ pytest.param(_PerImageOutputs, {"dynamo": False}, id="list_torchscript"),+ pytest.param(+ _PerImageOutputs,+ {"dynamo": False, "dynamic_axes": {"input": {0: "batch"}}},+ id="list_torchscript_batch_override",+ ),+ ],+ )+ def test_rechecks_tensor_output_at_the_tracing_batch_6161(self, post_processor, override, monkeypatch):+ # A list result already requires a fixed batch. A tensor result is checked again on the tracing batch.+ # Neither reading is kept after the export.+ _importorskip_exporter(override)+ calls = _count_probes(monkeypatch)+ model = _small_super_resolution(post_processor())++ if "dynamic_axes" in override:+ with pytest.raises(ValueError, match="returns one output per image"):+ model.to_onnx(save=False, **override)+ else:+ model.to_onnx(save=False, **override)++ assert calls == ["SuperResolution"] * (2 if post_processor is _Doubled else 1)+ assert "_onnx_per_image_output" not in model.__dict__++ @pytest.mark.timeout(120)+ def test_output_probe_leaves_the_model_as_it_was_6161(self):+ # The run that reads the output kind is in eval mode, on the network's dtype, without gradients: the batch+ # norm keeps its statistics, each submodule its training flag, and the global random state is given back.+ pytest.importorskip("onnx")++ def _draws_after(export):+ torch.manual_seed(0)+ network = _DrawingNormalisedModel()+ model = SuperResolution(network, nn.Identity(), _PerImageOutputs()).double().train()+ model.input_image_size = model.output_image_size = 16+ model.pre_processor.eval() # a mixed state, which ``train()`` would not restore+ running_mean = network.norm.running_mean.clone()+ if export:+ op = model.to_onnx(save=False, dynamo=False)+ assert op.graph.input[0].type.tensor_type.shape.dim[0].dim_value == 1+ assert torch.equal(network.norm.running_mean, running_mean)+ assert network.norm.num_batches_tracked.item() == 0+ assert model.training+ assert network.training+ assert network.norm.training+ assert not model.pre_processor.training+ return torch.rand(8)++ self.assert_close(_draws_after(True), _draws_after(False))++class TestRRDBNetBuilderWeights:"""Pretrained Real-ESRGAN weights load like every other kornia checkpoint, with no download here."""diff --git a/tests/models/test_object_detector.py b/tests/models/test_object_detector.pyindex d94b96574..7bb2f4479 100644--- a/tests/models/test_object_detector.py+++ b/tests/models/test_object_detector.py@@ -159,7 +159,7 @@ class TestObjectDetector(BaseTester):def test_output_check_keeps_an_image_module_cache(self):# ObjectDetector.to_onnx first runs the detector once to tell a per-image list from one tensor. That run, like# the export's own, leaves the show()/save() cache of an image module inside the detector as it was.- from kornia.contrib.object_detection import _returns_detections_per_image+ from kornia.core.mixin.onnx import _returns_per_image_outputsclass _Pre(kornia.core.ImageModule):def forward(self, x):@@ -182,13 +182,13 @@ class TestObjectDetector(BaseTester):detector = kornia.contrib.object_detection.ObjectDetector(_Model(), pre, _Post())pre(torch.rand(1, 3, 8, 8))cache = pre.__dict__["_output_image"]- assert not _returns_detections_per_image(detector, torch.rand(2, 3, 16, 16))+ assert not _returns_per_image_outputs(detector, torch.rand(2, 3, 16, 16))assert pre.__dict__["_output_image"] is cachedef test_output_check_gives_back_the_random_state(self):# The output check runs the detector in eval mode; a model that still draws there must not consume the# global random state, wherever the check runs, before the export or after it.- from kornia.contrib.object_detection import _returns_detections_per_image+ from kornia.core.mixin.onnx import _returns_per_image_outputsclass _Pre(torch.nn.Module):def forward(self, x):@@ -210,7 +210,7 @@ class TestObjectDetector(BaseTester):detector = kornia.contrib.object_detection.ObjectDetector(_DrawingModel(), _Pre(), _Post())images = torch.rand(2, 3, 16, 16)state = torch.get_rng_state()- assert not _returns_detections_per_image(detector, images)+ assert not _returns_per_image_outputs(detector, images)assert torch.equal(torch.get_rng_state(), state)@pytest.mark.parametrize("exporter", [{}, {"dynamo": False}], ids=["default-exporter", "legacy-exporter"])diff --git a/tests/models/test_rtdetr_onnx.py b/tests/models/test_rtdetr_onnx.pyindex fc10ccd3f..9f801739a 100644--- a/tests/models/test_rtdetr_onnx.py+++ b/tests/models/test_rtdetr_onnx.py@@ -17,6 +17,8 @@"""ONNX export tests for RT-DETR."""+import importlib+import pytestimport torchfrom torch import nn@@ -405,12 +407,52 @@ class _NormalisedDetections(_ScoredDetections):return super().forward(self.norm(images))[email protected](120)+ ("post_processor", "override"),+ [+ pytest.param(_BatchedDetections, {"dynamo": False}, id="batched_torchscript"),+ pytest.param(_PerImageDetections, {"dynamo": False}, id="per_image_torchscript"),+ pytest.param(+ _PerImageDetections,+ {"dynamo": False, "dynamic_axes": {"input": {0: "batch"}}},+ id="per_image_torchscript_batch_override",+ ),+ ],+)+def test_detector_rechecks_tensor_output_at_the_tracing_batch_6161(post_processor, override, monkeypatch):+ """Only a positive list reading can be reused without checking the actual tracing batch."""+ pytest.importorskip("onnx")+ mixin = importlib.import_module("kornia.core.mixin.onnx")+ probe = mixin._returns_per_image_outputs+ calls = []++ def _counting(module, inputs):+ calls.append(type(module).__name__)+ return probe(module, inputs)++ monkeypatch.setattr(+ importlib.import_module("kornia.contrib.object_detection"), "_returns_per_image_outputs", _counting+ )+ monkeypatch.setattr(mixin, "_returns_per_image_outputs", _counting)+ detector = ObjectDetector(_ScoredDetections(), ResizePreProcessor(32, 32), post_processor())++ if "dynamic_axes" in override:+ with pytest.raises(ValueError, match="confidence_filtering=False"):+ detector.to_onnx(image_size=32, save=False, **override)+ else:+ detector.to_onnx(image_size=32, save=False, **override)++ assert calls == ["ObjectDetector"] * (2 if post_processor is _BatchedDetections else 1)+ assert "_onnx_per_image_output" not in detector.__dict__++@pytest.mark.timeout(120)@pytest.mark.parametrize("per_image", [True, False], ids=["per_image", "batched"])def test_detector_output_probe_runs_in_eval_mode_on_the_models_dtype(per_image):- """The forward passes that read the output kind keep statistics and each training flag, in the model's dtype.+ """The forward pass that reads the output kind keeps statistics and each training flag, in the model's dtype.- A batched detector exports a dynamic batch, so ``to_onnx`` runs it a second time for the check of #6111.+ A batched detector exports a dynamic batch, whose check after the export (#6111) probes the tracing input too."""pytest.importorskip("onnx")pytest.importorskip("onnxscript")@@ -493,3 +535,19 @@ def test_resnet_d_onnx_odd_sizes(tmp_path, dynamo):expected = model(images)for actual, fmap in zip(outputs, expected):assert_close(torch.from_numpy(actual), fmap, atol=1e-4, rtol=1e-4)++[email protected](120)+def test_detector_batch_dependent_output_rejects_dynamic_export_6197(tmp_path):+ pytest.importorskip("onnx")++ class BatchDependentDetections(_BatchedDetections):+ def forward(self, logits, boxes, sizes):+ outputs = super().forward(logits, boxes, sizes)+ return outputs if outputs.shape[0] == 1 else list(outputs.unbind(0))++ detector = ObjectDetector(_ScoredDetections(), ResizePreProcessor(32, 32), BatchDependentDetections())+ path = tmp_path / "detector.onnx"+ with pytest.raises(ValueError, match="returns one output per image"):+ detector.to_onnx(image_size=32, onnx_name=str(path), dynamo=False)+ assert not path.exists()diff --git a/tests/onnx/test_object_detector_output.py b/tests/onnx/test_object_detector_output.pyindex d251b0a1b..cfcb1fb8b 100644--- a/tests/onnx/test_object_detector_output.py+++ b/tests/onnx/test_object_detector_output.py@@ -20,9 +20,10 @@ import pytestimport torchfrom torch import nn-from kornia.contrib.object_detection import ObjectDetector, _returns_detections_per_image+from kornia.contrib.object_detection import ObjectDetectorfrom kornia.core import ImageModulefrom kornia.core._compat import torch_version_lt+from kornia.core.mixin.onnx import _returns_per_image_outputsfrom kornia.models.processors import ResizePreProcessorfrom testing.base import DYNAMO_UNAVAILABLE_REASON, BaseTester, dynamo_is_available@@ -70,7 +71,7 @@ class TestObjectDetectorOutputSequence(BaseTester):)def test_probe(self, batch, output_kind, expected):detector = _detector(output_kind)- assert _returns_detections_per_image(detector, torch.rand(batch, 3, 16, 16)) is expected+ assert _returns_per_image_outputs(detector, torch.rand(batch, 3, 16, 16)) is expected@pytest.mark.parametrize("dynamo", [False, True])@pytest.mark.parametrize("output_kind", ["list", "tuple"])@@ -154,7 +155,7 @@ class TestObjectDetectorOutputSequence(BaseTester):detector = ObjectDetector(RandomScored(), ResizePreProcessor(16, 16), _Post("tuple")).train()images = torch.rand(1, 3, 16, 16)state = torch.get_rng_state().clone()- assert _returns_detections_per_image(detector, images)+ assert _returns_per_image_outputs(detector, images)assert torch.equal(state, torch.get_rng_state())assert all(module.training for module in detector.modules())@@ -168,7 +169,7 @@ class TestObjectDetectorOutputSequence(BaseTester):pre(torch.rand(1, 3, 8, 8))cache = pre.__dict__["_output_image"]- assert _returns_detections_per_image(detector, torch.rand(1, 3, 16, 16))+ assert _returns_per_image_outputs(detector, torch.rand(1, 3, 16, 16))assert pre.__dict__["_output_image"] is cachedef test_tuple_probe_accepts_contiguous_only_preprocessor(self):@@ -180,4 +181,4 @@ class TestObjectDetectorOutputSequence(BaseTester):detector = ObjectDetector(_Scored(), FlattenPre(), _Post("tuple"))images = torch.rand(1, 3, 16, 16)assert len(detector(images)) == 1- assert _returns_detections_per_image(detector, images)+ assert _returns_per_image_outputs(detector, images)