π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
Fix Resize ONNX export compatibility Make β¦ (#3463)
Arjit Rawatfe1a7d9b054e
diff --git a/kornia/geometry/transform/affwarp.py b/kornia/geometry/transform/affwarp.pyindex a91b8b05e..b4a36af5c 100644--- a/kornia/geometry/transform/affwarp.py+++ b/kornia/geometry/transform/affwarp.py@@ -15,7 +15,6 @@# limitations under the License.#-import warningsfrom typing import Optional, Tuple, Unionimport torch@@ -24,7 +23,6 @@ from torch import nnfrom kornia.core.ops import eye_likefrom kornia.core.utils import _extract_device_dtypefrom kornia.filters import gaussian_blur2d-from kornia.image.utils import perform_keep_shape_imagefrom .imgwarp import get_affine_matrix2d, get_projective_transform, get_rotation_matrix2d, warp_affine, warp_affine3d@@ -550,7 +548,6 @@ def _side_to_image_size(side_size: int, aspect_ratio: float, side: str = "short"return int(side_size / aspect_ratio), side_size-@perform_keep_shape_imagedef resize(input: torch.Tensor,size: Union[int, Tuple[int, int]],@@ -594,45 +591,45 @@ def resize(if len(input.shape) < 2:raise ValueError(f"Input tensor must have at least two dimensions. Got {len(input.shape)}")- input_size = h, w = input.shape[-2:]+ original_shape = input.shape+ h, w = input.shape[-2:]if isinstance(size, int):- if torch.onnx.is_in_onnx_export():- warnings.warn(- "Please pass the size with a tuple when exporting to ONNX to correct the tracing.", stacklevel=1- )aspect_ratio = w / hsize = _side_to_image_size(size, aspect_ratio, side)-- # Skip this dangerous if-else when converting to ONNX.- if not torch.onnx.is_in_onnx_export():- if size == input_size:- return input+ if len(original_shape) == 2:+ # (H, W) -> (1, 1, H, W)+ input = input.unsqueeze(0).unsqueeze(0)+ elif len(original_shape) == 3:+ # (C, H, W) -> (1, C, H, W)+ input = input.unsqueeze(0)+ elif len(original_shape) > 4:+ # Flatten all leading dims: (*, C, H, W) -> (B, C, H, W)+ batch_size = 1+ for d in original_shape[:-3]:+ batch_size *= d+ input = input.reshape(batch_size, *original_shape[-3:])factors = (h / size[0], w / size[1])-- # We do bluring only for downscalingantialias = antialias and (max(factors) > 1)if antialias:- # First, we have to determine sigma- # Taken from skimage: https://github.com/scikit-image/scikit-image/blob/v0.19.2/skimage/transform/_warps.py#L171sigmas = (max((factors[0] - 1.0) / 2.0, 0.001), max((factors[1] - 1.0) / 2.0, 0.001))- # Now kernel size. Good results are for 3 sigma, but that is kind of slow. Pillow uses 1 sigma- # https://github.com/python-pillow/Pillow/blob/master/src/libImaging/Resample.c#L206- # But they do it in the 2 passes, which gives better results. Let's try 2 sigmas for nowks = int(max(2.0 * 2 * sigmas[0], 3)), int(max(2.0 * 2 * sigmas[1], 3))- # Make sure it is odd- if (ks[0] % 2) == 0:- ks = ks[0] + 1, ks[1]-- if (ks[1] % 2) == 0:- ks = ks[0], ks[1] + 1+ ks = (ks[0] if ks[0] % 2 else ks[0] + 1, ks[1] if ks[1] % 2 else ks[1] + 1)input = gaussian_blur2d(input, ks, sigmas)output = torch.nn.functional.interpolate(input, size=size, mode=interpolation, align_corners=align_corners)++ if len(original_shape) == 2:+ output = output[0, 0]+ elif len(original_shape) == 3:+ output = output[0]+ elif len(original_shape) > 4:+ output = output.reshape(*original_shape[:-2], size[0], size[1])+return outputdiff --git a/tests/onnx/__init__.py b/tests/onnx/__init__.pynew file mode 100644index 000000000..4d273d5cb--- /dev/null+++ b/tests/onnx/__init__.py@@ -0,0 +1,16 @@+# 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.+#diff --git a/tests/onnx/check.py b/tests/onnx/check.pynew file mode 100644index 000000000..c655ceb76--- /dev/null+++ b/tests/onnx/check.py@@ -0,0 +1,33 @@+# 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.+# limitations under the License.+import sys+from pathlib import Path++script_dir = Path(__file__).parent.parent.parent+sys.path.insert(0, str(script_dir))+# ruff: noqa: E402+import test_resize_onnx++test_resize_onnx.test_resize_dynamo_with_binding()+print("Test 1 passed")+test_resize_onnx.test_resize_upscale_dynamo()+print("Test 2 passed")+test_resize_onnx.test_resize_downscale_dynamo()+print("Test 3 passed")+test_resize_onnx.test_resize_nearest_dynamo()+print("Test 4 passed")+print("ALL TESTS PASSED")diff --git a/tests/onnx/test_resize_onnx.py b/tests/onnx/test_resize_onnx.pynew file mode 100644index 000000000..903b03cca--- /dev/null+++ b/tests/onnx/test_resize_onnx.py@@ -0,0 +1,152 @@+# 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.+#++import os+import tempfile++import numpy as np+import pytest+import torch++from kornia.geometry.transform import Resize++onnx = pytest.importorskip("onnx")+ort = pytest.importorskip("onnxruntime")+++def test_resize_dynamo_with_binding():+ model = Resize((32, 32), interpolation="bilinear")+ model.eval()++ x = torch.randn(1, 3, 64, 64)+ with torch.no_grad():+ torch_out = model(x)++ fd, temp_path = tempfile.mkstemp(suffix=".onnx")+ os.close(fd)++ try:+ torch.onnx.export(model, x, temp_path, dynamo=True, opset_version=18)++ ort_session = ort.InferenceSession(temp_path)+ input_name = ort_session.get_inputs()[0].name+ output_name = ort_session.get_outputs()[0].name++ binding = ort_session.io_binding()+ binding.bind_cpu_input(input_name, x.numpy())+ binding.bind_output(output_name)++ ort_session.run_with_iobinding(binding)+ ort_out = binding.copy_outputs_to_cpu()[0]++ np.testing.assert_allclose(torch_out.numpy(), ort_out, rtol=1e-4, atol=1e-4)+ finally:+ if os.path.exists(temp_path):+ os.unlink(temp_path)+++def test_resize_upscale_dynamo():+ """Test upscaling with dynamo."""+ model = Resize((128, 128))+ model.eval()+ x = torch.randn(1, 3, 64, 64)++ with torch.no_grad():+ torch_out = model(x)++ fd, temp_path = tempfile.mkstemp(suffix=".onnx")+ os.close(fd)++ try:+ torch.onnx.export(model, x, temp_path, dynamo=True, opset_version=18)++ ort_session = ort.InferenceSession(temp_path)+ input_name = ort_session.get_inputs()[0].name+ output_name = ort_session.get_outputs()[0].name++ binding = ort_session.io_binding()+ binding.bind_cpu_input(input_name, x.numpy())+ binding.bind_output(output_name)+ ort_session.run_with_iobinding(binding)+ ort_out = binding.copy_outputs_to_cpu()[0]++ np.testing.assert_allclose(torch_out.numpy(), ort_out, rtol=1e-4, atol=1e-4)+ finally:+ if os.path.exists(temp_path):+ os.unlink(temp_path)+++def test_resize_downscale_dynamo():+ """Test downscaling with dynamo."""+ model = Resize((16, 16))+ model.eval()+ x = torch.randn(1, 3, 64, 64)++ with torch.no_grad():+ torch_out = model(x)++ fd, temp_path = tempfile.mkstemp(suffix=".onnx")+ os.close(fd)++ try:+ torch.onnx.export(model, x, temp_path, dynamo=True, opset_version=18)++ ort_session = ort.InferenceSession(temp_path)+ input_name = ort_session.get_inputs()[0].name+ output_name = ort_session.get_outputs()[0].name++ binding = ort_session.io_binding()+ binding.bind_cpu_input(input_name, x.numpy())+ binding.bind_output(output_name)+ ort_session.run_with_iobinding(binding)+ ort_out = binding.copy_outputs_to_cpu()[0]++ np.testing.assert_allclose(torch_out.numpy(), ort_out, rtol=1e-4, atol=1e-4)+ finally:+ if os.path.exists(temp_path):+ os.unlink(temp_path)+++def test_resize_nearest_dynamo():+ """Test nearest neighbor interpolation with dynamo."""+ model = Resize((32, 32), interpolation="nearest")+ model.eval()+ x = torch.randn(1, 3, 64, 64)++ with torch.no_grad():+ torch_out = model(x)++ fd, temp_path = tempfile.mkstemp(suffix=".onnx")+ os.close(fd)++ try:+ torch.onnx.export(model, x, temp_path, dynamo=True, opset_version=18)++ ort_session = ort.InferenceSession(temp_path)+ input_name = ort_session.get_inputs()[0].name+ output_name = ort_session.get_outputs()[0].name++ binding = ort_session.io_binding()+ binding.bind_cpu_input(input_name, x.numpy())+ binding.bind_output(output_name)+ ort_session.run_with_iobinding(binding)+ ort_out = binding.copy_outputs_to_cpu()[0]++ np.testing.assert_allclose(torch_out.numpy(), ort_out, rtol=1e-4, atol=1e-4)+ finally:+ if os.path.exists(temp_path):+ os.unlink(temp_path)