Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

refactor(compile): replace is_compiling() guards with genuine fullgraph code (#3794)

Edgar Riba2fd0a252d051
diff --git a/kornia/augmentation/base.py b/kornia/augmentation/base.py
index 30e325ed6..00a388ecb 100644
--- a/kornia/augmentation/base.py
+++ b/kornia/augmentation/base.py
@@ -175,34 +175,22 @@ class _BasicAugmentationBase(nn.Module):
else:
batch_prob = (torch.rand(1, device=self.device) < p_batch).to(self.dtype)
+ # Per-sample gate. `p` and `same_on_batch` are Python values, so these branches are
+ # resolved at trace time (no graph break).
elem_prob: torch.Tensor
- if not torch.compiler.is_compiling():
- # Eager keeps the exact original control flow so RNG draws are unchanged.
- if batch_prob.sum() == 1:
- if p == 1:
- elem_prob = torch.ones(batch_shape[0], device=self.device, dtype=self.dtype)
- elif p == 0:
- elem_prob = torch.zeros(batch_shape[0], device=self.device, dtype=self.dtype)
- elif same_on_batch:
- elem_prob = (torch.rand(1, device=self.device) < p).to(self.dtype).expand(batch_shape[0])
- else:
- elem_prob = (torch.rand(batch_shape[0], device=self.device) < p).to(self.dtype)
- batch_prob = batch_prob * elem_prob
- else:
- batch_prob = batch_prob.repeat(batch_shape[0])
+ if p == 1:
+ elem_prob = torch.ones(batch_shape[0], device=self.device, dtype=self.dtype)
+ elif p == 0:
+ elem_prob = torch.zeros(batch_shape[0], device=self.device, dtype=self.dtype)
+ elif same_on_batch:
+ elem_prob = (torch.rand(1, device=self.device) < p).to(self.dtype).expand(batch_shape[0])
else:
- # Compile: branchless equivalent of the `batch_prob.sum() == 1` gate. batch_prob
- # is (1,) in {0, 1}; multiplying by the per-sample gate yields zeros for a
- # deselected batch and elem_prob for a selected one, avoiding the graph break.
- if p == 1:
- elem_prob = torch.ones(batch_shape[0], device=self.device, dtype=self.dtype)
- elif p == 0:
- elem_prob = torch.zeros(batch_shape[0], device=self.device, dtype=self.dtype)
- elif same_on_batch:
- elem_prob = (torch.rand(1, device=self.device) < p).to(self.dtype).expand(batch_shape[0])
- else:
- elem_prob = (torch.rand(batch_shape[0], device=self.device) < p).to(self.dtype)
- batch_prob = batch_prob * elem_prob
+ elem_prob = (torch.rand(batch_shape[0], device=self.device) < p).to(self.dtype)
+
+ # Branchless combine (replaces the data-dependent `if batch_prob.sum() == 1`).
+ # batch_prob is (1,) in {0, 1}: a selected batch yields elem_prob, a deselected one
+ # yields zeros β€” identical to the old branch, without the graph break.
+ batch_prob = batch_prob * elem_prob
if len(batch_prob.shape) == 2:
return batch_prob[..., 0]
diff --git a/kornia/contrib/distance_transform.py b/kornia/contrib/distance_transform.py
index 81b098903..c9fc97aec 100644
--- a/kornia/contrib/distance_transform.py
+++ b/kornia/contrib/distance_transform.py
@@ -49,12 +49,9 @@ 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
- # 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
-
+ # No data-dependent early-out: the loop bound (n_iters) is fixed, and once no pixels
+ # remain the remaining iterations are exact no-ops (out += 0*mask, where(False,...)
+ # leaves boundary unchanged). Running them all keeps the op fullgraph-compilable.
offset: int = i * k_half
out = out + (offset + cdt) * mask.to(dtype=out.dtype)
boundary = torch.where(mask, signal_ones, boundary)
@@ -83,12 +80,9 @@ 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
- # 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
-
+ # No data-dependent early-out: the loop bound (n_iters) is fixed, and once no pixels
+ # remain the remaining iterations are exact no-ops (out += 0*mask, where(False,...)
+ # leaves boundary unchanged). Running them all keeps the op fullgraph-compilable.
offset: int = i * k_half
out = out + (offset + cdt) * mask.to(dtype=out.dtype)
boundary = torch.where(mask, signal_ones, boundary)
diff --git a/kornia/enhance/adjust.py b/kornia/enhance/adjust.py
index 2b0f1acfd..ae89aa890 100644
--- a/kornia/enhance/adjust.py
+++ b/kornia/enhance/adjust.py
@@ -292,13 +292,10 @@ def adjust_gamma(
gamma = gamma.to(input.device).to(input.dtype)
gain = gain.to(input.device).to(input.dtype)
- # `bool(tensor)` is untraceable by dynamo; skip the data-dependent validation under compile.
- if not torch.compiler.is_compiling():
- if (gamma < 0.0).any():
- raise ValueError(f"Gamma must be non-negative. Got {gamma}")
-
- if (gain < 0.0).any():
- raise ValueError(f"Gain must be non-negative. Got {gain}")
+ # torch._assert_async keeps the value check while staying fullgraph-compilable (a Python
+ # `if tensor: raise` would break the graph).
+ torch._assert_async((gamma >= 0.0).all(), "Gamma must be non-negative.")
+ torch._assert_async((gain >= 0.0).all(), "Gain must be non-negative.")
for _ in range(len(input.shape) - len(gamma.shape)):
gamma = torch.unsqueeze(gamma, dim=-1)
@@ -371,9 +368,8 @@ def adjust_contrast(image: torch.Tensor, factor: Union[float, torch.Tensor], cli
while len(factor.shape) != len(image.shape):
factor = factor[..., None]
- # `bool(tensor)` is untraceable by dynamo; skip the data-dependent validation under compile.
- if not torch.compiler.is_compiling():
- KORNIA_CHECK(bool((factor >= 0).all()), "Contrast factor must be positive.")
+ # torch._assert_async keeps the value check while staying fullgraph-compilable.
+ torch._assert_async((factor >= 0).all(), "Contrast factor must be positive.")
# Apply contrast factor to each channel
img_adjust: torch.Tensor = image * factor
diff --git a/kornia/losses/_utils.py b/kornia/losses/_utils.py
index c0bef8af4..9ca6fd74c 100644
--- a/kornia/losses/_utils.py
+++ b/kornia/losses/_utils.py
@@ -40,20 +40,18 @@ def mask_ignore_pixels(
Returns:
Tuple ``(target, target_mask)``. ``target`` is either the original
tensor or a copy where ignored labels were replaced by zero.
- ``target_mask`` is ``None`` when no ignored pixels are present;
- otherwise it is a boolean tensor with ``True`` at valid positions.
+ ``target_mask`` is ``None`` only when ``ignore_index`` is ``None``;
+ otherwise it is a boolean tensor with ``True`` at valid positions
+ (all-``True`` when no pixels are ignored).
"""
if ignore_index is None:
return target, None
target_mask = target != ignore_index
- # Data-dependent early-out (skip masking when nothing is ignored). Guard it under
- # torch.compile: returning the all-True mask instead of None just makes callers apply
- # a no-op mask, which keeps the result identical while staying fullgraph-safe.
- if not torch.compiler.is_compiling() and target_mask.all():
- return target, None
-
+ # No data-dependent early-out: always return the mask. When nothing is ignored the mask
+ # is all-True, so the caller's masking is a no-op and `where` leaves `target` unchanged β€”
+ # identical result to the old early-return, but fullgraph-compilable.
# map invalid pixels to a valid class (0)
# they need to be manually excluded from the loss computation after
target = target.where(target_mask, target.new_zeros(1))