Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

fix(contrib): make distance_transform torch.compile fullgraph-safe (#3788)

Edgar Riba8f0ec5ac993d
diff --git a/kornia/contrib/distance_transform.py b/kornia/contrib/distance_transform.py
index 8c1e5fd53..81b098903 100644
--- a/kornia/contrib/distance_transform.py
+++ b/kornia/contrib/distance_transform.py
@@ -49,7 +49,10 @@ def _distance_transform_2d_impl(image: torch.Tensor, kernel_size: int, h: float)
cdt = torch.nan_to_num(cdt, nan=0.0, posinf=0.0, neginf=0.0)
mask = cdt > 0
- if not mask.any():
+ # Early exit is a pure optimization: once no pixels remain, the remaining
+ # iterations are no-ops (out += 0*mask, where(False,...) leaves boundary). Skip
+ # the data-dependent break under compile so the graph stays static/fullgraph-safe.
+ if not torch.compiler.is_compiling() and not mask.any():
break
offset: int = i * k_half
@@ -80,7 +83,10 @@ def _distance_transform_3d_impl(image: torch.Tensor, kernel_size: int, h: float)
cdt = torch.nan_to_num(cdt, nan=0.0, posinf=0.0, neginf=0.0)
mask = cdt > 0
- if not mask.any():
+ # Early exit is a pure optimization: once no pixels remain, the remaining
+ # iterations are no-ops (out += 0*mask, where(False,...) leaves boundary). Skip
+ # the data-dependent break under compile so the graph stays static/fullgraph-safe.
+ if not torch.compiler.is_compiling() and not mask.any():
break
offset: int = i * k_half