π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
fix(subpix): support legacy ONNX export for 3D soft-argmax (#5775)
Karnajeet Gosavi3dfc82b6451e
diff --git a/changelog.d/5775.fixed.md b/changelog.d/5775.fixed.mdnew file mode 100644index 000000000..5fc7ab316--- /dev/null+++ b/changelog.d/5775.fixed.md@@ -0,0 +1,3 @@+`conv_soft_argmax3d` and `ConvSoftArgmax3d` export with the legacy TorchScript ONNX exporter+(`torch.onnx.export(..., dynamo=False)`) again; the per-window softmax change of this release (#5134) had broken that+export with `Unsupported: ONNX export of operator Unfold`.diff --git a/kornia/geometry/subpix/spatial_soft_argmax.py b/kornia/geometry/subpix/spatial_soft_argmax.pyindex 69d6d70b1..8870f80d8 100644--- a/kornia/geometry/subpix/spatial_soft_argmax.py+++ b/kornia/geometry/subpix/spatial_soft_argmax.py@@ -320,7 +320,14 @@ def _unfold3d(padded: torch.Tensor, kernel_size: tuple[int, int, int], stride: tsz, sy, sx = stridecolumns = F.unfold(padded.reshape(n * d_p, 1, h_p, w_p), (ky, kx), stride=(sy, sx))num_windows = columns.shape[-1]- columns = columns.view(n, d_p, ky * kx, num_windows).unfold(1, kz, sz) # (N, D_out, ky * kx, L, kz)+ columns = columns.view(n, d_p, ky * kx, num_windows)+ if torch.onnx.is_in_onnx_export():+ # The legacy TorchScript ONNX exporter cannot lower Tensor.unfold here. Strided depth slices give the same+ # windows, but they copy more than the view below, so only the export takes this path.+ last = sz * ((d_p - kz) // sz)+ columns = torch.stack([columns[:, i : i + last + 1 : sz] for i in range(kz)], dim=2) # (N, D_out, kz, ky*kx, L)+ return columns.reshape(n, columns.shape[1], kz * ky * kx, num_windows)+ columns = columns.unfold(1, kz, sz) # (N, D_out, ky * kx, L, kz)return columns.permute(0, 1, 4, 2, 3).reshape(n, columns.shape[1], kz * ky * kx, num_windows)diff --git a/tests/geometry/subpix/test_spatial_softargmax.py b/tests/geometry/subpix/test_spatial_softargmax.pyindex 173e7dadc..17f0d912e 100644--- a/tests/geometry/subpix/test_spatial_softargmax.py+++ b/tests/geometry/subpix/test_spatial_softargmax.py@@ -15,6 +15,7 @@# limitations under the License.#+import ioimport itertoolsimport mathimport warnings@@ -576,6 +577,54 @@ class TestConvSoftArgmax3d(BaseTester):gradient = torch.autograd.grad([output.sum() for output in outputs], data)[0]assert gradient.shape == data.shape+ @pytest.mark.device_agnostic+ @pytest.mark.parametrize("op_name", ["function", "module"])+ @pytest.mark.parametrize("dynamic", [False, True], ids=["static", "dynamic"])+ def test_legacy_onnx_export_matches_eager(self, dtype, op_name, dynamic):+ if dtype != torch.float32:+ pytest.skip("The ONNX export is checked once, in float32")+ pytest.importorskip("onnx")+ ort = pytest.importorskip("onnxruntime")++ if op_name == "function":++ class FunctionalWrapper(torch.nn.Module):+ def forward(self, x):+ return kornia.geometry.subpix.conv_soft_argmax3d(x)++ model = FunctionalWrapper()+ else:+ model = kornia.geometry.subpix.ConvSoftArgmax3d()+ sample = torch.rand(1, 2, 5, 8, 9, dtype=dtype)+ buffer = io.BytesIO()+ export_kwargs = {+ "input_names": ["input"],+ "output_names": ["coords", "values"],+ "opset_version": 17,+ "dynamo": False,+ }+ if dynamic:+ export_kwargs["dynamic_axes"] = {+ "input": {0: "batch", 2: "depth", 3: "height", 4: "width"},+ "coords": {0: "batch", 3: "depth_out", 4: "height_out", 5: "width_out"},+ "values": {0: "batch", 2: "depth_out", 3: "height_out", 4: "width_out"},+ }+ with warnings.catch_warnings():+ warnings.simplefilter("ignore")+ torch.onnx.export(model, (sample,), buffer, **export_kwargs)++ session = ort.InferenceSession(buffer.getvalue(), providers=["CPUExecutionProvider"])+ inputs = [sample]+ if dynamic:+ inputs.append(torch.rand(2, 2, 7, 9, 11, dtype=dtype))+ for image in inputs:+ actual = [torch.from_numpy(value) for value in session.run(None, {"input": image.numpy()})]+ expected = model(image)+ assert isinstance(expected, tuple)+ assert len(actual) == len(expected) == 2+ for got, want in zip(actual, expected):+ self.assert_close(got, want, atol=1e-6, rtol=1e-6)+def test_smoke(self, device, dtype):sample = torch.zeros(1, 1, 3, 3, 3, device=device, dtype=dtype)m = kornia.geometry.subpix.ConvSoftArgmax3d((3, 3, 3), output_value=False)