Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

fix(onnx): fix BoxFiltering batch size for per-image outputs (#6086)

Muhammad Talha829e38a5ec89
diff --git a/changelog.d/6086.fixed.md b/changelog.d/6086.fixed.md
new file mode 100644
index 000000000..02de0148e
--- /dev/null
+++ b/changelog.d/6086.fixed.md
@@ -0,0 +1 @@
+`BoxFiltering.to_onnx` without `filter_as_zero` now exports a fixed batch: the batch of `input_shape`, else of `pseudo_shape`, else one image. With the TorchScript exporter (the default before torch 2.9), the graph used to declare a dynamic batch but return only the traced batch's per-image outputs: it ran correctly only at a batch of 5, failed in ONNX Runtime at smaller batches and silently dropped images at larger ones. The dynamo exporter failed. Pass `input_shape=[5, -1, 6]` to keep exporting for 5 images. An `input_shape` with a dynamic (`-1`) batch now raises a `ValueError` that points to `filter_as_zero=True`, which exports a batch of any size as one `(B, D, 6)` tensor.
diff --git a/kornia/contrib/object_detection.py b/kornia/contrib/object_detection.py
index 8dcc1d391..8add5f237 100644
--- a/kornia/contrib/object_detection.py
+++ b/kornia/contrib/object_detection.py
@@ -323,6 +323,11 @@ class BoxFiltering(nn.Module, ONNXExportMixin):
classes_to_keep: a 1-d list of classes to keep. If None, keep all classes.
filter_as_zero: whether to filter boxes as zero.
+ Note:
+ Without ``filter_as_zero``, ONNX export produces one output tensor per image, so the batch must be fixed.
+ :meth:`to_onnx` defaults to a batch of one image. Use ``filter_as_zero=True`` to export a dynamic batch
+ as one ``(B, D, 6)`` tensor.
+
"""
ONNX_DEFAULT_INPUTSHAPE: ClassVar[List[int]] = [-1, -1, 6]
@@ -408,6 +413,66 @@ class BoxFiltering(nn.Module, ONNXExportMixin):
return filtered_boxes_list
+ def to_onnx(
+ self,
+ onnx_name: Optional[str] = None,
+ input_shape: Optional[list[int]] = None,
+ output_shape: Optional[list[int]] = None,
+ pseudo_shape: Optional[list[int]] = None,
+ model: Optional[nn.Module] = None,
+ save: bool = True,
+ additional_metadata: Optional[list[tuple[str, str]]] = None,
+ **kwargs: Any,
+ ) -> onnx.ModelProto:
+ """Export the filter with a fixed batch for per-image list outputs.
+
+ Args:
+ onnx_name: The output file name. Defaults to ``Kornia-BoxFiltering.onnx``.
+ input_shape: The ``[B, D, 6]`` input shape, with ``-1`` for a dynamic dimension. Defaults to
+ ``[1, -1, 6]`` without ``filter_as_zero`` and ``[-1, -1, 6]`` with it.
+ output_shape: The output shape used by the legacy TorchScript exporter. Defaults to ``[-1, 6]``
+ without ``filter_as_zero`` and ``[-1, -1, 6]`` with it. The dynamo exporter infers output shapes.
+ pseudo_shape: The dummy input shape used for tracing. Without ``filter_as_zero`` and ``input_shape``,
+ its batch is the exported batch. Explicit input and pseudo shapes must agree on fixed dimensions.
+ model: The model to export. Defaults to this filter.
+ save: Whether to save the exported model to ``onnx_name``.
+ additional_metadata: Additional metadata to add to the ONNX model.
+ **kwargs: Additional arguments to :func:`torch.onnx.export`.
+
+ Returns:
+ The exported ONNX model.
+
+ Raises:
+ ValueError: If ``input_shape`` marks the batch ``-1`` without ``filter_as_zero``.
+
+ Note:
+ The exporters flatten the Python list into a fixed number of graph outputs. Without ``filter_as_zero``,
+ the batch is therefore fixed: at the batch of ``input_shape``, else of ``pseudo_shape``, else at 1. ONNX
+ Runtime rejects other batch sizes. Each image's number of retained detections remains dynamic.
+ Use ``filter_as_zero=True`` for one ``(B, D, 6)`` output with a dynamic batch.
+
+ """
+ if not self.filter_as_zero:
+ if input_shape is None:
+ input_shape = [1 if pseudo_shape is None else pseudo_shape[0], *self.ONNX_DEFAULT_INPUTSHAPE[1:]]
+ if input_shape and input_shape[0] == -1:
+ raise ValueError(
+ "BoxFiltering returns one ONNX output per image without filter_as_zero and requires a fixed batch. "
+ "Fix the batch in input_shape, or use filter_as_zero=True to export a dynamic batch."
+ )
+ if output_shape is None:
+ output_shape = [-1, 6]
+ return super().to_onnx(
+ onnx_name=onnx_name,
+ input_shape=input_shape,
+ output_shape=output_shape,
+ pseudo_shape=pseudo_shape,
+ model=model,
+ save=save,
+ additional_metadata=additional_metadata,
+ **kwargs,
+ )
+
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
new file mode 100644
index 000000000..7060c1bf8
--- /dev/null
+++ b/tests/models/test_box_filtering_onnx.py
@@ -0,0 +1,139 @@
+# LICENSE HEADER MANAGED BY add-license-header
+#
+# Copyright 2018 Kornia Team
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+
+"""ONNX export tests for BoxFiltering (#6077)."""
+
+import pytest
+import torch
+
+from kornia.contrib.object_detection import BoxFiltering
+from kornia.core._compat import torch_version_ge, torch_version_lt
+
+from testing.base import DYNAMO_UNAVAILABLE_REASON, BaseTester, dynamo_is_available
+
+# ONNX Runtime's CPU provider is exercised regardless of the selected device or dtype.
+pytestmark = pytest.mark.device_agnostic
+
+_EXPORTERS = [
+ pytest.param(False, id="torchscript"),
+ pytest.param(
+ True,
+ # 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"),
+ pytest.mark.xfail(
+ torch_version_ge(2, 14) and torch_version_lt(2, 15, 0),
+ reason=(
+ "torch 2.14's CPU ONNX exporter cannot translate aten.mul.Scalar in the class mask: "
+ "No decompositions registered for the real-valued input; "
+ "also affects test_sam_onnx.py::test_sam_encoder_to_onnx"
+ ),
+ raises=torch.onnx.OnnxExporterError,
+ strict=torch.version.cuda is None,
+ ),
+ ],
+ ),
+]
+
+
+def _detections(batch: int, count: int) -> torch.Tensor:
+ """Create repeatable CPU detections for comparisons with ONNX Runtime."""
+ return torch.rand(batch, count, 6, generator=torch.Generator().manual_seed(0))
+
+
+def _session(exported):
+ """Validate the exported graph and load it with ONNX Runtime's CPU provider."""
+ onnx = pytest.importorskip("onnx")
+ ort = pytest.importorskip("onnxruntime")
+ onnx.checker.check_model(exported)
+ return ort.InferenceSession(exported.SerializeToString(), providers=["CPUExecutionProvider"])
+
+
+class TestBoxFilteringONNX(BaseTester):
+ """Check batch contracts and runtime results for both BoxFiltering output modes."""
+
+ @pytest.mark.timeout(120)
+ @pytest.mark.parametrize("dynamo", _EXPORTERS)
+ @pytest.mark.parametrize(
+ ("input_shape", "pseudo_shape", "batch"),
+ [(None, None, 1), (None, [3, 20, 6], 3), ([3, -1, 6], None, 3)],
+ ids=["default", "pseudo_batch_3", "input_batch_3"],
+ )
+ def test_list_export_fixes_the_batch_6077(self, dynamo, input_shape, pseudo_shape, batch):
+ """Fix the batch in the graph input, keep detection counts dynamic, and reject every other batch."""
+ pytest.importorskip("onnx")
+ pytest.importorskip("onnxscript")
+ ort = pytest.importorskip("onnxruntime")
+
+ module = BoxFiltering(confidence_threshold=0.5)
+ exported = module.to_onnx(save=False, input_shape=input_shape, pseudo_shape=pseudo_shape, dynamo=dynamo)
+
+ dims = exported.graph.input[0].type.tensor_type.shape.dim
+ assert dims[0].dim_value == batch
+ assert dims[1].dim_param
+ assert len(exported.graph.output) == batch
+ assert [d.dim_value for d in exported.graph.output[0].type.tensor_type.shape.dim][1:] == [6]
+
+ session = _session(exported)
+ # The trace has 20 detections; the runtime count must remain dynamic.
+ for count, empty_first in ((7, True), (33, False)):
+ boxes = _detections(batch, count)
+ if empty_first:
+ boxes[0, :, 1] = 0.1 # No detection kept.
+ if batch > 1:
+ boxes[-1, :, 1] = 0.9 # Every detection kept.
+ actual = session.run(None, {"input": boxes.numpy()})
+ expected = module(boxes)
+ assert len(actual) == len(expected) == batch
+ for got, want in zip(actual, expected):
+ self.assert_close(torch.from_numpy(got), want)
+
+ for other in (2, 5):
+ with pytest.raises(ort.capi.onnxruntime_pybind11_state.InvalidArgument, match=f"Expected: {batch}"):
+ session.run(None, {"input": _detections(other, 20).numpy()})
+
+ @pytest.mark.parametrize("input_shape", [[-1, -1, 6], [-1, 20, 6]])
+ def test_list_export_rejects_a_dynamic_batch_6077(self, input_shape):
+ """Point callers asking for a dynamic batch to the tensor-output mode."""
+ with pytest.raises(ValueError, match="filter_as_zero=True"):
+ BoxFiltering(confidence_threshold=0.5).to_onnx(save=False, input_shape=input_shape)
+
+ def test_explicit_shapes_must_agree(self):
+ """Reject a pseudo batch that conflicts with an explicitly fixed input batch."""
+ with pytest.raises(ValueError, match="input_shape"):
+ BoxFiltering(confidence_threshold=0.5).to_onnx(save=False, input_shape=[3, -1, 6], pseudo_shape=[5, 20, 6])
+
+ @pytest.mark.timeout(120)
+ @pytest.mark.parametrize("dynamo", _EXPORTERS)
+ def test_filter_as_zero_keeps_a_dynamic_batch_6077(self, dynamo):
+ """Match eager tensor outputs at batches both smaller and larger than the traced batch."""
+ pytest.importorskip("onnx")
+ pytest.importorskip("onnxscript")
+
+ module = BoxFiltering(confidence_threshold=0.5, filter_as_zero=True)
+ exported = module.to_onnx(save=False, dynamo=dynamo)
+ assert exported.graph.input[0].type.tensor_type.shape.dim[0].dim_param
+ assert len(exported.graph.output) == 1
+
+ session = _session(exported)
+ # The trace has a batch of 5 and 20 detections.
+ for batch, count in ((1, 20), (3, 7), (5, 20), (7, 33)):
+ boxes = _detections(batch, count)
+ (actual,) = session.run(None, {"input": boxes.numpy()})
+ self.assert_close(torch.from_numpy(actual), module(boxes))