π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
fix(filters): run Canny's hysteresis as a while_loop under export (#5689)
Leonardo Vannibdb25d858107
diff --git a/changelog.d/5689.fixed.md b/changelog.d/5689.fixed.mdnew file mode 100644index 000000000..75626d13a--- /dev/null+++ b/changelog.d/5689.fixed.md@@ -0,0 +1 @@+`Canny` and `canny` with `hysteresis=True` can now be exported. Under `torch.export` the hysteresis loop is a `torch.while_loop`, so the exported graph repeats until nothing changes for any input, and the dynamo ONNX exporter writes it as an ONNX `Loop` from torch 2.11. Before, both exporters failed on the data-dependent loop. `Canny.ONNX_EXPORTABLE` is now `True`.diff --git a/kornia/filters/canny.py b/kornia/filters/canny.pyindex e8175ee5c..3f0467788 100644--- a/kornia/filters/canny.py+++ b/kornia/filters/canny.py@@ -30,6 +30,7 @@ from kornia.core.check import (KORNIA_CHECK_IS_TENSOR,KORNIA_CHECK_SHAPE,)+from kornia.core.utils import is_exportingfrom .filter import _to_floatingfrom .gaussian import gaussian_blur2d@@ -58,6 +59,16 @@ def _beats(magnitude: torch.Tensor, neighbour: torch.Tensor, direction: torch.Tereturn (magnitude > neighbour) | (accepts_tie & (magnitude == neighbour))+def _hysteresis_step(edges: torch.Tensor, hysteresis_kernels: torch.Tensor) -> torch.Tensor:+ # One round of edge tracking: a weak pixel (0.5) with a strong (1) 8-neighbour becomes strong.+ weak = (edges == 0.5).to(edges.dtype)+ strong = (edges == 1).to(edges.dtype)+ hysteresis_magnitude = F.conv2d(edges, hysteresis_kernels, padding=hysteresis_kernels.shape[-1] // 2)+ hysteresis_magnitude = (hysteresis_magnitude == 1).any(1, keepdim=True).to(edges.dtype)+ hysteresis_magnitude = hysteresis_magnitude * weak + strong+ return hysteresis_magnitude + (hysteresis_magnitude == 0) * weak * 0.5++def canny(input: torch.Tensor,low_threshold: float = 0.1,@@ -95,7 +106,9 @@ def canny(magnitude is taken after this step, so it is zero off the edge ridges; it is differentiable with respectto the input, and the edge map is not.- Hysteresis keeps a weak pixel connected to a strong one through any of its 8 neighbours, repeated until- nothing changes, and returns edges of 0 and 1.+ nothing changes, and returns edges of 0 and 1. Under ``torch.export`` the loop is a ``torch.while_loop``,+ so the exported graph also repeats until nothing changes, for any input; the dynamo ONNX exporter writes+ it as an ONNX ``Loop`` from torch 2.11 and cannot export it before.- An integer image is promoted to float32 before the grayscale conversion, so a 3-channel integer imageis converted with the floating weights rather than rounded to an integer grey.@@ -210,28 +223,32 @@ def canny(low: torch.Tensor = magnitude > low_thresholdhigh: torch.Tensor = magnitude > high_threshold- edges = low * 0.5 + high * 0.5- edges = edges.to(dtype)+ # Cast before scaling: a boolean times a Python float exports as aten.mul.Scalar, which onnxscript < 0.7.2 cannot+ # translate. The result is 0, 0.5 or 1, exact in every floating dtype; the last cast keeps an integer input's dtype.+ edges = ((low.to(dtype) + high.to(dtype)) * 0.5).to(dtype)# Hysteresisif hysteresis:edges_old: torch.Tensor = -torch.ones(edges.shape, device=edges.device, dtype=dtype)hysteresis_kernels: torch.Tensor = get_hysteresis_kernel(device, dtype)- while ((edges_old - edges).abs() != 0).any():- weak: torch.Tensor = (edges == 0.5).to(dtype)- strong: torch.Tensor = (edges == 1).to(dtype)+ if is_exporting():+ # Graph capture cannot branch on the data, so the loop is a while_loop, which the dynamo ONNX exporter+ # writes as a Loop node from torch 2.11. The body must not return its input, hence the clone.+ def _changed(old: torch.Tensor, new: torch.Tensor) -> torch.Tensor:+ return ((old - new).abs() != 0).any()- hysteresis_magnitude: torch.Tensor = F.conv2d(- edges, hysteresis_kernels, padding=hysteresis_kernels.shape[-1] // 2- )- hysteresis_magnitude = (hysteresis_magnitude == 1).any(1, keepdim=True).to(dtype)- hysteresis_magnitude = hysteresis_magnitude * weak + strong+ def _step(old: torch.Tensor, new: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor]:+ return new.clone(), _hysteresis_step(new, hysteresis_kernels)- edges_old = edges.clone()- edges = hysteresis_magnitude + (hysteresis_magnitude == 0) * weak * 0.5+ _, edges = torch.while_loop(_changed, _step, (edges_old, edges))+ else:+ while ((edges_old - edges).abs() != 0).any():+ edges_old = edges+ edges = _hysteresis_step(edges, hysteresis_kernels)- edges = hysteresis_magnitude+ # The weak pixels left touch no strong pixel.+ edges = (edges == 1).to(dtype)return magnitude, edges@@ -266,8 +283,8 @@ class Canny(nn.Module):"""- # TODO: Handle multiple inputs and outputs models later- ONNX_EXPORTABLE = False+ # The dynamo ONNX exporter writes the hysteresis loop as an ONNX Loop from torch 2.11.+ ONNX_EXPORTABLE = Truedef __init__(self,diff --git a/tests/filters/test_canny.py b/tests/filters/test_canny.pyindex 828547126..8ea8055e1 100644--- a/tests/filters/test_canny.py+++ b/tests/filters/test_canny.py@@ -28,7 +28,7 @@ from kornia.core._compat import torch_version, torch_version_gefrom kornia.core.exceptions import ImageErrorfrom kornia.filters import Canny, canny, gaussian_blur2d, sobel, spatial_gradient-from testing.base import BaseTester, supports_reflect_padding, supports_replicate_padding+from testing.base import BaseTester, dynamo_is_available, supports_reflect_padding, supports_replicate_paddingclass TestCanny(BaseTester):@@ -568,6 +568,68 @@ class TestCanny(BaseTester):self.assert_close(magnitude, expected_magnitude)self.assert_close(edges, expected_edges)+ @staticmethod+ def _long_weak_chain(dtype):+ # A ramped step 0 | 0.6 h | h across x = 6..8, so the ridge is x = 7 alone with no tie, whose height h is+ # strong in the top three rows and weak below. The weak pixels join one per round: with kernel_size=1 and+ # thresholds 0.2 and 1.0 hysteresis needs 62 rounds and keeps the whole column x = 7 and nothing else. The+ # taper is geometric, not linear, so no two neighbours tie either, and noise of 1e-4 changes no edge.+ height = torch.full((64,), 0.1, dtype=dtype)+ height[:5] = torch.tensor([0.5, 0.36, 0.26, 0.19, 0.14], dtype=dtype)+ img = torch.zeros(1, 1, 64, 16, dtype=dtype)+ img[..., 7] = 0.6 * height+ img[..., 8:] = height[:, None]+ return img++ @pytest.mark.device_agnostic+ @pytest.mark.skipif(not dynamo_is_available(), reason="torch.export needs Dynamo on this torch/python pair")+ def test_torch_export_iterates_hysteresis_per_input(self, dtype):+ if dtype != torch.float32:+ pytest.skip("the exported graph is checked once, in float32")+ # Graph capture cannot branch on the data, so the hysteresis loop is a while_loop: a graph traced on one image+ # repeats until nothing changes on another. On a random image the loop stops after a few rounds; the chain+ # needs 62.+ model = Canny(0.2, 1.0, kernel_size=1).eval()+ chain = self._long_weak_chain(dtype)+ traced_on = torch.rand(chain.shape, dtype=dtype, generator=torch.Generator().manual_seed(0))+ exported = torch.export.export(model, (traced_on,)).module()+ for img in (chain, traced_on):+ magnitude, edges = exported(img)+ expected_magnitude, expected_edges = model(img)+ self.assert_close(magnitude, expected_magnitude)+ self.assert_close(edges, expected_edges, rtol=0, atol=0)+ edges = exported(chain)[1]+ assert edges[0, 0, :, 7].all()+ assert int(edges.sum()) == 64++ @pytest.mark.device_agnostic+ @pytest.mark.skipif(not dynamo_is_available(), reason="torch.export needs Dynamo on this torch/python pair")+ @pytest.mark.skipif(not torch_version_ge(2, 11), reason="the dynamo exporter writes while_loop from torch 2.11")+ def test_onnx_export_iterates_hysteresis_per_input(self, dtype):+ if dtype != torch.float32:+ pytest.skip("the exported graph is checked once, in float32")+ pytest.importorskip("onnx")+ pytest.importorskip("onnxscript")+ ort = pytest.importorskip("onnxruntime")+ # The while_loop becomes an ONNX Loop, which runs until nothing changes for each input.+ model = Canny(0.2, 1.0, kernel_size=1).eval()+ chain = self._long_weak_chain(dtype)+ traced_on = torch.rand(chain.shape, dtype=dtype, generator=torch.Generator().manual_seed(0))+ buffer = io.BytesIO()+ with warnings.catch_warnings():+ warnings.simplefilter("ignore")+ torch.onnx.export(model, (traced_on,), dynamo=True, opset_version=18, verbose=False).save(buffer)+ session = ort.InferenceSession(buffer.getvalue(), providers=["CPUExecutionProvider"])+ name = session.get_inputs()[0].name+ for img in (chain, traced_on):+ magnitude, edges = (torch.from_numpy(out) for out in session.run(None, {name: img.numpy()}))+ expected_magnitude, expected_edges = model(img)+ self.assert_close(magnitude, expected_magnitude)+ self.assert_close(edges, expected_edges, rtol=0, atol=0)+ edges = torch.from_numpy(session.run(None, {name: chain.numpy()})[1])+ assert edges[0, 0, :, 7].all()+ assert int(edges.sum()) == 64+@pytest.mark.parametrize("channels", [2, 4])def test_unsupported_channel_count_raises(self, channels, device, dtype):with pytest.raises(ImageError, match="1 or 3 channels"):diff --git a/tests/onnx/test_attribute_export_coverage.py b/tests/onnx/test_attribute_export_coverage.pyindex 24cc0eda4..222a07cdc 100644--- a/tests/onnx/test_attribute_export_coverage.py+++ b/tests/onnx/test_attribute_export_coverage.py@@ -82,7 +82,12 @@ _DECLARING_PACKAGES = ("kornia.color", "kornia.enhance", "kornia.filters", "korn# A class that keeps ``ONNX_EXPORTABLE = False`` needs a tracking issue: its case is a strict xfail that must# fail inside the exporter, so it turns red once the class exports and the marker can go.-_TRACKING_ISSUES = {"Canny": "#5398: Canny fails Dynamo ONNX export"}+_TRACKING_ISSUES: dict[str, str] = {}++# Classes whose export contains a ``torch.while_loop``, which the dynamo exporter writes as an ONNX ``Loop`` from+# torch 2.11 (pytorch/pytorch#162645). The older exporters have no translation for it (2.5.1, 2.6.0 and 2.9.1+# checked), so the marker is strict and must fail inside the exporter.+_WHILE_LOOP_EXPORTS = {"Canny"}# Classes that export from torch 2.9 (2.9.1 and 2.14 checked) but not with the exporter of torch 2.5.1 (RgbToYuv422# gives an invalid ``Range`` node, DexiNed fails on batch norm, MotionBlur3D on ``grid_sampler_3d``) or 2.6.0@@ -173,6 +178,15 @@ def _make_cases():# fails the case instead of satisfying the marker.reason = _TRACKING_ISSUES.get(cls.__name__, f"{cls.__name__} has no tracking issue")marks.append(pytest.mark.xfail(strict=True, raises=torch.onnx.OnnxExporterError, reason=reason))+ if cls.__name__ in _WHILE_LOOP_EXPORTS:+ marks.append(+ pytest.mark.xfail(+ torch_version_lt(2, 11, 0),+ strict=True,+ raises=torch.onnx.OnnxExporterError,+ reason="the dynamo exporter of torch < 2.11 cannot export torch.while_loop",+ )+ )if cls.__name__ in _OLD_EXPORTER_FAILURES:marks.append(pytest.mark.xfail(torch_version_lt(2, 9, 0), reason="the dynamo exporter of torch < 2.9", strict=False)