Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

fix(onnx): BoxFiltering exports on the torch 2.14 default exporter, and without a threshold filters at the eager default (#6159)

Dmytro Mishkinbb7471efe7d8
diff --git a/changelog.d/6159.breaking.md b/changelog.d/6159.breaking.md
new file mode 100644
index 000000000..898b38e03
--- /dev/null
+++ b/changelog.d/6159.breaking.md
@@ -0,0 +1 @@
+`BoxFiltering.to_onnx()` without a `confidence_threshold` on the legacy (TorchScript) exporter used to export a second float64 input, `onnx::Cast_1`, for the threshold, which the caller fed. The graph now has the boxes as its only input and filters at the eager default of `0.0`, so feeding two inputs raises; build the filter with `confidence_threshold` to export a different threshold.
diff --git a/changelog.d/6159.fixed.md b/changelog.d/6159.fixed.md
new file mode 100644
index 000000000..40a4b45ce
--- /dev/null
+++ b/changelog.d/6159.fixed.md
@@ -0,0 +1 @@
+The torch 2.14 default (dynamo) ONNX exporter now exports `BoxFiltering` and the detectors that contain it. With `dynamo=True` (the default from torch 2.9), a `BoxFiltering` without a `confidence_threshold` exported a graph that filtered at `0.1` wherever the export succeeded (torch 2.9.1, for example); it now filters at `0.0`, as eager does.
diff --git a/docs/source/models/rt_detr.rst b/docs/source/models/rt_detr.rst
index 5b20ccdfe..46645628d 100644
--- a/docs/source/models/rt_detr.rst
+++ b/docs/source/models/rt_detr.rst
@@ -38,7 +38,9 @@ Run it
Detections are filtered with ``confidence_threshold=0.3`` by default; pass a different value to ``build`` to keep
more or fewer boxes. ``detector.visualize(image, detections, output_type="pil")`` draws the boxes for you, and
-``detector.to_onnx("rtdetr-640.onnx", image_size=640)`` exports the model together with its pre- and post-processing.
+``detector.to_onnx("rtdetr-640.onnx", image_size=640)`` exports the model together with its pre- and
+post-processing. With the default confidence filtering the exported graph is for a batch of one image; build the
+detector with ``confidence_filtering=False`` to export a graph for any batch.
Available variants, from fastest to most accurate: ``rtdetr_r18vd``, ``rtdetr_r34vd``, ``rtdetr_r50vd_m``,
``rtdetr_r50vd`` and ``rtdetr_r101vd``. When ``build`` is given a ``model_name`` it always resizes the input to the
diff --git a/kornia/contrib/object_detection.py b/kornia/contrib/object_detection.py
index 4374e355b..23d404d10 100644
--- a/kornia/contrib/object_detection.py
+++ b/kornia/contrib/object_detection.py
@@ -356,6 +356,10 @@ 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:
+ The exported graph has one input, ``input``, the boxes. It filters at ``confidence_threshold``, held as a
+ constant, and at the eager default of ``0.0`` (keep boxes with a positive confidence) when none was given.
+
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
@@ -429,7 +433,7 @@ class BoxFiltering(nn.Module, ONNXExportMixin):
class_mask = (class_ids == classes_to_keep).any(dim=-1) # [B, D]
else:
# If no class filtering is needed, just use a mask of all `True`
- class_mask = (confidence_mask * 0 + 1).bool()
+ class_mask = torch.ones_like(confidence_mask)
# Combine the confidence and class masks
combined_mask = confidence_mask & class_mask # [B, D]
@@ -478,6 +482,10 @@ class BoxFiltering(nn.Module, ONNXExportMixin):
Raises:
ValueError: If ``input_shape`` marks the batch ``-1`` without ``filter_as_zero``.
+ Note:
+ The exported graph takes the boxes as its only input and filters at the threshold given to the
+ constructor, or at ``0.0`` when there is none, as eager does.
+
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
@@ -509,15 +517,12 @@ class BoxFiltering(nn.Module, ONNXExportMixin):
def _create_dummy_input(
self, input_shape: List[int], pseudo_shape: Optional[List[int]] = None
) -> Union[Tuple[Any, ...], torch.Tensor]:
- pseudo_input = torch.rand(
+ 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)
]
)
- if self.confidence_threshold is None:
- return pseudo_input, 0.1
- return pseudo_input
class RTDETRDetectorBuilder:
diff --git a/tests/models/test_box_filtering_onnx.py b/tests/models/test_box_filtering_onnx.py
index 7060c1bf8..f9240a9e4 100644
--- a/tests/models/test_box_filtering_onnx.py
+++ b/tests/models/test_box_filtering_onnx.py
@@ -21,7 +21,7 @@ import pytest
import torch
from kornia.contrib.object_detection import BoxFiltering
-from kornia.core._compat import torch_version_ge, torch_version_lt
+from kornia.core._compat import torch_version_lt
from testing.base import DYNAMO_UNAVAILABLE_REASON, BaseTester, dynamo_is_available
@@ -37,16 +37,6 @@ _EXPORTERS = [
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,
- ),
],
),
]
@@ -137,3 +127,59 @@ class TestBoxFilteringONNX(BaseTester):
boxes = _detections(batch, count)
(actual,) = session.run(None, {"input": boxes.numpy()})
self.assert_close(torch.from_numpy(actual), module(boxes))
+
+ @pytest.mark.timeout(120)
+ @pytest.mark.parametrize("dynamo", _EXPORTERS)
+ def test_filter_without_threshold_exports_one_input_6112(self, dynamo):
+ """A filter without a threshold exports one input and filters at the eager default, 0.0."""
+ pytest.importorskip("onnx")
+ pytest.importorskip("onnxscript")
+
+ module = BoxFiltering(filter_as_zero=True)
+ exported = module.to_onnx(save=False, dynamo=dynamo)
+ assert len(exported.graph.input) == 1
+
+ session = _session(exported)
+ boxes = torch.zeros(2, 50, 6)
+ boxes[:, :, 1] = torch.linspace(0.01, 0.99, 50)
+ boxes[:, :, 2:] = 1.0
+ (actual,) = session.run(None, {"input": boxes.numpy()})
+ assert int((torch.from_numpy(actual)[:, :, 1] > 0).sum()) == int((module(boxes)[:, :, 1] > 0).sum()) == 100
+
+ @pytest.mark.timeout(120)
+ @pytest.mark.parametrize("dynamo", _EXPORTERS)
+ def test_filter_with_threshold_keeps_it_as_a_constant_6112(self, dynamo):
+ """A thresholded filter still filters at its threshold, from one input."""
+ 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 len(exported.graph.input) == 1
+
+ boxes = torch.zeros(2, 50, 6)
+ boxes[:, :, 1] = torch.linspace(0.01, 0.99, 50)
+ (actual,) = _session(exported).run(None, {"input": boxes.numpy()})
+ self.assert_close(torch.from_numpy(actual), module(boxes))
+ assert int((torch.from_numpy(actual)[:, :, 1] > 0).sum()) == 50
+
+ @pytest.mark.timeout(120)
+ @pytest.mark.parametrize("dynamo", _EXPORTERS)
+ def test_list_filter_without_threshold_exports_one_input_6112(self, dynamo):
+ """List mode without a threshold exports one input and matches eager at the eager default, 0.0."""
+ pytest.importorskip("onnx")
+ pytest.importorskip("onnxscript")
+
+ module = BoxFiltering()
+ exported = module.to_onnx(save=False, input_shape=[2, -1, 6], dynamo=dynamo)
+ assert len(exported.graph.input) == 1
+
+ boxes = torch.zeros(2, 50, 6)
+ boxes[:, :, 1] = torch.linspace(-0.2, 0.99, 50)
+ boxes[:, :, 2:] = 1.0
+ actual = _session(exported).run(None, {"input": boxes.numpy()})
+ expected = module(boxes)
+ assert len(actual) == len(expected) == 2
+ 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
diff --git a/tests/models/test_object_detector.py b/tests/models/test_object_detector.py
index f9d0e5bda..d94b96574 100644
--- a/tests/models/test_object_detector.py
+++ b/tests/models/test_object_detector.py
@@ -23,7 +23,7 @@ import pytest
import torch
import kornia
-from kornia.core._compat import torch_version_ge, torch_version_lt
+from kornia.core._compat import torch_version_lt
from kornia.models.rt_detr import RTDETR, DETRPostProcessor, RTDETRConfig
from testing.base import BaseTester
@@ -128,18 +128,6 @@ class TestObjectDetector(BaseTester):
@pytest.mark.slow
@pytest.mark.timeout(120)
@pytest.mark.skipif(torch_version_lt(2, 0, 0), reason="Unsupported ONNX opset version: 16")
- @pytest.mark.xfail(
- 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: "
- "DispatchError 'No ONNX function found for aten.mul.Scalar'. Same exporter gap as "
- "test_sam_onnx.py::test_sam_encoder_to_onnx; not yet reported upstream"
- ),
- raises=torch.onnx.OnnxExporterError,
- # Strict, as in test_sam_onnx.py: an upstream fix inside 2.14.x must announce itself as
- # an XPASS rather than sit silent until the 2.15 bound expires. Both variants fail today.
- strict=True,
- )
@pytest.mark.parametrize("variant", ["resnet50d", "hgnetv2_l"])
def test_onnx(self, device, dtype, tmp_path: Path, variant: str):
config = RTDETRConfig(variant, 1)
diff --git a/tests/models/test_rtdetr_onnx.py b/tests/models/test_rtdetr_onnx.py
index 5d16bb6cf..d20147e67 100644
--- a/tests/models/test_rtdetr_onnx.py
+++ b/tests/models/test_rtdetr_onnx.py
@@ -277,17 +277,6 @@ class _ScoredDetections(nn.Module):
@pytest.mark.timeout(120)
- 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")