π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
fix(filters): keep Canny's hysteresis loop data-dependent under torch.jit.trace (#5710)
Muhammad Talha37136c9a1436
diff --git a/changelog.d/5710.fixed.md b/changelog.d/5710.fixed.mdnew file mode 100644index 000000000..88b3e67c0--- /dev/null+++ b/changelog.d/5710.fixed.md@@ -0,0 +1 @@+`canny` and `Canny` with `hysteresis=True` under `torch.jit.trace`, and so the legacy TorchScript ONNX exporter (`torch.onnx.export(..., dynamo=False)`), no longer repeat the hysteresis round only as many times as the traced image needed. The loop is now a scripted function that the trace calls, so the traced graph and the exported ONNX `Loop` run until nothing changes on every input. Before, a longer edge chain than the traced one was cut short without an error, with only a `TracerWarning`. If TorchScript cannot compile the loop, a `RuntimeWarning` reports it. On torch 2.5.1 and 2.9.1, where that exporter is the default, the trace raised `expected padding to be a single integer value or a list of 2 values` instead.diff --git a/kornia/filters/canny.py b/kornia/filters/canny.pyindex 3f0467788..0daad201e 100644--- a/kornia/filters/canny.py+++ b/kornia/filters/canny.py@@ -18,6 +18,9 @@from __future__ import annotationsimport math+import warnings+from collections.abc import Callable+from functools import lru_cacheimport torchimport torch.nn.functional as F@@ -63,12 +66,54 @@ def _hysteresis_step(edges: torch.Tensor, hysteresis_kernels: torch.Tensor) -> t# 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)+ # The kernels are always 3x3, so the padding is the constant 1. Not read from the kernel's shape: under+ # torch.jit.trace a shape is a traced value, which torch 2.5.1 and 2.9.1 turn into an empty padding list.+ hysteresis_magnitude = F.conv2d(edges, hysteresis_kernels, padding=1)hysteresis_magnitude = (hysteresis_magnitude == 1).any(1, keepdim=True).to(edges.dtype)hysteresis_magnitude = hysteresis_magnitude * weak + strongreturn hysteresis_magnitude + (hysteresis_magnitude == 0) * weak * 0.5+def _hysteresis_loop(edges: torch.Tensor, hysteresis_kernels: torch.Tensor) -> torch.Tensor:+ # Repeat the round until nothing changes, for torch.jit.trace: written in the subset of Python that TorchScript+ # compiles, so _hysteresis_loop_traced can hand a trace a scripted copy. canny keeps its eager loop inline: under+ # torch.compile the loop condition breaks the graph, and a break inside a called function splits canny once more.+ edges_old = -torch.ones_like(edges)+ while bool((edges_old - edges).abs().ne(0).any()):+ edges_old = edges+ edges = _hysteresis_step(edges, hysteresis_kernels)+ return edges+++@lru_cache(maxsize=1)+def _scripted_hysteresis_loop() -> Callable[[torch.Tensor, torch.Tensor], torch.Tensor]:+ # Compiled on the first trace, not at import, so only a trace pays for TorchScript.+ with warnings.catch_warnings():+ # torch 2.14 emits a FutureWarning that torch.jit.script is deprecated. The caller never called it+ # and torch.jit.trace already warns for them, so this would be noise.+ warnings.simplefilter("ignore", DeprecationWarning)+ warnings.simplefilter("ignore", FutureWarning)+ return torch.jit.script(_hysteresis_loop)+++def _hysteresis_loop_traced(edges: torch.Tensor, hysteresis_kernels: torch.Tensor) -> torch.Tensor:+ # torch.jit.trace unrolls a data-dependent loop to the rounds the traced image needed. A scripted+ # function called from a trace keeps its control flow (and becomes an ONNX Loop).+ try:+ scripted_loop = _scripted_hysteresis_loop()+ except Exception as error: # noqa: BLE001 - TorchScript may be absent, or unable to read the source+ warnings.warn(+ "canny with hysteresis=True could not compile its hysteresis loop with TorchScript, so the traced "+ "graph repeats the hysteresis round as many times as the traced input needed, on every input: a "+ "longer edge chain is cut short without an error. Export with torch.export or the dynamo ONNX "+ f"exporter instead. torch.jit.script raised {type(error).__name__}: {error}",+ RuntimeWarning,+ stacklevel=3,+ )+ return _hysteresis_loop(edges, hysteresis_kernels)+ return scripted_loop(edges, hysteresis_kernels)++def canny(input: torch.Tensor,low_threshold: float = 0.1,@@ -109,6 +154,12 @@ def canny(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 writesit as an ONNX ``Loop`` from torch 2.11 and cannot export it before.+ Under ``torch.jit.trace``, and so the legacy TorchScript ONNX exporter (``torch.onnx.export(...,+ dynamo=False)``), the loop is a scripted function that the trace calls, so the traced graph also repeats+ until nothing changes, for any input, and the exporter writes it as an ONNX ``Loop``. A trace cannot+ record a loop whose condition depends on the data on its own: if TorchScript cannot compile the function,+ a ``RuntimeWarning`` says so and the traced graph repeats the rounds the traced image needed on every input,+ which cuts a longer edge chain short without an error.- 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.@@ -229,10 +280,11 @@ def canny(# Hysteresisif hysteresis:- edges_old: torch.Tensor = -torch.ones(edges.shape, device=edges.device, dtype=dtype)hysteresis_kernels: torch.Tensor = get_hysteresis_kernel(device, dtype)if is_exporting():+ edges_old: torch.Tensor = -torch.ones(edges.shape, device=edges.device, dtype=dtype)+# 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:@@ -242,7 +294,10 @@ def canny(return new.clone(), _hysteresis_step(new, hysteresis_kernels)_, edges = torch.while_loop(_changed, _step, (edges_old, edges))+ elif torch.jit.is_tracing():+ edges = _hysteresis_loop_traced(edges, hysteresis_kernels)else:+ edges_old = -torch.ones_like(edges)while ((edges_old - edges).abs() != 0).any():edges_old = edgesedges = _hysteresis_step(edges, hysteresis_kernels)diff --git a/tests/filters/test_canny.py b/tests/filters/test_canny.pyindex 8ea8055e1..d9210cc4c 100644--- a/tests/filters/test_canny.py+++ b/tests/filters/test_canny.py@@ -15,6 +15,7 @@# limitations under the License.#+import importlibimport ioimport warningsfrom typing import Any@@ -398,6 +399,18 @@ class TestCanny(BaseTester):self.assert_close(actual_edges, expected_edges)self.assert_close(actual_magnitude, expected_magnitude)+ def test_dynamo_hysteresis_adds_no_graph(self, device, dtype, torch_optimizer):+ # The eager hysteresis loop stays inline in canny. Its condition breaks the graph, and a break inside a called+ # helper splits canny's frame once more: a fourth graph, ~15% slower compiled on a 256 x 256 CPU image.+ from torch._dynamo.testing import CompileCounter++ self._require_padding(device, dtype)+ counter = CompileCounter()+ compiled = torch_optimizer(Canny(), backend=counter)+ img = torch.rand(1, 3, 32, 32, generator=torch.Generator().manual_seed(0)).to(device=device, dtype=dtype)+ self.assert_close(compiled(img)[1], Canny()(img)[1])+ assert counter.frame_count <= 3+@staticmethoddef _require_padding(device, dtype):# gaussian_blur2d pads by reflection and spatial_gradient by replication, even with kernel_size=1@@ -630,6 +643,77 @@ class TestCanny(BaseTester):assert edges[0, 0, :, 7].all()assert int(edges.sum()) == 64+ @pytest.mark.device_agnostic+ def test_jit_trace_iterates_hysteresis_per_input(self, dtype):+ if dtype != torch.float32:+ pytest.skip("the traced graph is checked once, in float32")+ 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))+ with warnings.catch_warnings(record=True) as caught:+ warnings.simplefilter("always")+ traced = torch.jit.trace(model, (traced_on,), check_trace=False)+ assert not [w for w in caught if issubclass(w.category, RuntimeWarning) and "hysteresis" in str(w.message)]+ assert "prim::Loop" in str(traced.inlined_graph)+ for img in (chain, traced_on):+ magnitude, edges = traced(img)+ expected_magnitude, expected_edges = model(img)+ self.assert_close(magnitude, expected_magnitude)+ self.assert_close(edges, expected_edges, rtol=0, atol=0)+ edges = traced(chain)[1]+ assert edges[0, 0, :, 7].all()+ assert int(edges.sum()) == 64+ buffer = io.BytesIO() # the loop survives serialization+ torch.jit.save(traced, buffer)+ buffer.seek(0)+ assert int(torch.jit.load(buffer)(chain)[1].sum()) == 64++ @pytest.mark.device_agnostic+ def test_onnx_export_legacy_iterates_hysteresis_per_input(self, dtype):+ if dtype != torch.float32:+ pytest.skip("the exported graph is checked once, in float32")+ pytest.importorskip("onnx")+ ort = pytest.importorskip("onnxruntime")+ 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))+ export_kwargs: dict[str, Any] = {"input_names": ["input"], "opset_version": 17}+ if torch_version_ge(2, 5, 0):+ export_kwargs["dynamo"] = False+ buffer = io.BytesIO()+ with warnings.catch_warnings():+ warnings.simplefilter("ignore")+ torch.onnx.export(model, (traced_on,), buffer, **export_kwargs)+ session = ort.InferenceSession(buffer.getvalue(), providers=["CPUExecutionProvider"])+ for img in (chain, traced_on):+ magnitude, edges = (torch.from_numpy(out) for out in session.run(None, {"input": 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, {"input": chain.numpy()})[1])+ assert edges[0, 0, :, 7].all()+ assert int(edges.sum()) == 64++ @pytest.mark.device_agnostic+ def test_jit_trace_warns_when_the_loop_cannot_be_scripted(self, dtype, monkeypatch):+ if dtype != torch.float32:+ pytest.skip("the traced graph is checked once, in float32")+ canny_module = importlib.import_module("kornia.filters.canny") # kornia.filters.canny is the function++ def cannot_script():+ raise RuntimeError("no TorchScript here")++ monkeypatch.setattr(canny_module, "_scripted_hysteresis_loop", cannot_script)+ 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))+ with pytest.warns(RuntimeWarning, match="could not compile its hysteresis loop.*no TorchScript here"):+ traced = torch.jit.trace(model, (traced_on,), check_trace=False)+ assert int(traced(chain)[1].sum()) < 64 # cut short, as the warning says+ with warnings.catch_warnings(): # outside a trace the loop is never scripted+ warnings.simplefilter("error")+ assert int(model(chain)[1].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"):