Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

fix(filters): export GaussianBlur2d with dynamic axes on the legacy ONNX exporter (#5650)

mohamed shabanc1b221bca26e
diff --git a/changelog.d/5650.fixed.md b/changelog.d/5650.fixed.md
new file mode 100644
index 000000000..bad286b6d
--- /dev/null
+++ b/changelog.d/5650.fixed.md
@@ -0,0 +1 @@
+`GaussianBlur2d`, and `UnsharpMask` which blurs with it, now export through the legacy ONNX exporter (`torch.onnx.export(..., dynamo=False)`, the default on torch 2.5.1) with a dynamic batch, height and width. The export used to fail with "Unsupported: ONNX export of convolution for kernel of unknown shape". A per-sample `sigma` keeps a static batch, and its height and width are dynamic too.
diff --git a/kornia/filters/filter.py b/kornia/filters/filter.py
index ba0604dd4..a131daa0f 100644
--- a/kornia/filters/filter.py
+++ b/kornia/filters/filter.py
@@ -169,7 +169,10 @@ def filter2d(
if normalized:
tmp_kernel = normalize_kernel2d(tmp_kernel)
- tmp_kernel = tmp_kernel.expand(-1, c, -1, -1)
+ # The legacy ONNX tracer records ``input.shape`` reads as graph values, so with a dynamic batch or size the
+ # expanded kernel, and with it the convolution weight, has no static shape and the export fails (#5222).
+ # The channel count sets the convolution's ``groups``, which ONNX needs as a constant anyway: read it as an int.
+ tmp_kernel = tmp_kernel.expand(-1, int(c) if torch.jit.is_tracing() else c, -1, -1)
height, width = tmp_kernel.shape[-2:]
diff --git a/tests/core/test_onnx_mixin.py b/tests/core/test_onnx_mixin.py
index bb33aabf9..56ab5abb8 100644
--- a/tests/core/test_onnx_mixin.py
+++ b/tests/core/test_onnx_mixin.py
@@ -112,9 +112,9 @@ class TestONNXExportMixin(BaseTester):
ids=["conv", "gaussian_blur"],
)
def test_saved_model_has_the_documented_opset(self, tmp_path, channels, module):
+ """Test that the saved ONNX model uses the documented opset."""
# The dynamo exporter builds opset 18 and down-converts a lower request only when every op has an adapter, which
- # a convolution has and the blur's ``Pad`` has not. Static shapes: the legacy exporter cannot export
- # GaussianBlur2d with a dynamic dimension, even the batch alone (#5222).
+ # a convolution has and the blur's ``Pad`` has not.
path = tmp_path / "model.onnx"
shape = [2, channels, 16, 16]
op = ImageSequential(module()).to_onnx(onnx_name=str(path), input_shape=shape, output_shape=shape)
diff --git a/tests/filters/test_gaussian.py b/tests/filters/test_gaussian.py
index 7d8c0757e..9f71dd579 100644
--- a/tests/filters/test_gaussian.py
+++ b/tests/filters/test_gaussian.py
@@ -39,7 +39,14 @@ from kornia.filters import (
)
from kornia.filters.kernels import gaussian_discrete, gaussian_discrete_erf
-from testing.base import BaseTester, assert_close, supports_reflect_padding, supports_replicate_padding
+from testing.base import (
+ DYNAMIC_EXPORT_UNAVAILABLE_REASON,
+ BaseTester,
+ assert_close,
+ dynamic_export_is_available,
+ supports_reflect_padding,
+ supports_replicate_padding,
+)
@pytest.mark.parametrize(
@@ -535,6 +542,84 @@ class TestGaussianBlur2d(BaseTester):
torch.onnx.export(model, sample_input, buf, **export_kwargs)
assert buf.getbuffer().nbytes > 0
+ # a dynamic batch and spatial size used to leave the convolution weight without a static shape (#5222)
+ dynamic_buf = io.BytesIO()
+ dynamic_axes = {
+ "input": {0: "batch", 2: "height", 3: "width"},
+ "output": {0: "batch", 2: "height", 3: "width"},
+ }
+ with warnings.catch_warnings():
+ warnings.simplefilter("ignore")
+ torch.onnx.export(model, sample_input, dynamic_buf, dynamic_axes=dynamic_axes, **export_kwargs)
+ assert dynamic_buf.getbuffer().nbytes > 0
+
+ @pytest.mark.device_agnostic
+ def test_onnx_export_legacy_dynamic_matches_eager(self, dtype):
+ """Test that a dynamic-axes legacy export of GaussianBlur2d matches eager execution."""
+ if dtype != torch.float32:
+ pytest.skip("the exported graph is checked once, in float32")
+ pytest.importorskip("onnx")
+ ort = pytest.importorskip("onnxruntime")
+ model = GaussianBlur2d((3, 3), (1.5, 1.5))
+ sample_input = torch.rand(1, 3, 8, 8, dtype=dtype)
+ buf = io.BytesIO()
+ export_kwargs: dict[str, Any] = {
+ "input_names": ["input"],
+ "output_names": ["output"],
+ "opset_version": 17,
+ "dynamic_axes": {
+ "input": {0: "batch", 2: "height", 3: "width"},
+ "output": {0: "batch", 2: "height", 3: "width"},
+ },
+ }
+ if torch_version_ge(2, 5, 0):
+ export_kwargs["dynamo"] = False
+ with warnings.catch_warnings():
+ warnings.simplefilter("ignore")
+ torch.onnx.export(model, sample_input, buf, **export_kwargs)
+ session = ort.InferenceSession(buf.getvalue(), providers=["CPUExecutionProvider"])
+ for image in (sample_input, torch.rand(2, 3, 5, 9, dtype=dtype)):
+ exported = torch.from_numpy(session.run(None, {"input": image.numpy()})[0])
+ self.assert_close(exported, model(image))
+
+ @pytest.mark.device_agnostic
+ def test_onnx_export_legacy_dynamic_size_per_sample_sigma_matches_eager(self, dtype):
+ """Test that a per-sample sigma keeps a static batch but exports a dynamic height and width (#5222)."""
+ if dtype != torch.float32:
+ pytest.skip("the exported graph is checked once, in float32")
+ pytest.importorskip("onnx")
+ ort = pytest.importorskip("onnxruntime")
+ model = GaussianBlur2d((3, 5), torch.tensor([[1.5, 0.7], [0.5, 2.0]], dtype=dtype))
+ sample_input = torch.rand(2, 3, 8, 8, dtype=dtype)
+ buf = io.BytesIO()
+ export_kwargs: dict[str, Any] = {
+ "input_names": ["input"],
+ "output_names": ["output"],
+ "opset_version": 17,
+ "dynamic_axes": {"input": {2: "height", 3: "width"}, "output": {2: "height", 3: "width"}},
+ }
+ if torch_version_ge(2, 5, 0):
+ export_kwargs["dynamo"] = False
+ with warnings.catch_warnings():
+ warnings.simplefilter("ignore")
+ torch.onnx.export(model, sample_input, buf, **export_kwargs)
+ session = ort.InferenceSession(buf.getvalue(), providers=["CPUExecutionProvider"])
+ for image in (sample_input, torch.rand(2, 3, 5, 9, dtype=dtype)):
+ exported = torch.from_numpy(session.run(None, {"input": image.numpy()})[0])
+ self.assert_close(exported, model(image))
+
+ @pytest.mark.device_agnostic
+ @pytest.mark.skipif(not dynamic_export_is_available(), reason=DYNAMIC_EXPORT_UNAVAILABLE_REASON)
+ def test_torch_export_dynamic_channels_matches_eager(self, dtype):
+ """Test that torch.export keeps a dynamic channel axis; only the legacy tracer reads it as an int (#5222)."""
+ if dtype != torch.float32:
+ pytest.skip("the exported graph is checked once, in float32")
+ model = GaussianBlur2d((3, 3), (1.5, 1.5))
+ channels = torch.export.Dim("channels", min=2, max=16)
+ exported = torch.export.export(model, (torch.rand(2, 3, 8, 8, dtype=dtype),), dynamic_shapes=({1: channels},))
+ image = torch.rand(2, 5, 8, 8, dtype=dtype)
+ self.assert_close(exported.module()(image), model(image))
+
@pytest.mark.device_agnostic
# 2.5 is where `dynamo=` first exists, but there it still routes through the experimental
# `_compat.export_compat` shim. This test passes `fallback=False` implicitly, so on the 2.5.1
diff --git a/tests/onnx/test_sequential.py b/tests/onnx/test_sequential.py
index a01458e52..d0bc18f6d 100644
--- a/tests/onnx/test_sequential.py
+++ b/tests/onnx/test_sequential.py
@@ -133,8 +133,6 @@ class TestONNXSequentialOfKorniaExports:
from kornia.core import ImageSequential
from kornia.filters import GaussianBlur2d
- # Static shapes: the legacy exporter cannot export GaussianBlur2d with a dynamic dimension, even the batch
- # alone (#5222).
shapes = {"input_shape": [2, 1, 16, 16], "output_shape": [2, 1, 16, 16]}
blur = ImageSequential(GaussianBlur2d((3, 3), (1.5, 1.5)))
sigmoid = ImageSequential(torch.nn.Sigmoid())