π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
fix(filters): export blur pools with legacy ONNX (#5765)
A Aswanth Raj5bbdd23d19ff
diff --git a/changelog.d/5765.fixed.md b/changelog.d/5765.fixed.mdnew file mode 100644index 000000000..bcd81f18d--- /dev/null+++ b/changelog.d/5765.fixed.md@@ -0,0 +1 @@+The blur-pool functions and modules export through the legacy ONNX exporter with dynamic batch, height and width. Edge-aware blur pooling combines its edge maps with a boolean OR instead of adding booleans, so it also exports with static shapes, and its dynamo export on torch 2.14 no longer gives a graph that onnxruntime rejects. `EdgeAwareBlurPool2D.forward` takes `epsilon=None` (meaning `1e-6`) by default, so a legacy export of the module no longer adds `epsilon` as a second graph input.diff --git a/kornia/filters/blur_pool.py b/kornia/filters/blur_pool.pyindex c6a177506..70f1121eb 100644--- a/kornia/filters/blur_pool.py+++ b/kornia/filters/blur_pool.py@@ -95,7 +95,9 @@ class BlurPool2D(nn.Module):on the input size and ``self.stride``."""kernel = self.kernel.to(device=input.device, dtype=input.dtype)- return _blur_pool_by_kernel2d(input, kernel.repeat((input.shape[1], 1, 1, 1)), self.stride)+ # ONNX requires constant convolution groups and kernel shape, even with dynamic batch or spatial axes.+ channels = int(input.shape[1]) if torch.jit.is_tracing() else input.shape[1]+ return _blur_pool_by_kernel2d(input, kernel.repeat((channels, 1, 1, 1)), self.stride)class MaxBlurPool2D(nn.Module):@@ -177,9 +179,8 @@ class MaxBlurPool2D(nn.Module):and ``self.stride``."""kernel = self.kernel.to(device=input.device, dtype=input.dtype)- return _max_blur_pool_by_kernel2d(- input, kernel.repeat((input.size(1), 1, 1, 1)), self.stride, self.max_pool_size- )+ channels = int(input.shape[1]) if torch.jit.is_tracing() else input.shape[1]+ return _max_blur_pool_by_kernel2d(input, kernel.repeat((channels, 1, 1, 1)), self.stride, self.max_pool_size)class EdgeAwareBlurPool2D(nn.Module):@@ -209,7 +210,7 @@ class EdgeAwareBlurPool2D(nn.Module):self.edge_threshold = edge_thresholdself.edge_dilation_kernel_size = edge_dilation_kernel_size- def forward(self, input: torch.Tensor, epsilon: float = 1e-6) -> torch.Tensor:+ def forward(self, input: torch.Tensor, epsilon: float | None = None) -> torch.Tensor:"""Downsample while adapting the blur near image or feature edges.Edge-aware blur pooling estimates where strong local changes occur and@@ -223,12 +224,15 @@ class EdgeAwareBlurPool2D(nn.Module):channels, :math:`H` is the input height, and :math:`W` is theinput width.epsilon: Small positive value added to the input before the- logarithm of the edge test.+ logarithm of the edge test. ``None`` means ``1e-6``, which keeps the legacy ONNX exporter from+ turning the default into a graph input.Returns:Edge-aware blurred tensor with the shape of ``input``,:math:`(B, C, H, W)`."""+ if epsilon is None:+ epsilon = 1e-6return edge_aware_blur_pool2d(input, self.kernel_size, self.edge_threshold, self.edge_dilation_kernel_size, epsilon)@@ -279,8 +283,9 @@ def blur_pool2d(input: torch.Tensor, kernel_size: tuple[int, int] | int, stride:[0.0000, 0.0625, 0.3125]]]])"""+ channels = int(input.shape[1]) if torch.jit.is_tracing() else input.shape[1]kernel = get_pascal_kernel_2d(kernel_size, norm=True, device=input.device, dtype=input.dtype).repeat(- (input.size(1), 1, 1, 1)+ (channels, 1, 1, 1))return _blur_pool_by_kernel2d(input, kernel, stride)@@ -325,8 +330,9 @@ def max_blur_pool2d(_warn_ceil_mode_deprecated(ceil_mode)KORNIA_CHECK_SHAPE(input, ["B", "C", "H", "W"])+ channels = int(input.shape[1]) if torch.jit.is_tracing() else input.shape[1]kernel = get_pascal_kernel_2d(kernel_size, norm=True, device=input.device, dtype=input.dtype).repeat(- (input.shape[1], 1, 1, 1)+ (channels, 1, 1, 1))return _max_blur_pool_by_kernel2d(input, kernel, stride, max_pool_size)@@ -450,10 +456,10 @@ def edge_aware_blur_pool2d(edges_y = log_input[..., 4:, :] - log_input[..., :-4, :]edges_x, edges_y = edges_x.mean(dim=-3, keepdim=True), edges_y.mean(dim=-3, keepdim=True)edges_x_mask, edges_y_mask = edges_x.abs() > log_thresh.to(edges_x), edges_y.abs() > log_thresh.to(edges_y)- edges_xy_mask = (edges_x_mask[..., 2:-2, :] + edges_y_mask[..., :, 2:-2]).type_as(input)+ edges_xy_mask = (edges_x_mask[..., 2:-2, :] | edges_y_mask[..., :, 2:-2]).type_as(input)# dilate the content edges to have a soft mask of edges- dilated_edges = F.max_pool3d(edges_xy_mask, edge_dilation_kernel_size, 1, edge_dilation_kernel_size // 2)+ dilated_edges = F.max_pool2d(edges_xy_mask, edge_dilation_kernel_size, 1, edge_dilation_kernel_size // 2)# slice the padded regionsblurred_input = blurred_input[..., blur_pad_y:-blur_pad_y, blur_pad_x:-blur_pad_x]diff --git a/tests/filters/test_blur_pool.py b/tests/filters/test_blur_pool.pyindex 546bcd706..22e0f0620 100644--- a/tests/filters/test_blur_pool.py+++ b/tests/filters/test_blur_pool.py@@ -15,8 +15,10 @@# limitations under the License.#+import ioimport mathimport warnings+from collections.abc import Callableimport numpy as npimport pytest@@ -33,7 +35,84 @@ from kornia.filters import (max_blur_pool2d,)-from testing.base import BaseTester, supports_reflect_padding+from testing.base import BaseTester, dynamic_export_is_available, supports_reflect_padding+++class _FunctionalBlurPool(torch.nn.Module):+ def __init__(self, function: Callable, kernel_size: int) -> None:+ super().__init__()+ self.function = function+ self.kernel_size = kernel_size++ def forward(self, input: torch.Tensor) -> torch.Tensor:+ return self.function(input, self.kernel_size)+++class TestBlurPoolLegacyONNX(BaseTester):+ @pytest.mark.device_agnostic+ @pytest.mark.parametrize("pool", ["blur", "max", "edge"])+ @pytest.mark.parametrize("as_module", [True, False])+ @pytest.mark.parametrize("dynamic", [True, False])+ @pytest.mark.parametrize("kernel_size", [3, 4])+ def test_export_matches_eager(self, dtype, pool, as_module, dynamic, kernel_size):+ """Pin legacy export and runtime behavior for every blur-pool caller (#5753)."""+ if dtype != torch.float32:+ pytest.skip("the exported graph is checked once, in float32")+ pytest.importorskip("onnx")+ ort = pytest.importorskip("onnxruntime")+ module, function = {+ "blur": (BlurPool2D, blur_pool2d),+ "max": (MaxBlurPool2D, max_blur_pool2d),+ "edge": (EdgeAwareBlurPool2D, edge_aware_blur_pool2d),+ }[pool]+ # Export the module itself, as users do: a wrapper would hide forward's extra arguments from the exporter.+ model = module(kernel_size) if as_module else _FunctionalBlurPool(function, kernel_size)+ sample = torch.arange(240, dtype=dtype).reshape(1, 3, 8, 10) / 240 + 0.1+ axes = {"input": {0: "batch", 2: "height", 3: "width"}, "output": {0: "batch", 2: "height", 3: "width"}}+ buf = io.BytesIO()+ with warnings.catch_warnings():+ warnings.simplefilter("ignore")+ torch.onnx.export(+ model,+ (sample,),+ buf, # ty: ignore[invalid-argument-type] # The legacy exporter accepts BytesIO.+ input_names=["input"],+ output_names=["output"],+ opset_version=17,+ dynamic_axes=axes if dynamic else None,+ dynamo=False,+ )+ session = ort.InferenceSession(buf.getvalue(), providers=["CPUExecutionProvider"])+ assert [graph_input.name for graph_input in session.get_inputs()] == ["input"]+ images = [sample]+ if dynamic:+ images.append(torch.arange(2 * 3 * 11 * 13, dtype=dtype).reshape(2, 3, 11, 13) / 858 + 0.1)+ for image in images:+ actual = torch.from_numpy(session.run(None, {"input": image.numpy()})[0])+ self.assert_close(actual, model(image))++ @pytest.mark.device_agnostic+ @pytest.mark.parametrize("pool", ["blur", "max", "edge"])+ @pytest.mark.parametrize("as_module", [True, False])+ def test_torch_export_dynamic_channels(self, dtype, pool, as_module):+ """The tracing-only channel conversion preserves symbolic channels in torch.export."""+ if dtype != torch.float32:+ pytest.skip("the exported graph is checked once, in float32")+ if not dynamic_export_is_available():+ pytest.skip("named dynamic export is unavailable on this Torch/Python pair")+ module, function = {+ "blur": (BlurPool2D, blur_pool2d),+ "max": (MaxBlurPool2D, max_blur_pool2d),+ "edge": (EdgeAwareBlurPool2D, edge_aware_blur_pool2d),+ }[pool]+ model = module(3) if as_module else _FunctionalBlurPool(function, 3)+ sample = torch.arange(3 * 8 * 10, dtype=dtype).reshape(1, 3, 8, 10) / 240 + 0.1+ exported = torch.export.export(+ model, (sample,), dynamic_shapes=({1: torch.export.Dim("channels", min=1, max=16)},)+ ).module()+ for channels in (1, 3, 5):+ image = torch.ones(1, channels, 8, 10, dtype=dtype)+ self.assert_close(exported(image), model(image))def _zero_padded_reference(x: torch.Tensor, k: int, s: int) -> torch.Tensor: