π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
perf(enhance): skip torch._assert_async value checks on MPS (no-kernel CPU fallback syncs per call) (#3916)
Dmytro Mishkin81e6b7aebf4a
diff --git a/kornia/enhance/adjust.py b/kornia/enhance/adjust.pyindex 1a528381d..37d8b60b5 100644--- a/kornia/enhance/adjust.py+++ b/kornia/enhance/adjust.py@@ -34,6 +34,19 @@ from kornia.core.utils import _torch_histc_castfrom kornia.image.utils import perform_keep_shape_image, perform_keep_shape_video+def _assert_async_value_check(cond: torch.Tensor, msg: str) -> None:+ """Validate a tensor condition without graph breaks or hidden device syncs.++ ``torch._assert_async`` keeps the check fullgraph-compilable (a Python ``if tensor: raise``+ would break the graph), but ``aten::_assert_async`` has no MPS kernel β the CPU fallback+ materializes ``cond`` and drains the queued stream on every call, so on MPS the check is+ skipped instead.+ """+ if cond.device.type == "mps":+ return+ torch._assert_async(cond, msg)++def adjust_saturation_raw(image: torch.Tensor, factor: Union[float, torch.Tensor]) -> torch.Tensor:r"""Adjust color saturation of an image.@@ -261,6 +274,11 @@ def adjust_gamma(.. note::See a working example `here <https://kornia.github.io/tutorials/nbs/image_enhancement.html>`__.+ .. note::+ The non-negativity check on ``gamma``/``gain`` runs on CPU and CUDA (via ``torch._assert_async``).+ On MPS it is skipped: the op has no MPS kernel and its CPU fallback would synchronize the+ device on every call, so invalid values do not raise there.+Example:>>> x = torch.ones(1, 1, 2, 2)>>> adjust_gamma(x, 1.0, 2.0)@@ -292,10 +310,14 @@ def adjust_gamma(gamma = gamma.to(input.device).to(input.dtype)gain = gain.to(input.device).to(input.dtype)- # 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.")+ _assert_async_value_check(+ (gamma >= 0.0).all(),+ "Gamma must be non-negative. Clamp it first: max(gamma, 0.0) for floats, gamma.clamp_min(0.0) for tensors.",+ )+ _assert_async_value_check(+ (gain >= 0.0).all(),+ "Gain must be non-negative. Clamp it first: max(gain, 0.0) for floats, gain.clamp_min(0.0) for tensors.",+ )for _ in range(len(input.shape) - len(gamma.shape)):gamma = torch.unsqueeze(gamma, dim=-1)@@ -342,6 +364,11 @@ def adjust_contrast(image: torch.Tensor, factor: Union[float, torch.Tensor], cli.. note::See a working example `here <https://kornia.github.io/tutorials/nbs/image_enhancement.html>`__.+ .. note::+ The non-negativity check on ``factor`` runs on CPU and CUDA (via ``torch._assert_async``).+ On MPS it is skipped: the op has no MPS kernel and its CPU fallback would synchronize the+ device on every call, so invalid values do not raise there.+Example:>>> import torch>>> x = torch.ones(1, 1, 2, 2)@@ -368,8 +395,11 @@ def adjust_contrast(image: torch.Tensor, factor: Union[float, torch.Tensor], cliwhile len(factor.shape) != len(image.shape):factor = factor[..., None]- # torch._assert_async keeps the value check while staying fullgraph-compilable.- torch._assert_async((factor >= 0).all(), "Contrast factor must be positive.")+ _assert_async_value_check(+ (factor >= 0).all(),+ "Contrast factor must be non-negative. Clamp it first: max(factor, 0.0) for floats, "+ "factor.clamp_min(0.0) for tensors.",+ )# Apply contrast factor to each channelimg_adjust: torch.Tensor = image * factor@@ -693,6 +723,11 @@ def solarize(Returns:The solarized images with shape :math:`(*, C, H, W)`.+ .. note::+ The range check on ``additions`` runs on CPU and CUDA (via ``torch._assert_async``).+ On MPS it is skipped: the op has no MPS kernel and its CPU fallback would synchronize the+ device on every call, so invalid values do not raise there.+Example:>>> x = torch.rand(1, 4, 3, 3)>>> out = solarize(x, thresholds=0.5, additions=0.)@@ -722,11 +757,10 @@ def solarize(if isinstance(additions, float):additions = torch.as_tensor(additions)- # `torch._assert_async` keeps this a single traceable path (no Python-level branch on a- # tensor value), so `solarize` stays torch.compile fullgraph-safe while still validating.- torch._assert_async(+ _assert_async_value_check(((additions < 0.5) & (additions > -0.5)).all(),- "The value of 'addition' is between -0.5 and 0.5.",+ "The addition must be in the open range (-0.5, 0.5). Clamp it first: min(max(additions, -0.49), 0.49) "+ "for floats, additions.clamp(-0.49, 0.49) for tensors.",)if isinstance(additions, torch.Tensor) and len(additions.shape) != 0:diff --git a/tests/enhance/test_adjust.py b/tests/enhance/test_adjust.pyindex aa8c22d6e..f69bc020b 100644--- a/tests/enhance/test_adjust.py+++ b/tests/enhance/test_adjust.py@@ -359,6 +359,28 @@ class TestAdjustContrast(BaseTester):f = kornia.enhance.AdjustContrast(1.0)self.assert_close(f(data), expected)+ def test_negative_factor_errors(self, device, dtype):+ if device.type != "cpu":+ pytest.skip("value asserts are synchronous only on CPU (async on CUDA, skipped on MPS)")+ img = torch.rand(1, 3, 4, 4, device=device, dtype=dtype)+ factor = torch.tensor([-0.5], device=device, dtype=dtype)+ with pytest.raises(RuntimeError, match="non-negative"):+ kornia.enhance.adjust_contrast(img, factor)++ def test_mps_skips_value_check(self, device, dtype):+ # aten::_assert_async has no MPS kernel; its CPU fallback forces a full device sync per+ # call. On MPS the value check is skipped entirely (see the note in the adjust_contrast+ # docstring), so even an invalid factor must go through without raising, and the output+ # must stay on the device with the requested dtype.+ if device.type != "mps":+ pytest.skip("pins the MPS-only no-CPU-fallback behavior")+ img = torch.rand(1, 3, 4, 4, device=device, dtype=dtype)+ factor = torch.tensor([-0.5], device=device, dtype=dtype)+ out = kornia.enhance.adjust_contrast(img, factor)+ assert out.shape == img.shape+ assert out.device == img.device+ assert out.dtype == img.dtype+def test_factor_one_with_mean_subtraction(self, device, dtype):# prepare input datadata = torch.tensor(