Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

fix(onnx): EdgeDetector exports maps at the input's size; static batch for MobileSAM on the legacy exporter; RT-DETR output names (#6135)

Dmytro Mishkin88099f28d191
diff --git a/changelog.d/6135.breaking.md b/changelog.d/6135.breaking.md
new file mode 100644
index 000000000..23e6d2081
--- /dev/null
+++ b/changelog.d/6135.breaking.md
@@ -0,0 +1,14 @@
+Two `to_onnx` exports change in ways a caller can see:
+
+- An `EdgeDetector` whose `ResizePostProcessor` resizes with `interpolation_mode="area"` now raises a `ValueError` in
+ `to_onnx` with the pre- and post-processor, and so does a direct `torch.onnx.export(detector, ...)` on the
+ TorchScript exporter and, from torch 2.9, on the dynamo exporter (inside that exporter's own error). It used to export
+ a graph that returned the maps at the pre-processor's size. `"area"` resizing is adaptive average pooling, which
+ cannot be exported to the input's size: build the post-processor with `"bilinear"`, `"bicubic"`, `"nearest"` or
+ `"nearest-exact"` to export the detector.
+ Eager `forward` with `"area"` is unchanged.
+- `ObjectDetector.to_onnx(include_pre_and_post_processor=False)` of an RT-DETR model names its outputs `pred_logits`
+ and `pred_boxes`. The logits used to be the graph's `output`, and the boxes came out under an exporter-generated
+ name, such as `2814` from the TorchScript exporter, so code that reads `output` by name, for example
+ `session.run(["output"], ...)`, is now refused by ONNX Runtime. Read `pred_logits` instead, or pass `output_names`
+ to `to_onnx` to choose both names.
diff --git a/changelog.d/6135.fixed.md b/changelog.d/6135.fixed.md
new file mode 100644
index 000000000..27e666e37
--- /dev/null
+++ b/changelog.d/6135.fixed.md
@@ -0,0 +1,22 @@
+ONNX exports of `EdgeDetector`, MobileSAM and RT-DETR declare and return what they compute:
+
+- `EdgeDetector.to_onnx` with the pre- and post-processor exports a graph whose edge maps have the input's size, as
+ eager `forward` returns them. The graph returned the maps at the pre-processor's size (352 x 352 for the default
+ builder) whatever the input, and only warned that `ResizePostProcessor` is not exported. With a `ResizePostProcessor`
+ in `"bilinear"`, `"bicubic"`, `"nearest"` or `"nearest-exact"` mode it now returns one `(B, 1, H, W)` tensor, resized
+ with that mode: the `torch.cat` of the eager per-image list. A direct `torch.onnx.export(detector, ...)` gives the
+ same graph on the TorchScript exporter and, from torch 2.9, on the dynamo exporter. `image_size` is documented as the
+ graph's input size, which the maps have too: the pre-processor keeps the size it was built with. Eager `forward` and
+ `ResizePostProcessor` are unchanged, and a `ResizePostProcessor` subclass that overrides `forward` is exported as its
+ `forward` computes.
+- `Sam.to_onnx` of a MobileSAM (TinyViT image encoder) on the TorchScript exporter, the default before torch 2.9 or
+ `dynamo=False`, traces the encoder at the batch of `pseudo_shape` (1 by default) and declares that batch static, so
+ the graph states the one batch it runs at. It declared a dynamic batch, but ran only at the traced batch. Other
+ encoders, and the dynamo exporter, keep a dynamic batch.
+- `ObjectDetector.to_onnx(include_pre_and_post_processor=False)` names both outputs of an RT-DETR model, `pred_logits`
+ and `pred_boxes` (now declared once as `RTDETR.ONNX_OUTPUT_NAMES`), each with the input's dynamic batch, and keeps the
+ detector's dynamic height and width for `image_size=None`. Only the logits were named (`output`), and the boxes came
+ out under an exporter-generated name, such as `2814` from the TorchScript exporter. A caller's `output_names` take
+ their place, with the same batch; a model that declares no output names keeps the single `output`.
+ `RTDETR.to_onnx` given its own `output_names` declares the input's dynamic batch on them too; it declared it on
+ `pred_logits` and `pred_boxes`, which the graph then did not have.
diff --git a/kornia/contrib/edge_detection.py b/kornia/contrib/edge_detection.py
index 91665a91e..fc0a38555 100644
--- a/kornia/contrib/edge_detection.py
+++ b/kornia/contrib/edge_detection.py
@@ -28,6 +28,7 @@ from kornia.core.external import PILImage as Image
from kornia.core.external import onnx
from kornia.core.mixin.onnx import ONNXExportMixin
from kornia.enhance.normalize import Normalize
+from kornia.geometry.transform import resize
from kornia.models.base import ModelBase
from kornia.models.dexined import DexiNed
from kornia.models.processors import ResizePostProcessor, ResizePreProcessor
@@ -56,6 +57,8 @@ class EdgeDetector(ModelBase, ONNXExportMixin):
"""
name: str = "edge_detection"
+ # Set by ``to_onnx`` for the duration of its export, read by ``forward`` (see there).
+ _exporting_to_onnx: bool = False
def __init__(
self,
@@ -112,13 +115,59 @@ class EdgeDetector(ModelBase, ONNXExportMixin):
Returns:
A list with one output of shape :math:`(1, 1, H, W)` per input image, resized back to that image's size.
For a detector from :py:class:`~kornia.contrib.edge_detection.EdgeDetectorBuilder`, it holds edge
- probabilities in :math:`[0, 1]`.
+ probabilities in :math:`[0, 1]`. Under an ONNX export with a ``ResizePostProcessor``, one
+ :math:`(B, 1, H, W)` tensor at the input's size instead, see :meth:`to_onnx`.
+
+ Raises:
+ ValueError: Under an ONNX export through :meth:`to_onnx`, or a direct one on the TorchScript exporter or,
+ from torch 2.9, the dynamo exporter, if the ``ResizePostProcessor`` resizes with ``"area"``.
"""
+ if (
+ (self._exporting_to_onnx or torch.onnx.is_in_onnx_export())
+ and isinstance(images, torch.Tensor)
+ and self._resizes_back_on_export()
+ ):
+ # An exported graph returns one tensor, so the maps of a batch, whose images share a size, are resized
+ # back together: the ``torch.cat`` of the eager list. The size is read from the input, a symbolic size
+ # under every exporter, not from the pre-processor's ``original_sizes``, whose values
+ # ``ResizePostProcessor`` reads with ``.tolist()``. The flag covers the dynamo exporter below torch 2.9,
+ # where ``is_in_onnx_export()`` is False; ``is_exporting()`` would also be True under ``torch.compile``
+ # there (#5037).
+ interpolation = self._export_interpolation()
+ height, width = images.shape[-2:]
+ out_images = self.model(self.pre_processor(images)[0])
+ return resize(out_images, (height, width), interpolation=interpolation)
images, image_sizes = self.pre_processor(images)
out_images = self.model(images)
return self.post_processor(out_images, image_sizes)
+ def _resizes_back_on_export(self) -> bool:
+ """Whether an export replaces the post-processor: a ``ResizePostProcessor`` that keeps its own ``forward``.
+
+ A subclass that overrides ``forward`` is exported as that ``forward`` computes.
+ """
+ return (
+ isinstance(self.post_processor, ResizePostProcessor)
+ and type(self.post_processor).forward is ResizePostProcessor.forward
+ )
+
+ def _export_interpolation(self) -> str:
+ """The post-processor's interpolation mode, which an export resizes the maps back with.
+
+ Raises:
+ ValueError: For ``"area"``, which an exported graph cannot compute at the input's size.
+ """
+ interpolation = self.post_processor.interpolation_mode
+ if interpolation == "area":
+ raise ValueError(
+ 'A ResizePostProcessor with interpolation_mode="area" cannot be exported with the input\'s size: '
+ '"area" resizing is adaptive average pooling, which an exported graph cannot compute to a size known '
+ 'only at run time. Build the post-processor with "bilinear", "bicubic", "nearest" or "nearest-exact" '
+ "for export."
+ )
+ return interpolation
+
def visualize(
self,
images: Union[torch.Tensor, list[torch.Tensor]],
@@ -178,36 +227,56 @@ class EdgeDetector(ModelBase, ONNXExportMixin):
) -> onnx.ModelProto:
"""Export the current edge detection model to an ONNX model file.
+ The graph takes one :math:`(B, 3, H, W)` tensor. With the pre- and post-processor and a
+ ``ResizePostProcessor``, it returns the edge maps of the batch as one :math:`(B, 1, H, W)` tensor at the
+ input's size, resized with the post-processor's ``"bilinear"``, ``"bicubic"``, ``"nearest"`` or
+ ``"nearest-exact"`` mode: the ``torch.cat`` of the list that :meth:`forward` returns. A subclass of
+ ``ResizePostProcessor`` that overrides ``forward`` is exported as its ``forward`` computes. Export through
+ this method rather than ``torch.onnx.export(detector, ...)``: below torch 2.9, a direct
+ ``torch.onnx.export(..., dynamo=True)`` traces the eager per-image list instead.
+
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"``, for
+ example ``"kornia_dexined_352.onnx"``.
image_size:
- The size to which input images will be resized during preprocessing.
- If None, image_size will be dynamic. For DexiNed, recommended scale is 352.
+ 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.
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.
+ 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.
+
"""
if onnx_name is None:
onnx_name = f"kornia_{self.name}_{image_size}.onnx"
-
- 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,
- )
+ 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
+
+ previous = self._exporting_to_onnx
+ self._exporting_to_onnx = True
+ try:
+ 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,
+ )
+ finally:
+ self._exporting_to_onnx = previous
class EdgeDetectorBuilder:
diff --git a/kornia/contrib/object_detection.py b/kornia/contrib/object_detection.py
index ccd5fe0db..8e52de393 100644
--- a/kornia/contrib/object_detection.py
+++ b/kornia/contrib/object_detection.py
@@ -34,6 +34,7 @@ from kornia.core.mixin.onnx import (
_first_floating_tensor,
_preserved_output_caches,
_to_floating,
+ _uses_dynamic_shapes,
)
from kornia.image.draw import draw_rectangle
from kornia.models.base import ModelBase
@@ -280,6 +281,10 @@ class ObjectDetector(ModelBase, ONNXExportMixin):
the detector returns is read from one forward pass at the export size, in eval mode and without gradients.
Build an RT-DETR detector with ``confidence_filtering=False`` to export a batch of any size.
+ 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
+ under those names, each with a dynamic batch; any other model has one output, ``output``.
+
"""
if onnx_name is None:
onnx_name = f"kornia_{self.name}_{image_size}.onnx"
@@ -289,11 +294,24 @@ class ObjectDetector(ModelBase, ONNXExportMixin):
batch = -1
if include_pre_and_post_processor and _returns_detections_per_image(self, torch.rand(pseudo_shape)):
batch = 1
+ input_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)
+ if output_names:
+ # The bare model's outputs by name, each with a dynamic batch: listed in ``dynamic_axes`` for the
+ # TorchScript exporter, derived by the dynamo exporter from the input's dynamic dimensions.
+ if kwargs.get("output_names") is None: # absent, or ``torch.onnx.export``'s own default of None
+ kwargs["output_names"] = list(output_names)
+ if not _uses_dynamic_shapes(kwargs) and "dynamic_axes" not in kwargs and "dynamic_shapes" not in kwargs:
+ input_axes = {i: f"dim_{i}" for i, dim in enumerate(input_shape) if dim == -1}
+ # Keyed by the names the graph gets, the caller's if given.
+ 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=[batch, 3, image_size or -1, image_size or -1],
+ input_shape=input_shape,
output_shape=[-1, -1, 6],
pseudo_shape=pseudo_shape,
model=self if include_pre_and_post_processor else self.model,
diff --git a/kornia/core/mixin/onnx.py b/kornia/core/mixin/onnx.py
index 4d0d101fe..758635d4f 100644
--- a/kornia/core/mixin/onnx.py
+++ b/kornia/core/mixin/onnx.py
@@ -184,6 +184,14 @@ def _to_floating(value: Any, reference: torch.Tensor) -> Any:
return value
+def _uses_dynamic_shapes(export_kwargs: dict[str, Any]) -> bool:
+ """Whether ``ONNXExportMixin.to_onnx`` declares its dynamic dimensions with ``dynamic_shapes``.
+
+ It does on the dynamo exporter from torch 2.9, which warns on ``dynamic_axes``, and uses ``dynamic_axes`` otherwise.
+ """
+ return bool(torch_version_ge(2, 9, 0) and export_kwargs.get("dynamo", True))
+
+
@contextlib.contextmanager
def _eval_mode(module: Any) -> Iterator[None]:
"""Put ``module`` in eval mode for the block, then restore the training flag of each of its submodules."""
@@ -379,8 +387,7 @@ class ONNXExportMixin:
"output_names": ["output"],
}
if "dynamic_axes" not in kwargs and "dynamic_shapes" not in kwargs:
- # The dynamo exporter (the default from torch 2.9) takes ``dynamic_shapes`` and warns on ``dynamic_axes``.
- if torch_version_ge(2, 9, 0) and kwargs.get("dynamo", True):
+ if _uses_dynamic_shapes(kwargs):
default_args["dynamic_shapes"] = self._create_dynamic_shapes(input_shape, dummy_input)
else:
default_args["dynamic_axes"] = self._create_dynamic_axes(input_shape, output_shape)
diff --git a/kornia/models/rt_detr/model.py b/kornia/models/rt_detr/model.py
index 678d29e81..23195ee83 100644
--- a/kornia/models/rt_detr/model.py
+++ b/kornia/models/rt_detr/model.py
@@ -22,7 +22,7 @@ from __future__ import annotations
import re
from dataclasses import dataclass
from enum import Enum
-from typing import Any, Optional
+from typing import Any, ClassVar, Optional
import torch
@@ -149,6 +149,10 @@ class RTDETRConfig:
class RTDETR(ONNXExportMixin, ModelBase[RTDETRConfig]):
"""RT-DETR Object Detection model, as described in https://arxiv.org/abs/2304.08069."""
+ # The names of the ONNX outputs, in the order :meth:`forward` returns them. ``to_onnx`` and
+ # :meth:`kornia.contrib.object_detection.ObjectDetector.to_onnx` without pre- and post-processing use them.
+ ONNX_OUTPUT_NAMES: ClassVar[tuple[str, ...]] = ("pred_logits", "pred_boxes")
+
def __init__(self, backbone: ResNetD | PPHGNetV2, encoder: HybridEncoder, decoder: RTDETRHead):
"""Construct RT-DETR Object Detection model.
@@ -352,14 +356,12 @@ class RTDETR(ONNXExportMixin, ModelBase[RTDETRConfig]):
``onnx.ModelProto`` of the exported model.
"""
- kwargs.setdefault("output_names", ["pred_logits", "pred_boxes"])
+ if kwargs.get("output_names") is None: # absent, or ``torch.onnx.export``'s own default of None
+ kwargs["output_names"] = list(self.ONNX_OUTPUT_NAMES)
+ # keyed by the names the graph gets, the caller's if given
kwargs.setdefault(
"dynamic_axes",
- {
- "input": {0: "batch"},
- "pred_logits": {0: "batch"},
- "pred_boxes": {0: "batch"},
- },
+ {"input": {0: "batch"}, **{name: {0: "batch"} for name in kwargs["output_names"]}},
)
if pseudo_shape is None:
pseudo_shape = [1, 3, 640, 640]
diff --git a/kornia/models/sam/model.py b/kornia/models/sam/model.py
index eea7623be..d683b980e 100644
--- a/kornia/models/sam/model.py
+++ b/kornia/models/sam/model.py
@@ -33,6 +33,7 @@ from typing import Any, Optional
import torch
+from kornia.core._compat import torch_version_ge
from kornia.core.check import KORNIA_CHECK, KORNIA_CHECK_SHAPE
from kornia.core.download import hf_url
from kornia.core.mixin.onnx import ONNXExportMixin
@@ -288,7 +289,11 @@ class Sam(ONNXExportMixin, ModelBase[SamConfig]):
``"Kornia-Sam-ImageEncoder.onnx"``.
pseudo_shape: Concrete input shape used to trace the encoder, e.g.
``[1, 3, 1024, 1024]``. Defaults to ``[1, 3, 1024, 1024]``. The batch is
- exported as dynamic, so a batch below 2 is traced at 2.
+ exported as dynamic, so a batch below 2 is traced at 2. A TinyViT image encoder
+ (MobileSAM) on the legacy TorchScript exporter (the default before torch 2.9, or
+ ``dynamo=False``) is the exception: that graph runs at the traced batch only, so it is
+ traced at this shape's batch and declares it static. With a caller's ``dynamic_axes``, such an
+ encoder is still traced at this shape's batch and runs at that batch only.
save: Whether to write the model to disk. Default ``True``.
**kwargs: Additional keyword arguments forwarded to
:func:`torch.onnx.export`.
@@ -302,16 +307,17 @@ class Sam(ONNXExportMixin, ModelBase[SamConfig]):
if pseudo_shape is None:
pseudo_shape = [1, 3, 1024, 1024]
kwargs.setdefault("output_names", ["image_embeddings"])
- kwargs.setdefault(
- "dynamic_axes",
- {
- "input": {0: "batch"},
- "image_embeddings": {0: "batch"},
- },
- )
+ input_shape = [-1, 3, -1, -1]
+ dynamic_axes: dict[str, dict[int, str]] = {"input": {0: "batch"}, "image_embeddings": {0: "batch"}}
+ if isinstance(self.image_encoder, TinyViT) and not kwargs.get("dynamo", torch_version_ge(2, 9, 0)):
+ # The TorchScript exporter keeps the traced batch in TinyViT's attention reshapes, so the graph runs at
+ # that batch only: a fixed batch is traced at the pseudo shape's size rather than at 2, and declared.
+ input_shape = [pseudo_shape[0], 3, -1, -1]
+ dynamic_axes = {}
+ kwargs.setdefault("dynamic_axes", dynamic_axes)
return super().to_onnx(
onnx_name=onnx_name,
- input_shape=[-1, 3, -1, -1],
+ input_shape=input_shape,
pseudo_shape=pseudo_shape,
model=self.image_encoder,
save=save,
diff --git a/tests/contrib/test_edge_detector.py b/tests/contrib/test_edge_detector.py
index 927b67434..300645e47 100644
--- a/tests/contrib/test_edge_detector.py
+++ b/tests/contrib/test_edge_detector.py
@@ -15,14 +15,59 @@
# limitations under the License.
#
+from typing import Optional
+
import pytest
import torch
+from torch import nn
import kornia
-from kornia.contrib.edge_detection import EdgeDetectorBuilder
+from kornia.contrib.edge_detection import EdgeDetector, EdgeDetectorBuilder
+from kornia.core._compat import torch_version_ge, torch_version_lt
from kornia.models.dexined import DexiNed
+from kornia.models.processors import ResizePostProcessor, ResizePreProcessor
+
+from testing.base import DYNAMO_UNAVAILABLE_REASON, BaseTester, dynamo_is_available
+
+try:
+ from onnxruntime.capi.onnxruntime_pybind11_state import Fail as _OrtFail
+ from onnxruntime.capi.onnxruntime_pybind11_state import InvalidArgument as _OrtInvalidArgument
+ from onnxruntime.capi.onnxruntime_pybind11_state import InvalidGraph as _OrtInvalidGraph
+except ImportError: # the ONNX tests skip without onnxruntime
+ _OrtFail = _OrtInvalidArgument = _OrtInvalidGraph = RuntimeError
+
+# The interpolation modes an exported ``ResizePostProcessor`` resizes with; "area" raises, see its own test.
+_EXPORTABLE_MODES = ["nearest", "bilinear", "bicubic", "nearest-exact"]
+
+# ``to_onnx`` without ``dynamo=``: the dynamo exporter from torch 2.9, the TorchScript exporter before it.
+_EXPORTERS = [pytest.param({}, id="default"), pytest.param({"dynamo": False}, id="legacy")]
+
+
+def _run_onnx(op, x):
+ ort = pytest.importorskip("onnxruntime")
+ session = ort.InferenceSession(op.SerializeToString(), providers=["CPUExecutionProvider"])
+ return torch.from_numpy(session.run(None, {session.get_inputs()[0].name: x.numpy()})[0])
+
+
+def _small_edge_detector(post_processor: Optional[nn.Module] = None) -> EdgeDetector:
+ """A detector whose model is one convolution and a sigmoid, behind the builder's resize pre- and post-processor."""
+ torch.manual_seed(0)
+ model = nn.Sequential(nn.Conv2d(3, 1, 3, padding=1), nn.Sigmoid())
+ return EdgeDetector(model, ResizePreProcessor(16, 16), post_processor or ResizePostProcessor())
+
+
+class _DoubledPostProcessor(ResizePostProcessor):
+ """A ``ResizePostProcessor`` subclass with its own ``forward``: the maps at the model's size, doubled."""
+
+ def forward(self, imgs, original_sizes):
+ return 2 * imgs
+
+
+class _NearestPostProcessor(ResizePostProcessor):
+ """A ``ResizePostProcessor`` subclass that keeps its ``forward``: nearest resizing by default."""
-from testing.base import BaseTester
+ def __init__(self) -> None:
+ super().__init__("nearest")
class TestEdgeDetector(BaseTester):
@@ -82,6 +127,284 @@ class TestEdgeDetector(BaseTester):
eager = det.model(img)
self.assert_close(exported, eager, rtol=0.0, atol=1e-4)
+ def test_list_of_two_sizes_returns_a_map_per_image_at_its_size(self, device, dtype):
+ det = EdgeDetectorBuilder.build(pretrained=False, image_size=32).to(device, dtype)
+ generator = torch.Generator().manual_seed(0)
+ images = [torch.rand(3, h, w, generator=generator).to(device, dtype) for h, w in [(40, 72), (33, 47)]]
+
+ out = det(images)
+
+ assert isinstance(out, list)
+ assert [tuple(edge_map.shape) for edge_map in out] == [(1, 1, 40, 72), (1, 1, 33, 47)]
+ for image, edge_map in zip(images, out):
+ self.assert_close(edge_map, det(image[None])[0])
+
+ @pytest.mark.device_agnostic
+ @pytest.mark.timeout(120)
+ @pytest.mark.parametrize("export_kwargs", _EXPORTERS)
+ @pytest.mark.parametrize("interpolation", _EXPORTABLE_MODES)
+ @pytest.mark.parametrize(
+ ("image_size", "shapes"),
+ [
+ # different heights and widths, an odd size, sizes above and below the pre-processor's 32
+ (None, [(1, 3, 40, 72), (2, 3, 33, 47), (3, 3, 64, 48), (1, 3, 20, 28)]),
+ # a graph input size other than the pre-processor's, which keeps its own
+ (48, [(1, 3, 48, 48), (2, 3, 48, 48), (3, 3, 48, 48)]),
+ ],
+ ids=["dynamic_size", "fixed_size"],
+ )
+ def test_onnx_with_pre_and_post_processor_matches_eager(self, export_kwargs, interpolation, image_size, shapes):
+ # The graph returns one (B, 1, H, W) tensor at the input's size, resized with the post-processor's mode:
+ # ``torch.cat`` of the eager per-image list.
+ pytest.importorskip("onnx")
+ if export_kwargs.get("dynamo", torch_version_ge(2, 9, 0)):
+ pytest.importorskip("onnxscript")
+ torch.manual_seed(0)
+ det = EdgeDetectorBuilder.build(pretrained=False, image_size=32)
+ det.post_processor = ResizePostProcessor(interpolation)
+ op = det.to_onnx(image_size=image_size, save=False, **export_kwargs)
+
+ generator = torch.Generator().manual_seed(0)
+ for shape in shapes:
+ images = torch.rand(*shape, generator=generator)
+ with torch.no_grad():
+ expected = torch.cat(det(images))
+ assert expected.shape == (shape[0], 1, *shape[2:])
+ self.assert_close(_run_onnx(op, images), expected, rtol=0.0, atol=1e-4)
+
+ @pytest.mark.device_agnostic
+ @pytest.mark.timeout(120)
+ @pytest.mark.skipif(not dynamo_is_available(), reason=DYNAMO_UNAVAILABLE_REASON)
+ @pytest.mark.parametrize(
+ "image_size",
+ [
+ pytest.param(
+ None,
+ id="dynamic_size",
+ marks=[
+ pytest.mark.xfail(
+ torch_version_lt(2, 6, 0),
+ reason=(
+ "the dynamo exporter of torch 2.5.1 writes a resize to a symbolic size, as "
+ "F.interpolate(x, size=y.shape[-2:]) alone, as a Concat of 0-d sizes, which ONNX Runtime "
+ "rejects as INVALID_GRAPH"
+ ),
+ raises=_OrtInvalidGraph,
+ strict=True,
+ ),
+ pytest.mark.xfail(
+ torch_version_ge(2, 6, 0) and torch_version_lt(2, 9, 0),
+ reason=(
+ "not checked on torch 2.6 to 2.8, whose dynamo exporter may write a resize to a symbolic "
+ "size as torch 2.5.1's does, which ONNX Runtime rejects"
+ ),
+ raises=(_OrtInvalidGraph, _OrtFail, _OrtInvalidArgument),
+ strict=False,
+ ),
+ ],
+ ),
+ pytest.param(24, id="fixed_size"),
+ ],
+ )
+ def test_onnx_on_the_torch_export_exporter_returns_the_input_size(self, image_size):
+ # Below torch 2.9, ``dynamo=True`` selects the exporter on which ``torch.onnx.is_in_onnx_export()`` is False,
+ # so only the flag that ``to_onnx`` sets selects the export branch there. A one-convolution model: that
+ # exporter cannot translate DexiNed's batch norm on torch 2.5.1.
+ pytest.importorskip("onnx")
+ pytest.importorskip("onnxscript")
+ det = _small_edge_detector()
+ op = det.to_onnx(image_size=image_size, save=False, dynamo=True)
+
+ generator = torch.Generator().manual_seed(0)
+ shapes = [(1, 3, 20, 28), (3, 3, 33, 18)] if image_size is None else [(1, 3, 24, 24), (3, 3, 24, 24)]
+ for shape in shapes:
+ images = torch.rand(*shape, 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(
+ "dynamo",
+ [
+ pytest.param(False, id="legacy"),
+ pytest.param(
+ True,
+ id="torch_export",
+ marks=pytest.mark.skipif(
+ torch_version_lt(2, 9, 0),
+ reason="below torch 2.9 a direct export on that exporter takes the eager path; use to_onnx",
+ ),
+ ),
+ ],
+ )
+ def test_direct_torch_onnx_export_matches_eager(self, tmp_path, dynamo):
+ # ``torch.onnx.export(detector, ...)`` without ``to_onnx``: ``torch.onnx.is_in_onnx_export()`` alone selects
+ # the export branch, on the legacy exporter and on the dynamo exporter from torch 2.9.
+ pytest.importorskip("onnx")
+ if dynamo:
+ pytest.importorskip("onnxscript")
+ det = _small_edge_detector().eval()
+ path = tmp_path / "edge_detector.onnx"
+ traced = torch.rand(2, 3, 24, 32, generator=torch.Generator().manual_seed(1))
+ if dynamo:
+ dims = {0: "batch", 2: "height", 3: "width"}
+ torch.onnx.export(det, (traced,), str(path), dynamo=True, input_names=["input"], dynamic_shapes=(dims,))
+ else:
+ axes = {0: "batch", 2: "height", 3: "width"}
+ torch.onnx.export(
+ det,
+ (traced,),
+ str(path),
+ dynamo=False,
+ opset_version=18,
+ input_names=["input"],
+ output_names=["output"],
+ dynamic_axes={"input": axes, "output": axes},
+ )
+ onnx = pytest.importorskip("onnx")
+ op = onnx.load(str(path))
+
+ generator = torch.Generator().manual_seed(0)
+ for shape in [(1, 3, 20, 28), (3, 3, 33, 18)]:
+ images = torch.rand(*shape, 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", _EXPORTERS)
+ def test_onnx_with_an_area_post_processor_raises(self, export_kwargs):
+ # "area" resizing is adaptive average pooling, which cannot be exported to a size known only at run time:
+ # the legacy exporter fails on it and the dynamo exporter's graph is right only at the traced size.
+ pytest.importorskip("onnx")
+ if export_kwargs.get("dynamo", torch_version_ge(2, 9, 0)):
+ pytest.importorskip("onnxscript")
+ det = _small_edge_detector(ResizePostProcessor("area"))
+ images = torch.rand(2, 3, 20, 28, generator=torch.Generator().manual_seed(0))
+
+ with pytest.raises(ValueError, match='"area"'):
+ det.to_onnx(image_size=None, save=False, **export_kwargs)
+ with pytest.raises(ValueError, match='"area"'):
+ det.to_onnx(image_size=24, save=False, **export_kwargs)
+
+ # eager resizing with "area" is unchanged
+ out = det(images)
+ assert isinstance(out, list)
+ assert [tuple(edge_map.shape) for edge_map in out] == [(1, 1, 20, 28)] * 2
+ assert det._exporting_to_onnx is False
+
+ @pytest.mark.device_agnostic
+ @pytest.mark.timeout(120)
+ @pytest.mark.parametrize("export_kwargs", _EXPORTERS)
+ def test_onnx_keeps_the_forward_of_a_post_processor_subclass(self, export_kwargs):
+ # Only ``ResizePostProcessor.forward`` itself is replaced by the export branch: a subclass that overrides it is
+ # exported as its own ``forward`` computes.
+ pytest.importorskip("onnx")
+ if export_kwargs.get("dynamo", torch_version_ge(2, 9, 0)):
+ pytest.importorskip("onnxscript")
+ det = _small_edge_detector(_DoubledPostProcessor())
+ op = det.to_onnx(image_size=None, save=False, **export_kwargs)
+
+ generator = torch.Generator().manual_seed(0)
+ for shape in [(1, 3, 20, 28), (3, 3, 33, 18)]:
+ images = torch.rand(*shape, generator=generator)
+ with torch.no_grad():
+ expected = det(images)
+ assert expected.shape == (shape[0], 1, 16, 16)
+ 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", _EXPORTERS)
+ def test_onnx_resizes_back_for_a_post_processor_subclass_that_keeps_forward(self, export_kwargs):
+ # A subclass without its own ``forward`` resizes as ``ResizePostProcessor`` does, so the export branch replaces
+ # it too, with the subclass's mode.
+ pytest.importorskip("onnx")
+ if export_kwargs.get("dynamo", torch_version_ge(2, 9, 0)):
+ pytest.importorskip("onnxscript")
+ det = _small_edge_detector(_NearestPostProcessor())
+ op = det.to_onnx(image_size=None, save=False, **export_kwargs)
+
+ generator = torch.Generator().manual_seed(0)
+ for shape in [(1, 3, 20, 28), (3, 3, 33, 18)]:
+ images = torch.rand(*shape, 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(
+ "dynamo",
+ [
+ pytest.param(False, id="legacy"),
+ pytest.param(
+ True,
+ id="torch_export",
+ marks=pytest.mark.skipif(
+ torch_version_lt(2, 9, 0),
+ reason="below torch 2.9 a direct export on that exporter takes the eager path; use to_onnx",
+ ),
+ ),
+ ],
+ )
+ def test_direct_torch_onnx_export_with_an_area_post_processor_raises(self, tmp_path, dynamo):
+ # ``forward`` itself rejects "area" under export: the dynamo exporter would otherwise give a graph that is
+ # right only at the traced size. That exporter raises its own error, caused by the ``ValueError``.
+ pytest.importorskip("onnx")
+ if dynamo:
+ pytest.importorskip("onnxscript")
+ det = _small_edge_detector(ResizePostProcessor("area")).eval()
+ traced = torch.rand(2, 3, 24, 32, generator=torch.Generator().manual_seed(1))
+ dims = {0: "batch", 2: "height", 3: "width"}
+ export_kwargs = (
+ {"dynamic_shapes": (dims,)}
+ if dynamo
+ else {"opset_version": 18, "output_names": ["output"], "dynamic_axes": {"input": dims, "output": dims}}
+ )
+
+ # torch 2.9's non-strict export registers a global buffer-registration hook and removes it only when the
+ # trace succeeds. Drop the one this failing export leaves behind, or every later dynamo trace in the process
+ # calls it and raises ``Unsupported``.
+ buffer_hooks = torch.nn.modules.module._global_buffer_registration_hooks
+ hooks_before = set(buffer_hooks)
+ try:
+ with pytest.raises(Exception) as info:
+ torch.onnx.export(
+ det,
+ (traced,),
+ str(tmp_path / "edge_detector.onnx"),
+ dynamo=dynamo,
+ input_names=["input"],
+ **export_kwargs,
+ )
+ finally:
+ for key in set(buffer_hooks) - hooks_before:
+ del buffer_hooks[key]
+
+ error = info.value
+ while error is not None and not isinstance(error, ValueError):
+ error = error.__cause__ or error.__context__
+ assert error is not None, f"no ValueError behind {info.value!r}"
+ assert '"area"' in str(error)
+
+ 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.
+ det = _small_edge_detector().to(device, dtype)
+ images = torch.rand(2, 3, 20, 28, generator=torch.Generator().manual_seed(0)).to(device, dtype)
+
+ out = torch_optimizer(det)(images)
+
+ assert isinstance(out, list)
+ expected = det(images)
+ assert len(out) == len(expected) == 2
+ for actual, edge_map in zip(out, expected):
+ self.assert_close(actual, edge_map)
+
@pytest.mark.slow
def test_smoke(self, device, dtype):
img = torch.rand(2, 3, 64, 64, device=device, dtype=dtype)
diff --git a/tests/contrib/test_super_resolution.py b/tests/contrib/test_super_resolution.py
index 7b721ba09..b8dc36e89 100644
--- a/tests/contrib/test_super_resolution.py
+++ b/tests/contrib/test_super_resolution.py
@@ -27,7 +27,7 @@ from kornia.contrib.super_resolution import (
SuperResolution,
SuperResolutionConfig,
)
-from kornia.core._compat import torch_version_lt
+from kornia.core._compat import torch_version_ge, torch_version_lt
from testing.base import BaseTester
@@ -152,6 +152,32 @@ class TestSuperResolutionBuilders(BaseTester):
pytest.importorskip("onnxscript")
builder.build(pretrained=False, **build_kwargs).to_onnx(save=False)
+ @pytest.mark.device_agnostic
+ @pytest.mark.timeout(120)
+ @pytest.mark.parametrize("export_kwargs", [{}, {"dynamo": False}], ids=["default", "legacy"])
+ def test_to_onnx_with_pre_and_post_processor_matches_eager_at_any_size(self, export_kwargs):
+ """Without an ``image_size``, the graph takes any batch, height and width, as the eager pre-processor does."""
+ pytest.importorskip("onnx")
+ ort = pytest.importorskip("onnxruntime")
+ if export_kwargs.get("dynamo", torch_version_ge(2, 9, 0)):
+ pytest.importorskip("onnxscript")
+ torch.manual_seed(0)
+ model = SmallSRBuilder.build(pretrained=False)
+ op = model.to_onnx(save=False, **export_kwargs)
+ dims = [d.dim_param or d.dim_value for d in op.graph.input[0].type.tensor_type.shape.dim]
+ assert dims[1] == 3
+ assert all(isinstance(d, str) for d in (dims[0], dims[2], dims[3]))
+ session = ort.InferenceSession(op.SerializeToString(), providers=["CPUExecutionProvider"])
+
+ generator = torch.Generator().manual_seed(0)
+ # batches other than the traced 2, H != W, odd sizes
+ for shape in [(1, 3, 40, 56), (3, 3, 37, 61)]:
+ images = torch.rand(*shape, generator=generator)
+ (upscaled,) = session.run(None, {session.get_inputs()[0].name: images.numpy()})
+ with torch.no_grad():
+ expected = model(images)
+ self.assert_close(torch.from_numpy(upscaled), expected, rtol=1e-4, atol=1e-4)
+
@pytest.mark.parametrize(("upscale_factor", "image_size"), [(2, 32), (3, None), (4, 64)])
def test_output_image_size_matches_the_real_forward(self, device, dtype, upscale_factor, image_size):
"""``output_image_size`` must equal what a forward actually returns.
diff --git a/tests/core/test_onnx_mixin.py b/tests/core/test_onnx_mixin.py
index 347d48178..f9aea9bc4 100644
--- a/tests/core/test_onnx_mixin.py
+++ b/tests/core/test_onnx_mixin.py
@@ -189,20 +189,23 @@ class TestONNXExportMixin(BaseTester):
assert dims[1] == 3
assert all(isinstance(d, str) for d in (dims[0], dims[2], dims[3]))
- x = torch.rand(2, 3, 5, 7)
- with torch.no_grad():
- expected = model(x)
- self.assert_close(_run(op, x), expected)
+ # the batch is traced at 2: batches 1 and 3 check that the graph does not keep it
+ for batch in (1, 2, 3):
+ x = torch.rand(batch, 3, 5, 7)
+ with torch.no_grad():
+ expected = model(x)
+ self.assert_close(_run(op, x), expected)
def test_pseudo_shape_alone_sets_the_channel_count(self):
# Without input_shape, the default's fixed channel count follows an explicit pseudo shape.
model = ImageSequential(nn.Conv2d(1, 1, 1))
op = model.to_onnx(save=False, pseudo_shape=[1, 1, 32, 32])
- x = torch.rand(2, 1, 5, 7)
- with torch.no_grad():
- expected = model(x)
- self.assert_close(_run(op, x), expected)
+ for batch in (1, 2, 3):
+ x = torch.rand(batch, 1, 5, 7)
+ with torch.no_grad():
+ expected = model(x)
+ self.assert_close(_run(op, x), expected)
dims = _input_dims(op)
assert dims[1] == 1
diff --git a/tests/models/test_dexined_onnx.py b/tests/models/test_dexined_onnx.py
index 140d7bcf4..d52547ed6 100644
--- a/tests/models/test_dexined_onnx.py
+++ b/tests/models/test_dexined_onnx.py
@@ -16,9 +16,13 @@
#
import pytest
+import torch
+from kornia.core._compat import torch_version_ge
from kornia.models.dexined import DexiNed
+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
@@ -37,3 +41,25 @@ def test_dexined_to_onnx(tmp_path):
assert isinstance(op, onnx.ModelProto)
assert onnx_path.exists(), "ONNX file was not written to disk"
+
+
[email protected]("export_kwargs", [{}, {"dynamo": False}], ids=["default", "legacy"])
+def test_dexined_onnx_matches_eager_at_other_shapes(export_kwargs):
+ """Batch, height and width are dynamic: other batches than the traced 2, H != W and odd sizes match eager."""
+ pytest.importorskip("onnx")
+ ort = pytest.importorskip("onnxruntime")
+ if export_kwargs.get("dynamo", torch_version_ge(2, 9, 0)):
+ pytest.importorskip("onnxscript")
+ torch.manual_seed(0)
+ model = DexiNed(pretrained=False).eval()
+ op = model.to_onnx(save=False, pseudo_shape=[1, 3, 32, 32], **export_kwargs)
+ session = ort.InferenceSession(op.SerializeToString(), providers=["CPUExecutionProvider"])
+
+ generator = torch.Generator().manual_seed(0)
+ for shape in [(1, 3, 32, 32), (3, 3, 48, 80), (1, 3, 33, 47), (2, 3, 65, 31)]:
+ images = torch.rand(*shape, generator=generator)
+ (edges,) = session.run(None, {session.get_inputs()[0].name: images.numpy()})
+ with torch.no_grad():
+ expected = model(images)
+ assert_close(torch.from_numpy(edges), expected, rtol=1e-4, atol=1e-4)
diff --git a/tests/models/test_rtdetr_onnx.py b/tests/models/test_rtdetr_onnx.py
index d76eff42d..5d16bb6cf 100644
--- a/tests/models/test_rtdetr_onnx.py
+++ b/tests/models/test_rtdetr_onnx.py
@@ -59,6 +59,104 @@ def _post_processor() -> DETRPostProcessor:
return DETRPostProcessor(confidence_threshold=0.0, num_classes=2, num_top_queries=1, confidence_filtering=False)
+# ``to_onnx`` without ``dynamo=``: the dynamo exporter from torch 2.9, the TorchScript exporter before it.
+_EXPORTERS = [pytest.param({}, id="default"), pytest.param({"dynamo": False}, id="legacy")]
+
+
+def _importorskip_exporter(export_kwargs: dict) -> None:
+ pytest.importorskip("onnx")
+ if export_kwargs.get("dynamo", torch_version_ge(2, 9, 0)):
+ pytest.importorskip("onnxscript")
+
+
+def _small_rtdetr() -> RTDETR:
+ """A randomly initialised RT-DETR-R18 with 10 queries, which runs on 96 x 128 images (252 anchors)."""
+ torch.manual_seed(0)
+ return RTDETR.from_config(RTDETRConfig("resnet18d", num_classes=4, head_num_queries=10)).eval()
+
+
+def _images(shapes: list[tuple[int, int, int]]) -> list[torch.Tensor]:
+ # Seed 38 keeps the queries of ``_small_rtdetr`` apart on these shapes, see ``_eager_with_distinct_queries``.
+ generator = torch.Generator().manual_seed(38)
+ return [torch.rand(batch, 3, height, width, generator=generator) for batch, height, width in shapes]
+
+
+def _eager_with_distinct_queries(model: RTDETR, images: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor]:
+ """The model's eager ``(logits, boxes)``, after checking that its query selection has no near tie.
+
+ RT-DETR keeps the queries with the highest encoder scores, in score order. Where two scores nearly tie, a
+ difference of 1e-6 between ONNX Runtime and eager swaps two queries, and the outputs then differ by whole boxes
+ although the export is right. A random init on random images ties easily, so the inputs are drawn with a seed
+ whose scores stay at least 1e-4 apart; a change to the model's initialisation that breaks this fails here.
+ """
+ scores: list[torch.Tensor] = []
+ handle = model.decoder.enc_score_head.register_forward_hook(lambda m, i, out: scores.append(out.max(-1).values))
+ try:
+ with torch.no_grad():
+ logits, boxes = model(images)
+ finally:
+ handle.remove()
+ kept = scores[0].topk(model.decoder.num_queries + 1, dim=1).values
+ gap = (kept[:, :-1] - kept[:, 1:]).min().item()
+ assert gap > 1e-4, f"near tie between kept encoder scores ({gap:.1e}): pick another seed in _images"
+ return logits, boxes
+
+
+def _check_onnx_against_eager(op, model: RTDETR, images: torch.Tensor) -> None:
+ ort = pytest.importorskip("onnxruntime")
+ session = ort.InferenceSession(op.SerializeToString(), providers=["CPUExecutionProvider"])
+ logits, boxes = session.run(None, {session.get_inputs()[0].name: images.numpy()})
+ expected_logits, expected_boxes = _eager_with_distinct_queries(model, images)
+ assert_close(torch.from_numpy(logits), expected_logits, rtol=1e-4, atol=1e-4)
+ assert_close(torch.from_numpy(boxes), expected_boxes, rtol=1e-4, atol=1e-4)
+
+
+def _dims(value_info) -> list:
+ return [d.dim_param or d.dim_value for d in value_info.type.tensor_type.shape.dim]
+
+
[email protected]("export_kwargs", _EXPORTERS)
+def test_rtdetr_onnx_matches_eager_at_other_batches(export_kwargs):
+ """``RTDETR.to_onnx`` keeps the batch dynamic: batches 1 and 3 match eager on a graph traced at 2, H != W."""
+ _importorskip_exporter(export_kwargs)
+ model = _small_rtdetr()
+ op = model.to_onnx(save=False, pseudo_shape=[1, 3, 96, 128], **export_kwargs)
+
+ assert [o.name for o in op.graph.output] == ["pred_logits", "pred_boxes"]
+ for images in _images([(1, 96, 128), (3, 96, 128)]):
+ _check_onnx_against_eager(op, model, images)
+
+
+def test_rtdetr_legacy_onnx_ties_the_callers_output_names_to_the_input_batch():
+ """``RTDETR.to_onnx`` gives a caller's ``output_names`` the input's dynamic batch, as the declared names get it."""
+ _importorskip_exporter({"dynamo": False})
+ op = _small_rtdetr().to_onnx(save=False, pseudo_shape=[1, 3, 96, 128], dynamo=False, output_names=["a", "b"])
+
+ assert [o.name for o in op.graph.output] == ["a", "b"]
+ assert [_dims(output)[0] for output in op.graph.output] == ["batch", "batch"]
+
+
[email protected]("export_kwargs", _EXPORTERS)
+def test_detector_model_only_onnx_names_both_outputs(export_kwargs):
+ """Without pre- and post-processing, the detector exports RT-DETR's two outputs by name, at a dynamic size."""
+ _importorskip_exporter(export_kwargs)
+ model = _small_rtdetr()
+ detector = ObjectDetector(model, ResizePreProcessor(96, 96), _post_processor())
+ op = detector.to_onnx(image_size=None, include_pre_and_post_processor=False, save=False, **export_kwargs)
+
+ assert [o.name for o in op.graph.output] == ["pred_logits", "pred_boxes"]
+ # each output's batch is the input's dynamic batch
+ batch = _dims(op.graph.input[0])[0]
+ assert isinstance(batch, str)
+ assert [_dims(output)[0] for output in op.graph.output] == [batch, batch]
+ # two sizes, multiples of 32 with H != W, at batches other than the traced 2
+ for images in _images([(1, 96, 128), (3, 96, 128), (1, 128, 96), (3, 128, 96)]):
+ _check_onnx_against_eager(op, model, images)
+
+
@pytest.mark.timeout(120)
@pytest.mark.parametrize("sizes_dtype", [torch.float32, torch.int64])
def test_postprocessor_onnx_per_image_sizes(tmp_path, sizes_dtype):
@@ -135,6 +233,40 @@ def test_resize_preprocessor_onnx_dynamic_sizes():
assert_close(detections[..., 2:], expected)
+ ("output_names", "expected_names"),
+ [(["a", "b"], ["a", "b"]), (None, ["pred_logits", "pred_boxes"])],
+ ids=["callers_names", "none"],
+)
+def test_detector_model_only_legacy_onnx_ties_the_callers_output_names_to_the_input_batch(output_names, expected_names):
+ """A caller's ``output_names`` win over ``ONNX_OUTPUT_NAMES``, and each still gets the input's dynamic batch.
+
+ ``output_names=None``, the default of ``torch.onnx.export``, keeps the declared names.
+ """
+ _importorskip_exporter({"dynamo": False})
+ detector = ObjectDetector(_small_rtdetr(), ResizePreProcessor(96, 96), _post_processor())
+ op = detector.to_onnx(
+ image_size=None, include_pre_and_post_processor=False, save=False, dynamo=False, output_names=output_names
+ )
+
+ assert [o.name for o in op.graph.output] == expected_names
+ batch = _dims(op.graph.input[0])[0]
+ assert [_dims(output)[0] for output in op.graph.output] == [batch, batch]
+
+
+def test_detector_model_only_onnx_without_declared_names_keeps_output():
+ """A model that declares no ``ONNX_OUTPUT_NAMES`` keeps the mixin's single ``output`` name."""
+ _importorskip_exporter({})
+ detector = ObjectDetector(_FixedDetections(), ResizePreProcessor(32, 32), _post_processor())
+ assert not hasattr(detector.model, "ONNX_OUTPUT_NAMES")
+
+ op = detector.to_onnx(image_size=None, include_pre_and_post_processor=False, save=False)
+
+ assert op.graph.output[0].name == "output"
+
+
class _ScoredDetections(nn.Module):
"""One query per image, scored by the image's mean so that the export keeps its input; a fixed box."""
diff --git a/tests/models/test_sam_onnx.py b/tests/models/test_sam_onnx.py
index 74316c758..8633b7727 100644
--- a/tests/models/test_sam_onnx.py
+++ b/tests/models/test_sam_onnx.py
@@ -21,7 +21,12 @@ import pytest
import torch
from kornia.core._compat import torch_version_ge, torch_version_lt
+from kornia.models.sam.architecture.common import LayerNorm
+from kornia.models.sam.architecture.image_encoder import ImageEncoderViT
from kornia.models.sam.model import Sam, SamConfig
+from kornia.models.tiny_vit import TinyViT
+
+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
@@ -74,3 +79,95 @@ def test_sam_encoder_to_onnx(tmp_path):
output_names = [o.name for o in op.graph.output]
assert "image_embeddings" in output_names, f"Expected 'image_embeddings', got {output_names}"
+
+
+def _dims(value_info):
+ return [d.dim_param or d.dim_value for d in value_info.type.tensor_type.shape.dim]
+
+
+def _check_onnx_against_eager(op, encoder, batches, size):
+ ort = pytest.importorskip("onnxruntime")
+ session = ort.InferenceSession(op.SerializeToString(), providers=["CPUExecutionProvider"])
+ generator = torch.Generator().manual_seed(0)
+ for batch in batches:
+ images = torch.rand(batch, 3, size, size, generator=generator)
+ (embeddings,) = session.run(None, {session.get_inputs()[0].name: images.numpy()})
+ with torch.no_grad():
+ expected = encoder(images)
+ assert_close(torch.from_numpy(embeddings), expected, rtol=1e-4, atol=1e-4)
+
+
+def test_vit_encoder_legacy_onnx_matches_eager_at_every_batch():
+ """On the legacy exporter, a ViT image encoder runs at batches other than the traced one."""
+ pytest.importorskip("onnx")
+ torch.manual_seed(0)
+ model = Sam.from_config(
+ SamConfig(
+ model_type=None, encoder_embed_dim=16, encoder_depth=1, encoder_num_heads=1, encoder_global_attn_indexes=[0]
+ )
+ )
+ # A 64 px encoder with a windowed and a global block: the 1024 px one holds a 4096 x 4096 attention per image.
+ model.image_encoder = ImageEncoderViT(
+ img_size=64,
+ embed_dim=16,
+ depth=2,
+ num_heads=1,
+ norm_layer=LayerNorm,
+ use_rel_pos=True,
+ global_attn_indexes=(1,),
+ window_size=14,
+ out_chans=256,
+ )
+ model.eval()
+
+ op = model.to_onnx(save=False, pseudo_shape=[1, 3, 64, 64], dynamo=False)
+
+ assert _dims(op.graph.input[0]) == ["batch", 3, 64, 64]
+ _check_onnx_against_eager(op, model.image_encoder, (1, 2, 3), 64)
+
+
[email protected]("export_kwargs", [{}, {"dynamo": False}], ids=["default", "legacy"])
+def test_tiny_vit_encoder_onnx_runs_at_the_batches_it_declares(export_kwargs):
+ """A MobileSAM (TinyViT) encoder: a dynamic batch on the dynamo exporter, the pseudo batch on the legacy one.
+
+ The legacy TorchScript exporter (the default before torch 2.9) keeps the traced batch in TinyViT's reshapes, so
+ its graph is traced at the pseudo shape's batch and declares that batch, rather than a dynamic batch that runs at
+ the traced size only.
+ """
+ pytest.importorskip("onnx")
+ legacy = not export_kwargs.get("dynamo", torch_version_ge(2, 9, 0))
+ if not legacy:
+ pytest.importorskip("onnxscript")
+ torch.manual_seed(0)
+ model = Sam.from_name("mobile_sam")
+ # The MobileSAM encoder layout at 64 px instead of 1024 px.
+ model.image_encoder = TinyViT.from_config("5m", img_size=64, mobile_sam=True)
+ model.eval()
+
+ op = model.to_onnx(save=False, pseudo_shape=[1, 3, 64, 64], **export_kwargs)
+
+ if legacy:
+ _check_onnx_against_eager(op, model.image_encoder, (1,), 64)
+ assert _dims(op.graph.input[0]) == [1, 3, 64, 64]
+ assert _dims(op.graph.output[0])[0] == 1
+ else:
+ _check_onnx_against_eager(op, model.image_encoder, (1, 2, 3), 64)
+ assert isinstance(_dims(op.graph.input[0])[0], str)
+
+
+def test_tiny_vit_encoder_legacy_onnx_declares_the_pseudo_batch():
+ """On the legacy exporter, a TinyViT encoder is traced at the pseudo shape's batch, here 3, and declares it."""
+ pytest.importorskip("onnx")
+ torch.manual_seed(0)
+ model = Sam.from_name("mobile_sam")
+ model.image_encoder = TinyViT.from_config("5m", img_size=64, mobile_sam=True)
+ model.eval()
+
+ op = model.to_onnx(save=False, pseudo_shape=[3, 3, 64, 64], dynamo=False)
+
+ assert _dims(op.graph.input[0]) == [3, 3, 64, 64]
+ assert _dims(op.graph.output[0])[0] == 3
+ _check_onnx_against_eager(op, model.image_encoder, (3,), 64)