Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

fix(onnx): exported dynamic batches run at every batch size; PR CI runs Dynamo on torch 2.5.1 and 2.9.1 (#6076)

Dmytro Mishkin33684ef1c9fd
diff --git a/.github/workflows/pr_test_cpu.yml b/.github/workflows/pr_test_cpu.yml
index b5431a08a..e9cbdad60 100644
--- a/.github/workflows/pr_test_cpu.yml
+++ b/.github/workflows/pr_test_cpu.yml
@@ -86,12 +86,19 @@ jobs:
fail-fast: false
# Each PR leg is here for failures the others do not catch; the full os x dtype x python x
# torch matrix runs on main twice a day in scheduled_test_cpu.yml. Measured over the PR
- # runs from 2026-09-03 to 2026-09-24, these six legs plus the half-precision, MPS and
- # dynamo jobs caught every test failure that the previous 27-leg matrix caught, apart from
- # one environment-specific `test_check_torch_env` failure.
- # - ubuntu 3.13 / torch 2.5.1 (float32, float64): the only place Python 3.13 meets the
- # oldest torch -- 2.5.1 has no 3.13 wheels on Windows or macOS -- and the leg that
- # caught the most failures nothing else caught.
+ # runs from 2026-09-03 to 2026-09-24, the six legs of the time plus the half-precision, MPS
+ # and dynamo jobs caught every test failure that the previous 27-leg matrix caught, apart
+ # from one environment-specific `test_check_torch_env` failure. Both of that time's torch
+ # 2.5.1 legs ran Python 3.13, and none ran torch 2.9, so tests that need Dynamo on an older
+ # torch failed first on main; the two Python 3.12 legs below close that gap.
+ # - ubuntu 3.13 / torch 2.5.1 (float32): the only place Python 3.13 meets the oldest torch
+ # -- 2.5.1 has no 3.13 wheels on Windows or macOS -- and the leg that caught the most
+ # failures nothing else caught.
+ # - ubuntu 3.12 / torch 2.5.1 (float64): the oldest torch with Dynamo, which 2.5.1 lacks on
+ # Python 3.13, so its torch.export and dynamo ONNX exporter tests run before merge.
+ # - ubuntu 3.12 / torch 2.9.1 (float32): the first release on which `torch.onnx.export`,
+ # and with it `to_onnx`, defaults to the dynamo exporter. Its torch.export specializes
+ # differently from 2.14's: a DexiNed export ran only at the traced batch size (#6066).
# - ubuntu 3.11 / torch 2.14.0 (float32, float64): the oldest Python on the newest torch,
# so every Python and torch pin still gets a full-suite run in both dtypes on Linux.
# - windows-latest float64: Windows-only failures (path handling, the eager RNG audit)
@@ -108,8 +115,12 @@ jobs:
pytorch-version: "2.5.1"
- os: ubuntu-latest
pytorch-dtype: "float64"
- python-version: "3.13"
+ python-version: "3.12"
pytorch-version: "2.5.1"
+ - os: ubuntu-latest
+ pytorch-dtype: "float32"
+ python-version: "3.12"
+ pytorch-version: "2.9.1"
- os: ubuntu-latest
pytorch-dtype: "float32"
python-version: "3.11"
diff --git a/changelog.d/6076.fixed.md b/changelog.d/6076.fixed.md
new file mode 100644
index 000000000..22bbb74b7
--- /dev/null
+++ b/changelog.d/6076.fixed.md
@@ -0,0 +1 @@
+ONNX exports that declare a dynamic batch now run at every batch size. `to_onnx` traced them from a batch of 1, which `torch.export` specializes. On torch 2.9, the exported DexiNed edge detector and SAM image encoder kept that batch inside the graph, and ONNX Runtime rejected any other. `ResizePreProcessor` looped over the batch, so the loop unrolled at the traced size. On every torch release, the default exports of `EdgeDetector` and `SmallSR`, which include that pre-processor, returned one image's output for a batch of any size. `to_onnx` now traces each dynamic dimension at a size of at least 2, and `ResizePreProcessor` resizes a tensor batch in one call. An `ObjectDetector` whose post-processor returns a list of per-image detections, as the default confidence-filtered RT-DETR detector does, used to declare a dynamic batch and return the first image's detections for any batch. It is now exported for a batch of one image; build an RT-DETR detector with `confidence_filtering=False` to export a batch of any size.
diff --git a/kornia/contrib/object_detection.py b/kornia/contrib/object_detection.py
index e3cd8fa97..8dcc1d391 100644
--- a/kornia/contrib/object_detection.py
+++ b/kornia/contrib/object_detection.py
@@ -28,7 +28,7 @@ from kornia.constants import _get_by_name
from kornia.core.check import KORNIA_CHECK_SHAPE
from kornia.core.external import PILImage as Image
from kornia.core.external import onnx
-from kornia.core.mixin.onnx import ONNXExportMixin
+from kornia.core.mixin.onnx import ONNXExportMixin, _eval_mode, _first_floating_tensor, _to_floating
from kornia.image.draw import draw_rectangle
from kornia.models.base import ModelBase
from kornia.models.processors import ResizePreProcessor
@@ -126,6 +126,19 @@ def results_from_detections(
return results
+def _returns_detections_per_image(detector: nn.Module, images: torch.Tensor) -> bool:
+ """Return whether ``detector`` returns a list of per-image detections for ``images`` rather than one tensor.
+
+ The detector runs once, 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. Its output decides, so any post-processor is covered.
+ """
+ reference = _first_floating_tensor(detector)
+ if reference is not None:
+ images = _to_floating(images, reference)
+ with _eval_mode(detector), torch.no_grad():
+ return isinstance(detector(images), list)
+
+
class ObjectDetector(ModelBase, ONNXExportMixin):
"""Wrap an object detection model and perform pre-processing and post-processing."""
@@ -251,16 +264,29 @@ class ObjectDetector(ModelBase, ONNXExportMixin):
Additional metadata to add to the ONNX model.
kwargs: Additional arguments to convert to onnx.
+ Note:
+ With a post-processor that returns a list of per-image detections, as a
+ ``kornia.models.rt_detr.DETRPostProcessor`` that filters by confidence does, the model is
+ exported 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 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.
+
"""
if onnx_name is None:
onnx_name = f"kornia_{self.name}_{image_size}.onnx"
+ pseudo_shape = [1, 3, image_size or 352, image_size or 352]
+ # Exported for a dynamic batch, a per-image list comes out as the traced batch's detections, or the export
+ # fails: such a detector is exported for one image.
+ batch = -1
+ if include_pre_and_post_processor and _returns_detections_per_image(self, torch.rand(pseudo_shape)):
+ batch = 1
return ONNXExportMixin.to_onnx(
self,
onnx_name,
- input_shape=[-1, 3, image_size or -1, image_size or -1],
+ input_shape=[batch, 3, image_size or -1, image_size or -1],
output_shape=[-1, -1, 6],
- pseudo_shape=[1, 3, image_size or 352, image_size or 352],
+ pseudo_shape=pseudo_shape,
model=self if include_pre_and_post_processor else self.model,
save=save,
additional_metadata=additional_metadata,
diff --git a/kornia/core/mixin/onnx.py b/kornia/core/mixin/onnx.py
index 5c104c442..56f70b3df 100644
--- a/kornia/core/mixin/onnx.py
+++ b/kornia/core/mixin/onnx.py
@@ -17,6 +17,7 @@
from __future__ import annotations
+import contextlib
import io
import itertools
import os
@@ -24,6 +25,7 @@ import tempfile
from typing import (
Any,
ClassVar,
+ Iterator,
Optional,
Union,
)
@@ -61,6 +63,22 @@ def _to_floating(value: Any, reference: torch.Tensor) -> Any:
return value
+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."""
+ modes = [(m, m.training) for m in module.modules()] if isinstance(module, nn.Module) else []
+ try:
+ if isinstance(module, nn.Module):
+ module.eval()
+ yield
+ finally:
+ # The flag is set directly on purpose: ``train()`` recurses into the children, which would lose a mixed
+ # state. It also skips ``train()`` overrides: check any new ``train()`` override with side effects against
+ # this restore.
+ for submodule, training in modes:
+ submodule.training = training
+
+
class ONNXExportMixin:
"""Mixin class that provides ONNX export functionality for objects that support it.
@@ -147,7 +165,9 @@ class ONNXExportMixin:
- The export requests ONNX opset 18, which the dynamo exporter (the default of `torch.onnx.export`
from torch 2.9) builds natively and the legacy TorchScript exporter emits directly. Pass
`opset_version` to request another one.
- - A dummy input tensor is created from the input shape, with each `-1` taken from the pseudo shape.
+ - A dummy input tensor is created from the input shape, with each `-1` taken from the pseudo shape and
+ raised to 2 if it is smaller: `torch.export` specializes an example size of 0 or 1, which can leave a
+ graph that declares the dimension dynamic but runs only at that size.
It has the dtype and device of the model's first floating parameter or, for a model without one,
of its first floating buffer; it is float32 on the CPU for a model with neither.
- The dimensions marked `-1` are exported as dynamic: through `dynamic_shapes` on the dynamo exporter
@@ -189,6 +209,14 @@ class ONNXExportMixin:
raise FileNotFoundError(f"Cannot save the ONNX model to {onnx_name}: {directory} does not exist.")
module = self if model is None else model
+ if -1 in input_shape:
+ # ``torch.export`` specializes an example size of 0 or 1, so a dynamic dimension traced at 1 can come out
+ # fixed inside the graph while the graph input stays dynamic: on torch 2.9 DexiNed's ``Resize`` nodes kept
+ # the batch of 1 and failed in ONNX Runtime at any other batch size. Dynamic dimensions are traced at 2 or
+ # more.
+ pseudo_shape = [
+ max(size, 2) if dim == -1 else size for dim, size in zip(input_shape, resolved_pseudo_shape)
+ ]
dummy_input = self._create_dummy_input(input_shape, pseudo_shape)
reference = _first_floating_tensor(module)
if reference is not None:
@@ -211,26 +239,16 @@ class ONNXExportMixin:
# The dynamo exporter captures the model in whatever mode it is in, so a model left in training mode would
# export active Dropout. Each submodule's own flag is restored, since ``train(True)`` would reset them all.
- modes = [(m, m.training) for m in module.modules()] if isinstance(module, nn.Module) else []
- try:
- if isinstance(module, nn.Module):
- module.eval()
- # A file path rather than a buffer: exporting to ``io.BytesIO`` is deprecated from torch 2.9.
- with tempfile.TemporaryDirectory() as tmp_dir:
- tmp_path = os.path.join(tmp_dir, "model.onnx")
- torch.onnx.export(
- module,
- dummy_input,
- tmp_path,
- **default_args,
- )
- onnx_model = onnx.load(tmp_path)
- finally:
- # The flag is set directly on purpose: ``train()`` recurses into the children, which would lose a mixed
- # state. It also skips ``train()`` overrides: check any new ``train()`` override with side effects against
- # this restore.
- for submodule, training in modes:
- submodule.training = training
+ # A file path rather than a buffer: exporting to ``io.BytesIO`` is deprecated from torch 2.9.
+ with _eval_mode(module), tempfile.TemporaryDirectory() as tmp_dir:
+ tmp_path = os.path.join(tmp_dir, "model.onnx")
+ torch.onnx.export(
+ module,
+ dummy_input,
+ tmp_path,
+ **default_args,
+ )
+ onnx_model = onnx.load(tmp_path)
# Later entries overwrite earlier ones, so the caller's metadata wins over the class's.
metadata = [*self.ADDITIONAL_METADATA, *(additional_metadata or [])]
diff --git a/kornia/models/processors/__init__.py b/kornia/models/processors/__init__.py
index a5906261a..1db6e034a 100644
--- a/kornia/models/processors/__init__.py
+++ b/kornia/models/processors/__init__.py
@@ -71,11 +71,18 @@ class ResizePreProcessor(nn.Module):
- original_sizes: Original image sizes of shape :math:`(B, 2)` containing (height, width), as
``int64`` on the images' device.
"""
- resized_imgs: List[Tensor] = []
+ # int64: a half-precision image dtype cannot hold every size (bfloat16 rounds 667 to 668). Filled in rather
+ # than built with ``torch.tensor``, which the TorchScript ONNX exporter bakes in as constants.
+ if isinstance(imgs, Tensor):
+ # One resize for the whole batch, whose images share a size: a loop over the batch would unroll at the
+ # traced batch size in an ONNX export and fix the exported model to that batch.
+ original_sizes = imgs.new_zeros((imgs.shape[0], 2), dtype=torch.long)
+ original_sizes[:, 0] = imgs.shape[-2] # Height
+ original_sizes[:, 1] = imgs.shape[-1] # Width
+ return resize(imgs, size=self.size, interpolation=self.interpolation_mode), original_sizes
- iters = len(imgs) if isinstance(imgs, list) else imgs.shape[0]
- # int64: a half-precision image dtype cannot hold every size (bfloat16 rounds 667 to 668). Filled per image
- # rather than built with ``torch.tensor``, which the TorchScript ONNX exporter bakes in as constants.
+ resized_imgs: List[Tensor] = []
+ iters = len(imgs)
original_sizes = imgs[0].new_zeros((iters, 2), dtype=torch.long)
for i in range(iters):
diff --git a/kornia/models/rt_detr/model.py b/kornia/models/rt_detr/model.py
index 5090d8f4a..678d29e81 100644
--- a/kornia/models/rt_detr/model.py
+++ b/kornia/models/rt_detr/model.py
@@ -342,7 +342,8 @@ class RTDETR(ONNXExportMixin, ModelBase[RTDETRConfig]):
onnx_name: Path for the saved ``.onnx`` file. Defaults to
``"Kornia-RTDETR.onnx"``.
pseudo_shape: Concrete input shape used to trace the model, e.g.
- ``[1, 3, 640, 640]``. Defaults to ``[1, 3, 640, 640]``.
+ ``[1, 3, 640, 640]``. Defaults to ``[1, 3, 640, 640]``. The batch is
+ exported as dynamic, so a batch below 2 is traced at 2.
save: Whether to write the model to disk. Default ``True``.
**kwargs: Additional keyword arguments forwarded to
:func:`torch.onnx.export`.
diff --git a/kornia/models/sam/model.py b/kornia/models/sam/model.py
index ffddbc30f..eea7623be 100644
--- a/kornia/models/sam/model.py
+++ b/kornia/models/sam/model.py
@@ -287,7 +287,8 @@ class Sam(ONNXExportMixin, ModelBase[SamConfig]):
onnx_name: Path for the saved ``.onnx`` file. Defaults to
``"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]``.
+ ``[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.
save: Whether to write the model to disk. Default ``True``.
**kwargs: Additional keyword arguments forwarded to
:func:`torch.onnx.export`.
diff --git a/tests/contrib/test_super_resolution.py b/tests/contrib/test_super_resolution.py
index 85c6d4f7a..2480e91db 100644
--- a/tests/contrib/test_super_resolution.py
+++ b/tests/contrib/test_super_resolution.py
@@ -180,9 +180,12 @@ class TestSuperResolutionBuilders(BaseTester):
def test_onnx_export_shape_matches_the_real_forward(self):
"""The static size handed to ``to_onnx`` must be the one the graph produces."""
- pytest.importorskip("onnx")
+ onnx = pytest.importorskip("onnx")
pytest.importorskip("onnxscript")
model = SmallSRBuilder.build(pretrained=False, upscale_factor=2, image_size=32)
exported = model.to_onnx(save=False)
- out_dim = exported.graph.output[0].type.tensor_type.shape.dim[-1]
+ # The legacy TorchScript exporter (the default before torch 2.9) declares the dimensions after a resize of the
+ # dynamic batch as symbolic; shape inference with data propagation reads the size either exporter's graph makes.
+ inferred = onnx.shape_inference.infer_shapes(exported, data_prop=True)
+ out_dim = inferred.graph.output[0].type.tensor_type.shape.dim[-1]
assert out_dim.dim_value == model.output_image_size
diff --git a/tests/core/test_onnx_mixin.py b/tests/core/test_onnx_mixin.py
index d549c6b84..8684d5ee0 100644
--- a/tests/core/test_onnx_mixin.py
+++ b/tests/core/test_onnx_mixin.py
@@ -164,6 +164,30 @@ class TestONNXExportMixin(BaseTester):
with pytest.raises(FileNotFoundError, match="no_such_dir"):
ImageSequential(nn.Identity()).to_onnx(onnx_name=str(tmp_path / "no_such_dir" / "x.onnx"), **_RGB)
+ @pytest.mark.parametrize(
+ "input_shape, pseudo_shape, traced",
+ [
+ ([-1, 3, -1, -1], [1, 3, 1, 32], [2, 3, 2, 32]),
+ ([-1, 3, 16, -1], [0, 3, 16, 5], [2, 3, 16, 5]),
+ ([1, 3, 16, 16], [1, 3, 16, 16], [1, 3, 16, 16]),
+ ],
+ ids=["sizes_of_one", "size_of_zero", "fixed_dimensions"],
+ )
+ def test_dynamic_dimensions_are_traced_at_two_or_more_6066(self, monkeypatch, input_shape, pseudo_shape, traced):
+ # torch.export specializes an example size of 0 or 1. On torch 2.9, DexiNed exported from a batch of 1 kept
+ # that batch inside its Resize nodes and failed in ONNX Runtime at any other batch size. Fixed dimensions keep
+ # theirs.
+ traced_shapes = []
+
+ def _capture(model, args, *rest, **kwargs):
+ traced_shapes.append(list(args.shape))
+ raise RuntimeError("captured")
+
+ monkeypatch.setattr(torch.onnx, "export", _capture)
+ with pytest.raises(RuntimeError, match="captured"):
+ ImageSequential(nn.Identity()).to_onnx(save=False, input_shape=input_shape, pseudo_shape=pseudo_shape)
+ assert traced_shapes == [traced]
+
class _ChannelAffine(nn.Module):
"""A per-channel affine map, with its weights as parameters or as buffers.
diff --git a/tests/models/test_processors.py b/tests/models/test_processors.py
index 309e8cdc1..aa93190b1 100644
--- a/tests/models/test_processors.py
+++ b/tests/models/test_processors.py
@@ -44,6 +44,16 @@ class TestResizePreProcessor(BaseTester):
assert original_sizes.device == device
assert original_sizes.tolist() == [list(size) for size in sizes]
+ def test_tensor_batch_matches_the_per_image_resize(self, device, dtype):
+ # A tensor batch is resized in one call, which keeps its batch dynamic in an ONNX export.
+ images = torch.rand(3, 3, 13, 17, device=device, dtype=dtype)
+
+ resized, original_sizes = ResizePreProcessor(8, 9)(images)
+ per_image, per_image_sizes = ResizePreProcessor(8, 9)(list(images))
+
+ self.assert_close(resized, per_image)
+ assert original_sizes.tolist() == per_image_sizes.tolist() == [[13, 17]] * 3
+
class TestResizePostProcessor(BaseTester):
@pytest.mark.parametrize(
diff --git a/tests/models/test_rtdetr_onnx.py b/tests/models/test_rtdetr_onnx.py
index c36139f2b..d76eff42d 100644
--- a/tests/models/test_rtdetr_onnx.py
+++ b/tests/models/test_rtdetr_onnx.py
@@ -22,6 +22,7 @@ import torch
from torch import nn
from kornia.contrib.object_detection import ObjectDetector
+from kornia.core._compat import torch_version_ge, torch_version_lt
from kornia.models.processors import ResizePreProcessor
from kornia.models.rt_detr.model import RTDETR, RTDETRConfig
from kornia.models.rt_detr.post_processor import DETRPostProcessor
@@ -112,7 +113,7 @@ class _FixedDetections(nn.Module):
@pytest.mark.timeout(120)
def test_resize_preprocessor_onnx_dynamic_sizes():
- """With a dynamic H and W, the exported detector reads each input's size instead of the trace's."""
+ """With a dynamic batch, H and W, the exported detector reads each input's size instead of the trace's."""
pytest.importorskip("onnx")
ort = pytest.importorskip("onnxruntime")
pytest.importorskip("onnxscript")
@@ -122,21 +123,135 @@ def test_resize_preprocessor_onnx_dynamic_sizes():
session = ort.InferenceSession(exported.SerializeToString(), providers=["CPUExecutionProvider"])
generator = torch.Generator().manual_seed(0)
- for height, width in [(77, 128), (96, 100)]:
- images = torch.rand(1, 3, height, width, generator=generator)
+ # A batch of 2 came out as one image's detections when the pre-processor looped over the batch.
+ for batch, height, width in [(1, 77, 128), (1, 96, 100), (2, 77, 128)]:
+ images = torch.rand(batch, 3, height, width, generator=generator)
(detections,) = session.run(None, {"input": images.numpy()})
detections = torch.from_numpy(detections)
assert_close(detections, detector(images))
# xywh of the normalised box (0.5, 0.5, 0.25, 0.25) in this image's pixels
- expected = torch.tensor([[[0.375 * width, 0.375 * height, 0.25 * width, 0.25 * height]]])
+ expected = torch.tensor([[[0.375 * width, 0.375 * height, 0.25 * width, 0.25 * height]]]).expand(batch, -1, -1)
assert_close(detections[..., 2:], expected)
+class _ScoredDetections(nn.Module):
+ """One query per image, scored by the image's mean so that the export keeps its input; a fixed box."""
+
+ def forward(self, images: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor]:
+ score = images.mean((1, 2, 3))
+ boxes = images.new_tensor([0.5, 0.5, 0.25, 0.25]).expand(images.shape[0], 1, 4)
+ return torch.stack([score, -score], -1)[:, None], boxes
+
+
+ torch_version_ge(2, 14) and torch_version_lt(2, 15, 0),
+ reason=(
+ "torch 2.14's dynamo ONNX exporter cannot translate aten.mul.Scalar for this graph in the CPU build: "
+ "DispatchError 'No decompositions registered for the real-valued input', as in "
+ "test_sam_onnx.py::test_sam_encoder_to_onnx"
+ ),
+ raises=torch.onnx.OnnxExporterError,
+ # Strict on the CPU builds, as in test_sam_onnx.py, where an upstream fix inside 2.14.x must show as an XPASS.
+ strict=torch.version.cuda is None,
+)
+def test_detector_with_per_image_detections_exports_one_image():
+ """A post-processor returning a list per image is exported for a batch of one, not for any batch's first image."""
+ pytest.importorskip("onnx")
+ ort = pytest.importorskip("onnxruntime")
+ pytest.importorskip("onnxscript")
+
+ post_processor = DETRPostProcessor(confidence_threshold=0.5, num_classes=2, num_top_queries=1)
+ detector = ObjectDetector(_ScoredDetections(), ResizePreProcessor(32, 32), post_processor)
+ images = torch.rand(1, 3, 32, 32, generator=torch.Generator().manual_seed(0))
+ assert isinstance(detector(images), list)
+
+ exported = detector.to_onnx(image_size=32, save=False)
+ assert exported.graph.input[0].type.tensor_type.shape.dim[0].dim_value == 1
+
+ session = ort.InferenceSession(exported.SerializeToString(), providers=["CPUExecutionProvider"])
+ (detections,) = session.run(None, {"input": images.numpy()})
+ assert_close(torch.from_numpy(detections), detector(images)[0])
+
+
+class _PerImageDetections(nn.Module):
+ """A caller's own post-processor, not a ``DETRPostProcessor``: one ``(Q, 6)`` tensor per image."""
+
+ def forward(self, logits: torch.Tensor, boxes: torch.Tensor, sizes: torch.Tensor) -> list[torch.Tensor]:
+ scores, labels = logits.max(-1, keepdim=True)
+ detections = torch.cat([labels.to(boxes), scores, boxes], -1)
+ return [detections[i] for i in range(detections.shape[0])]
+
+
+def test_detector_with_a_custom_per_image_post_processor_exports_one_image():
+ """The output decides, not the post-processor's class: any per-image list is exported for a batch of one."""
+ pytest.importorskip("onnx")
+ ort = pytest.importorskip("onnxruntime")
+ pytest.importorskip("onnxscript")
+
+ detector = ObjectDetector(_ScoredDetections(), ResizePreProcessor(32, 32), _PerImageDetections())
+ images = torch.rand(1, 3, 32, 32, generator=torch.Generator().manual_seed(0))
+
+ exported = detector.to_onnx(image_size=32, save=False)
+ assert exported.graph.input[0].type.tensor_type.shape.dim[0].dim_value == 1
+
+ session = ort.InferenceSession(exported.SerializeToString(), providers=["CPUExecutionProvider"])
+ (detections,) = session.run(None, {"input": images.numpy()})
+ assert_close(torch.from_numpy(detections), detector(images)[0])
+
+
+class _NormalisedDetections(_ScoredDetections):
+ """``_ScoredDetections`` behind a batch norm, whose statistics a forward pass in training mode would update."""
+
+ def __init__(self) -> None:
+ super().__init__()
+ self.norm = nn.BatchNorm2d(3)
+
+ def forward(self, images: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor]:
+ return super().forward(self.norm(images))
+
+
+def test_detector_output_probe_runs_in_eval_mode_on_the_models_dtype():
+ """The forward pass that reads the output kind keeps statistics and each training flag, in the model's dtype."""
+ pytest.importorskip("onnx")
+ pytest.importorskip("onnxscript")
+
+ model = _NormalisedDetections()
+ detector = ObjectDetector(model, ResizePreProcessor(32, 32), _PerImageDetections()).double().train()
+ detector.pre_processor.eval() # a mixed state, which ``train()`` would not restore
+ running_mean = model.norm.running_mean.clone()
+
+ exported = detector.to_onnx(image_size=32, save=False)
+
+ assert exported.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 detector.training
+ assert model.norm.training
+ assert not detector.pre_processor.training
+
+
@pytest.mark.timeout(120)
@pytest.mark.parametrize(
"dynamo",
- [False, pytest.param(True, marks=pytest.mark.skipif(not dynamo_is_available(), reason=DYNAMO_UNAVAILABLE_REASON))],
+ [
+ False,
+ pytest.param(
+ True,
+ marks=[
+ pytest.mark.skipif(not dynamo_is_available(), reason=DYNAMO_UNAVAILABLE_REASON),
+ # torch 2.5.1 and 2.6.0 fail on the stem's batch norm (2.5.1 on a bare ``BatchNorm2d`` too) with
+ # ``_native_batch_norm_legit_no_training``; 2.9.1 passes, and 2.9 makes dynamo the default exporter.
+ pytest.mark.skipif(
+ torch_version_lt(2, 9, 0),
+ reason="the dynamo ONNX exporter before torch 2.9 cannot translate BatchNorm",
+ ),
+ ],
+ ),
+ ],
)
def test_resnet_d_onnx_odd_sizes(tmp_path, dynamo):
"""At an odd feature map the exported ResNet-D matches eager in old and new ONNX Runtime alike.