Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

fix(onnx): reject a dynamic batch on ObjectDetector and BoxFiltering exports that return one output per image (#6162)

Dmytro Mishkindb1717f89f5c
diff --git a/changelog.d/6162.fixed.md b/changelog.d/6162.fixed.md
new file mode 100644
index 000000000..1b9605c04
--- /dev/null
+++ b/changelog.d/6162.fixed.md
@@ -0,0 +1 @@
+`ObjectDetector.to_onnx` and `BoxFiltering.to_onnx` raise a `ValueError` when a `dynamic_axes` or `dynamic_shapes` argument makes the batch of a per-image-list export dynamic. Such an export has one graph output per traced image, so it used to succeed, declare a dynamic batch, and give wrong results at any other batch size: a detector returned one image's detections for a batch of 3, and a `BoxFiltering` traced at a batch of 5 returned 5 outputs at a batch of 7 and failed in ONNX Runtime at batches of 1 and 3. The check reads the exported graph, so it covers every form of the two arguments, and an override that keeps the batch fixed, such as `torch.export.Dim.STATIC()` or a dynamic detection count only, still exports. Nothing is saved when it raises. `filter_as_zero=True`, and an RT-DETR detector built with `confidence_filtering=False`, export a dynamic batch as before.
diff --git a/kornia/contrib/object_detection.py b/kornia/contrib/object_detection.py
index 23d404d10..69fabfa45 100644
--- a/kornia/contrib/object_detection.py
+++ b/kornia/contrib/object_detection.py
@@ -19,7 +19,7 @@ from __future__ import annotations
from dataclasses import dataclass
from enum import Enum
-from typing import Any, ClassVar, List, Optional, Tuple, Union
+from typing import Any, ClassVar, List, Optional, Union
import torch
from torch import nn
@@ -283,7 +283,9 @@ class ObjectDetector(ModelBase, ONNXExportMixin):
``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.
+ 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
@@ -326,6 +328,14 @@ class ObjectDetector(ModelBase, ONNXExportMixin):
**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):
+ return None
+ return (
+ "Use a post-processor that returns one tensor for the batch, such as a DETRPostProcessor with "
+ "confidence_filtering=False, to export a dynamic batch."
+ )
+
def compile(
self,
*,
@@ -480,7 +490,8 @@ class BoxFiltering(nn.Module, ONNXExportMixin):
The exported ONNX model.
Raises:
- ValueError: If ``input_shape`` marks the batch ``-1`` without ``filter_as_zero``.
+ ValueError: If ``input_shape`` marks the batch ``-1`` without ``filter_as_zero``, or a ``dynamic_axes``
+ or ``dynamic_shapes`` argument makes the exported batch dynamic without it.
Note:
The exported graph takes the boxes as its only input and filters at the threshold given to the
@@ -514,15 +525,10 @@ class BoxFiltering(nn.Module, ONNXExportMixin):
**kwargs,
)
- def _create_dummy_input(
- self, input_shape: List[int], pseudo_shape: Optional[List[int]] = None
- ) -> Union[Tuple[Any, ...], torch.Tensor]:
- return torch.rand(
- *[
- ((self.ONNX_EXPORT_PSEUDO_SHAPE[i] if pseudo_shape is None else pseudo_shape[i]) if dim == -1 else dim)
- for i, dim in enumerate(input_shape)
- ]
- )
+ def _onnx_fixed_batch_hint(self, module: Any, dummy_input: Any) -> Optional[str]:
+ if not isinstance(module, BoxFiltering) or module.filter_as_zero:
+ return None
+ return "Use filter_as_zero=True to export a dynamic batch as one (B, D, 6) output."
class RTDETRDetectorBuilder:
diff --git a/kornia/core/mixin/onnx.py b/kornia/core/mixin/onnx.py
index ca6322134..fee9cab61 100644
--- a/kornia/core/mixin/onnx.py
+++ b/kornia/core/mixin/onnx.py
@@ -306,6 +306,14 @@ def _removed_buffer_hooks() -> Iterator[None]:
del hooks[key]
+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:
+ return False
+ dims = onnx_model.graph.input[0].type.tensor_type.shape.dim
+ return len(dims) > 0 and not dims[0].HasField("dim_value")
+
+
class ONNXExportMixin:
"""Mixin class that provides ONNX export functionality for objects that support it.
@@ -379,7 +387,10 @@ class ONNXExportMixin:
Raises:
RuntimeError: If `ONNX_EXPORTABLE` is False.
ValueError: If `input_shape` has a dynamic dimension and a rank other than the pseudo shape's, or
- a fixed entry of `input_shape` differs from the explicit `pseudo_shape`.
+ a 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.
FileNotFoundError: If `save` is True and the directory of `onnx_name` does not exist. This is
checked before the export runs.
@@ -411,6 +422,11 @@ class ONNXExportMixin:
- The dimensions marked `-1` are exported as dynamic: through `dynamic_shapes` on the dynamo exporter
from torch 2.9, through `dynamic_axes` otherwise. A `dynamic_axes` or `dynamic_shapes` keyword
argument 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
+ ``filter_as_zero`` declare such an output: their own ``to_onnx`` fixes the batch, and an export whose
+ batch 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.
- The model is exported with `torch.onnx.export`, with constant folding enabled.
"""
@@ -496,6 +512,19 @@ class ONNXExportMixin:
)
onnx_model = onnx.load(tmp_path)
+ # The batch of a per-image-list export can still come out dynamic: a ``dynamic_axes`` or ``dynamic_shapes``
+ # keyword replaces the dynamic dimensions derived from ``input_shape``, and a direct call of this method can
+ # mark the batch -1. The exported graph is checked rather than the arguments, whose forms differ between the
+ # exporters and between torch releases.
+ if _has_dynamic_batch(onnx_model):
+ hint = self._onnx_fixed_batch_hint(module, dummy_input)
+ if hint is not None:
+ raise ValueError(
+ f"{type(module).__name__} returns one output per image, so its ONNX export needs a fixed batch, "
+ "but the exported batch is dynamic (a -1 batch in input_shape, or a dynamic_axes or "
+ f"dynamic_shapes argument). Fix the batch there. {hint}"
+ )
+
# Later entries overwrite earlier ones, so the caller's metadata wins over the class's.
metadata = [*self.ADDITIONAL_METADATA, *(additional_metadata or [])]
onnx_model = kornia.onnx.utils.add_metadata(onnx_model, metadata)
@@ -503,6 +532,15 @@ class ONNXExportMixin:
onnx.save(onnx_model, onnx_name)
return onnx_model
+ def _onnx_fixed_batch_hint(self, module: Any, dummy_input: Any) -> Optional[str]:
+ """Return how to export ``module`` for a dynamic batch if it returns one output per image, else ``None``.
+
+ :meth:`to_onnx` calls it only when the exported graph has a dynamic batch, and raises when it returns a hint.
+ The default returns ``None`` and so checks nothing: a class whose model can return one output per image
+ overrides it.
+ """
+ return None
+
def _create_dummy_input(
self, input_shape: list[int], pseudo_shape: Optional[list[int]] = None
) -> Union[tuple[Any, ...], torch.Tensor]:
diff --git a/tests/models/test_box_filtering_onnx.py b/tests/models/test_box_filtering_onnx.py
index f9240a9e4..29e5ee16d 100644
--- a/tests/models/test_box_filtering_onnx.py
+++ b/tests/models/test_box_filtering_onnx.py
@@ -183,3 +183,93 @@ class TestBoxFilteringONNX(BaseTester):
for got, want in zip(actual, expected):
self.assert_close(torch.from_numpy(got), want)
assert sum(len(w) for w in expected) < 100 # the negative scores are dropped
+
+
+# A caller's batch override, by exporter: the TorchScript exporter reads ``dynamic_axes``, the dynamo exporter
+# ``dynamic_shapes``. The ``Dim`` hints are built in the test, since ``Dim.AUTO`` is missing from older torch releases.
+_DYNAMO_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"),
+]
+_BATCH_OVERRIDES = [
+ pytest.param(False, {"input": {0: "batch"}}, id="torchscript_axes_mapping"),
+ pytest.param(False, {"input": [0]}, id="torchscript_axes_list"),
+ pytest.param(True, ({0: "batch"},), id="torch_export_shapes_tuple", marks=_DYNAMO_MARKS),
+ pytest.param(True, {"boxes": {0: "batch"}}, id="torch_export_shapes_mapping", marks=_DYNAMO_MARKS),
+ pytest.param(True, (["batch", None, None],), id="torch_export_shapes_per_axis", marks=_DYNAMO_MARKS),
+ pytest.param(True, "AUTO", id="torch_export_dim_auto", marks=_DYNAMO_MARKS),
+ pytest.param(True, "DYNAMIC", id="torch_export_dim_dynamic", marks=_DYNAMO_MARKS),
+]
+
+
+def _override(dynamo, spec):
+ if dynamo:
+ if isinstance(spec, str):
+ spec = ({0: getattr(torch.export.Dim, spec)},)
+ return {"dynamo": True, "dynamic_shapes": spec}
+ return {"dynamo": False, "dynamic_axes": spec}
+
+
+class TestBoxFilteringONNXBatchOverride(BaseTester):
+ """A caller's dynamic_axes or dynamic_shapes cannot give a per-image list export a dynamic batch (#6111)."""
+
+ @pytest.mark.timeout(120)
+ @pytest.mark.parametrize(("dynamo", "spec"), _BATCH_OVERRIDES)
+ def test_list_export_rejects_a_dynamic_batch_override_6111(self, dynamo, spec, tmp_path):
+ """Each form of the override raises after the export, before the file is written."""
+ pytest.importorskip("onnx")
+ pytest.importorskip("onnxscript")
+ module = BoxFiltering(confidence_threshold=0.5, classes_to_keep=[0, 1, 2])
+ path = tmp_path / "filter.onnx"
+
+ with pytest.raises(ValueError, match="filter_as_zero=True"):
+ module.to_onnx(onnx_name=str(path), **_override(dynamo, spec))
+ assert not path.exists()
+
+ @pytest.mark.timeout(120)
+ @pytest.mark.parametrize(("dynamo", "spec"), _BATCH_OVERRIDES)
+ def test_filter_as_zero_accepts_a_dynamic_batch_override_6111(self, dynamo, spec):
+ """The tensor output follows any batch, so the same override exports a dynamic batch."""
+ pytest.importorskip("onnx")
+ pytest.importorskip("onnxscript")
+ module = BoxFiltering(confidence_threshold=0.5, classes_to_keep=[0, 1, 2], filter_as_zero=True)
+
+ exported = module.to_onnx(save=False, **_override(dynamo, spec))
+
+ assert exported.graph.input[0].type.tensor_type.shape.dim[0].dim_param
+
+ @pytest.mark.timeout(120)
+ @pytest.mark.parametrize(
+ ("dynamo", "spec"),
+ [
+ pytest.param(False, {"input": {1: "detections"}}, id="torchscript_detections_only"),
+ pytest.param(True, "STATIC", id="torch_export_dim_static", marks=_DYNAMO_MARKS),
+ ],
+ )
+ def test_list_export_accepts_an_override_with_a_fixed_batch_6111(self, dynamo, spec):
+ """An override that keeps the batch fixed is not rejected: the graph decides, not the keyword's form."""
+ pytest.importorskip("onnx")
+ pytest.importorskip("onnxscript")
+ if dynamo:
+ spec = ({0: torch.export.Dim.STATIC(), 1: torch.export.Dim("detections")},)
+ module = BoxFiltering(confidence_threshold=0.5, classes_to_keep=[0, 1, 2])
+
+ exported = module.to_onnx(save=False, **_override(dynamo, spec))
+
+ dims = exported.graph.input[0].type.tensor_type.shape.dim
+ assert dims[0].dim_value == 1
+ assert dims[1].dim_param
+
+ @pytest.mark.timeout(120)
+ def test_the_exported_model_decides_not_the_caller_6111(self):
+ """With ``model=``, the exported filter's ``filter_as_zero`` decides whether a dynamic batch raises."""
+ pytest.importorskip("onnx")
+ list_filter = BoxFiltering(confidence_threshold=0.5, classes_to_keep=[0, 1, 2])
+ zero_filter = BoxFiltering(confidence_threshold=0.5, classes_to_keep=[0, 1, 2], filter_as_zero=True)
+
+ # A filter_as_zero caller keeps the default input_shape, [-1, -1, 6], so the list filter gets a dynamic batch.
+ with pytest.raises(ValueError, match="filter_as_zero=True"):
+ zero_filter.to_onnx(model=list_filter, save=False, dynamo=False)
+ exported = list_filter.to_onnx(model=zero_filter, save=False, dynamo=False, dynamic_axes={"input": {0: "b"}})
+
+ assert exported.graph.input[0].type.tensor_type.shape.dim[0].dim_param == "b"
diff --git a/tests/models/test_rtdetr_onnx.py b/tests/models/test_rtdetr_onnx.py
index d20147e67..fc10ccd3f 100644
--- a/tests/models/test_rtdetr_onnx.py
+++ b/tests/models/test_rtdetr_onnx.py
@@ -323,6 +323,77 @@ def test_detector_with_a_custom_per_image_post_processor_exports_one_image():
assert_close(torch.from_numpy(detections), detector(images)[0])
+class _BatchedDetections(nn.Module):
+ """``_PerImageDetections`` as one ``(B, Q, 6)`` tensor, which follows any batch."""
+
+ def forward(self, logits: torch.Tensor, boxes: torch.Tensor, sizes: torch.Tensor) -> torch.Tensor:
+ scores, labels = logits.max(-1, keepdim=True)
+ return torch.cat([labels.to(boxes), scores, boxes], -1)
+
+
+_DYNAMIC_BATCH = [
+ pytest.param({"dynamo": False, "dynamic_axes": {"input": {0: "batch"}}}, id="torchscript"),
+ pytest.param(
+ {"dynamo": True, "dynamic_shapes": ({0: "batch"},)},
+ # conftest.py deselects IDs containing "dynamo" unless KORNIA_TEST_OPTIMIZER is set.
+ id="torch_export",
+ 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]("override", _DYNAMIC_BATCH)
+def test_detector_with_per_image_detections_rejects_a_dynamic_batch_override_6111(override):
+ """A caller's dynamic batch cannot reach a per-image list export, which would return one image's detections."""
+ pytest.importorskip("onnx")
+ pytest.importorskip("onnxscript")
+
+ detector = ObjectDetector(_ScoredDetections(), ResizePreProcessor(32, 32), _PerImageDetections())
+ with pytest.raises(ValueError, match="confidence_filtering=False"):
+ detector.to_onnx(image_size=32, save=False, **override)
+
+
[email protected]("override", _DYNAMIC_BATCH)
+def test_detector_with_batched_detections_accepts_a_dynamic_batch_override_6111(override):
+ """A detector whose output is one tensor exports the caller's dynamic batch and runs at another batch size."""
+ pytest.importorskip("onnx")
+ ort = pytest.importorskip("onnxruntime")
+ pytest.importorskip("onnxscript")
+
+ detector = ObjectDetector(_ScoredDetections(), ResizePreProcessor(32, 32), _BatchedDetections())
+ exported = detector.to_onnx(image_size=32, save=False, **override)
+ assert exported.graph.input[0].type.tensor_type.shape.dim[0].dim_param
+
+ images = torch.rand(3, 3, 32, 32, generator=torch.Generator().manual_seed(0))
+ session = ort.InferenceSession(exported.SerializeToString(), providers=["CPUExecutionProvider"])
+ (detections,) = session.run(None, {"input": images.numpy()})
+ assert_close(torch.from_numpy(detections), detector(images))
+
+
[email protected]("override", [pytest.param({}, id="default"), *_DYNAMIC_BATCH])
+def test_detector_model_only_onnx_of_a_per_image_detector_keeps_a_dynamic_batch_6111(override):
+ """Without the post-processor, the model's tensor outputs follow any batch, whatever the post-processor returns."""
+ _importorskip_exporter(override)
+ ort = pytest.importorskip("onnxruntime")
+
+ detector = ObjectDetector(_ScoredDetections(), ResizePreProcessor(32, 32), _PerImageDetections())
+ exported = detector.to_onnx(image_size=32, include_pre_and_post_processor=False, save=False, **override)
+ assert exported.graph.input[0].type.tensor_type.shape.dim[0].dim_param
+
+ images = torch.rand(3, 3, 32, 32, generator=torch.Generator().manual_seed(0))
+ session = ort.InferenceSession(exported.SerializeToString(), providers=["CPUExecutionProvider"])
+ scores, boxes = session.run(None, {"input": images.numpy()})
+ expected_scores, expected_boxes = detector.model(images)
+ assert_close(torch.from_numpy(scores), expected_scores)
+ assert_close(torch.from_numpy(boxes), expected_boxes)
+
+
class _NormalisedDetections(_ScoredDetections):
"""``_ScoredDetections`` behind a batch norm, whose statistics a forward pass in training mode would update."""
@@ -335,19 +406,25 @@ class _NormalisedDetections(_ScoredDetections):
@pytest.mark.timeout(120)
-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."""
[email protected]("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.
+
+ A batched detector exports a dynamic batch, so ``to_onnx`` runs it a second time for the check of #6111.
+ """
pytest.importorskip("onnx")
pytest.importorskip("onnxscript")
model = _NormalisedDetections()
- detector = ObjectDetector(model, ResizePreProcessor(32, 32), _PerImageDetections()).double().train()
+ post_processor = _PerImageDetections() if per_image else _BatchedDetections()
+ detector = ObjectDetector(model, ResizePreProcessor(32, 32), post_processor).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
+ batch = exported.graph.input[0].type.tensor_type.shape.dim[0]
+ assert batch.dim_value == 1 if per_image else batch.dim_param
assert torch.equal(model.norm.running_mean, running_mean)
assert model.norm.num_batches_tracked.item() == 0
assert detector.training