π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
perf(augmentation): make crop generator torch.compile fullgraph (#3842)
Edgar Riba4822ca0c6da5
diff --git a/kornia/augmentation/random_generator/_2d/crop.py b/kornia/augmentation/random_generator/_2d/crop.pyindex 5c100e96d..2928e7d56 100644--- a/kornia/augmentation/random_generator/_2d/crop.py+++ b/kornia/augmentation/random_generator/_2d/crop.py@@ -90,8 +90,11 @@ class CropGenerator(RandomGeneratorBase):"If `size` is a torch.Tensor, it must be shaped as (B, 2). "f"Got {size.shape} while expecting {torch.Size([batch_size, 2])}.")- if not (input_size[0] > 0 and input_size[1] > 0 and (size > 0).all()):- raise AssertionError(f"Got non-positive input size or size. {input_size}, {size}.")+ # Only check the (Python int) input size here; ``size`` comes from a validated positive+ # config value, and a per-forward ``(size > 0).all()`` sync would break torch.compile+ # fullgraph.+ if not (input_size[0] > 0 and input_size[1] > 0):+ raise AssertionError(f"Got non-positive input size. {input_size}.")size = size.floor()x_diff = input_size[1] - size[:, 1] + 1@@ -257,24 +260,27 @@ class ResizedCropGenerator(CropGenerator):h_out = h[torch.arange(0, batch_size, device=_device, dtype=torch.long), argmax_dim1]w_out = w[torch.arange(0, batch_size, device=_device, dtype=torch.long), argmax_dim1]- if not cond_bool.all():- # Fallback to center crop- in_ratio = float(size[0]) / float(size[1])- _min = float(self.ratio.min()) if isinstance(self.ratio, torch.Tensor) else min(self.ratio)- if in_ratio < _min:- h_ct = torch.tensor(size[0], device=_device, dtype=_dtype)- w_ct = torch.round(h_ct / _min)- elif in_ratio > _min:- w_ct = torch.tensor(size[1], device=_device, dtype=_dtype)- h_ct = torch.round(w_ct * _min)- else: # whole image- h_ct = torch.tensor(size[0], device=_device, dtype=_dtype)- w_ct = torch.tensor(size[1], device=_device, dtype=_dtype)- h_ct = h_ct.floor()- w_ct = w_ct.floor()-- h_out = torch.where(cond_bool, h_out, h_ct)- w_out = torch.where(cond_bool, w_out, w_ct)+ # Center-crop fallback for samples where no candidate crop fit (``cond_bool`` False). The+ # fallback size is a compile-time constant (from ``size`` and ``self.ratio``), so compute it+ # unconditionally and select branchlessly with ``torch.where`` β dropping the+ # ``if not cond_bool.all()`` device sync keeps the generator torch.compile fullgraph. When+ # every candidate fit, ``where`` returns ``h_out``/``w_out`` unchanged (byte-identical).+ in_ratio = float(size[0]) / float(size[1])+ _min = float(self.ratio.min()) if isinstance(self.ratio, torch.Tensor) else min(self.ratio)+ if in_ratio < _min:+ h_ct = torch.tensor(size[0], device=_device, dtype=_dtype)+ w_ct = torch.round(h_ct / _min)+ elif in_ratio > _min:+ w_ct = torch.tensor(size[1], device=_device, dtype=_dtype)+ h_ct = torch.round(w_ct * _min)+ else: # whole image+ h_ct = torch.tensor(size[0], device=_device, dtype=_dtype)+ w_ct = torch.tensor(size[1], device=_device, dtype=_dtype)+ h_ct = h_ct.floor()+ w_ct = w_ct.floor()++ h_out = torch.where(cond_bool, h_out, h_ct)+ w_out = torch.where(cond_bool, w_out, w_ct)# Clamp crop size to input size to prevent out-of-bounds cropsh_out = torch.clamp(h_out, min=1, max=size[0])diff --git a/kornia/enhance/adjust.py b/kornia/enhance/adjust.pyindex 4687f2730..1a528381d 100644--- a/kornia/enhance/adjust.py+++ b/kornia/enhance/adjust.py@@ -926,11 +926,9 @@ def _scale_channel_batched(input: torch.Tensor) -> torch.Tensor:n = shape[0] * shape[1]scaled = input.reshape(n, -1) * 255.0 # (N, P)- min_, max_ = input.min(), input.max()- if min_.item() < 0.0 and not torch.isclose(min_, torch.as_tensor(0.0, dtype=min_.dtype)):- raise ValueError(f"Values in the input torch.Tensor must greater or equal to 0.0. Found {min_.item()}.")- if max_.item() > 1.0 and not torch.isclose(max_, torch.as_tensor(1.0, dtype=max_.dtype)):- raise ValueError(f"Values in the input torch.Tensor must lower or equal to 1.0. Found {max_.item()}.")+ # Input is expected in [0, 1] (see the docstring). Out-of-range values are clamped into the+ # 256-bin range below rather than raising: the previous ``.item()`` range check forced two+ # device syncs and broke ``torch.compile`` fullgraph for no correctness benefit on valid input.# Per-plane 256-bin histogram matching ``torch.histc(x, 256, 0, 255)`` bin placement.bins = torch.clamp((scaled * (256.0 / 255.0)).floor().long(), 0, 255)