π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
fix(filters): check a device sigma in gaussian_blur2d without a host sync (#6337)
Dmytro Mishkindf68386656be
diff --git a/changelog.d/6337.fixed.md b/changelog.d/6337.fixed.mdnew file mode 100644index 000000000..6bb5cdb5b--- /dev/null+++ b/changelog.d/6337.fixed.md@@ -0,0 +1 @@+`gaussian_blur2d` no longer waits for the device when `sigma` is a tensor on CUDA, or on MPS from torch 2.13: its positivity is checked there with `torch._assert_async`. A value that is not positive in such a `sigma` used to raise `BaseError` during the call and now raises `RuntimeError` at the next synchronization, which on CUDA is a device-side assert. A tuple or a CPU tensor `sigma` is still checked during the call.diff --git a/kornia/filters/gaussian.py b/kornia/filters/gaussian.pyindex 95c764844..792d92206 100644--- a/kornia/filters/gaussian.py+++ b/kornia/filters/gaussian.py@@ -21,7 +21,14 @@ import torchimport torch.nn.functional as Ffrom torch import nn-from kornia.core.check import KORNIA_CHECK, KORNIA_CHECK_IS_TENSOR, KORNIA_CHECK_SAME_SIZE, KORNIA_CHECK_SHAPE+from kornia.core._compat import torch_version_ge+from kornia.core.check import (+ KORNIA_CHECK,+ KORNIA_CHECK_IS_TENSOR,+ KORNIA_CHECK_SAME_SIZE,+ KORNIA_CHECK_SHAPE,+ are_checks_enabled,+)from kornia.core.ops import _device_literalfrom kornia.core.utils import _autocast_disabled, _to_device_nonblocking, is_autocast_enabled, is_compiling@@ -32,6 +39,9 @@ from .kernels import _check_kernel_size, _unpack_2d_ks, get_gaussian_kernel1d, g# full-graph capture. Cache it without changing any backend settings._HAS_MKLDNN = torch.backends.mkldnn.is_available()+# ``aten::_assert_async.msg`` gained its MPS kernel in torch 2.13; kornia supports torch >= 2.5.1.+_MPS_HAS_ASSERT_ASYNC = torch_version_ge(2, 13)+def _gaussian_blur2d_cpu_eligible(input: torch.Tensor) -> bool:"""Select large native-precision images where weighted slices beat convolution."""@@ -112,7 +122,7 @@ def gaussian_blur2d(kernel_size: the size of the kernel. Can be an integer or tuple of two integers (height, width).sigma: the standard deviation of the kernel. Can be a tuple of two floats or a torch.Tensorwith shape :math:`(1, 2)`, shared by the batch, or :math:`(B, 2)`, one row per sample.- Values must be positive.+ Values must be positive; the note below says when that is checked.border_type: the padding mode to be applied before convolving.The expected modes are: ``'constant'``, ``'reflect'``,``'replicate'`` or ``'circular'``, case-insensitive. Default: ``'reflect'``.@@ -124,10 +134,19 @@ def gaussian_blur2d(Raises:~kornia.core.exceptions.TypeCheckError: if input is not a torch.Tensor.~kornia.core.exceptions.ShapeError: if input is not 4D.- ~kornia.core.exceptions.BaseError: if sigma values are not positive.+ ~kornia.core.exceptions.BaseError: if sigma values are not positive, for a tuple or a CPU tensor ``sigma``.+ RuntimeError: at the next synchronization, if a ``sigma`` tensor on an accelerator has a value that is not+ positive.~kornia.core.exceptions.BaseError: if the ``sigma`` batch is neither 1 nor the input batch.~kornia.core.exceptions.BaseError: if kernel_size is not a positive odd integer.+ .. note::+ A tuple or a CPU tensor ``sigma`` is checked on the host during the call. A ``sigma`` tensor on an+ accelerator is checked there with ``torch._assert_async``, so the call does not wait for the device to read it+ back: a value that is not positive raises ``RuntimeError`` at the next synchronization. On CUDA that error is+ a device-side assert, after which the CUDA context cannot be used. MPS has the assert from torch 2.13; on an+ older release ``sigma`` is read on the host instead. The check is skipped under ``torch.compile``.+.. note::See a working example `here <https://www.kornia.org/tutorials/nbs/gaussian_blur.html>`__.@@ -177,7 +196,7 @@ def _gaussian_blur2d(separable: bool,) -> torch.Tensor:"""Construct and apply the kernels in the working dtype."""- # The positivity check below reads ``host_sigma``: the Python numbers, or ``sigma`` in the input dtype on the+ # The positivity check below takes ``host_sigma``: the Python numbers, or ``sigma`` in the input dtype on the# device it came on, so that a CPU sigma, as the augmentations pass it, is checked without reading the GPU.host_sigma: tuple[float, float] | torch.Tensorif isinstance(sigma, tuple) and all(isinstance(s, (int, float)) for s in sigma):@@ -186,8 +205,9 @@ def _gaussian_blur2d(# kernel. The values round from the same Python numbers either way.sigma = _device_literal([sigma], device=input.device, dtype=input.dtype)elif isinstance(sigma, tuple):- sigma = torch.tensor([sigma], device=input.device, dtype=input.dtype)- host_sigma = sigma+ # Built on the host, so that it is checked there like the Python numbers.+ host_sigma = torch.tensor([sigma], dtype=input.dtype)+ sigma = _to_device_nonblocking(host_sigma, input.device)else:KORNIA_CHECK_IS_TENSOR(sigma)# Cast where it lives and then move: the blocking ``sigma.to(device, dtype)`` also casts on the host.@@ -197,15 +217,21 @@ def _gaussian_blur2d(KORNIA_CHECK_SHAPE(sigma, ["B", "2"])KORNIA_CHECK_SAME_SIZE(sigma, input, allow_one=True, msg="sigma must have a batch of 1 or the input batch.")# `bool()` on a tensor is untraceable by dynamo; skip the data-dependent check under compile.- if not is_compiling():+ # ``disable_checks()`` skips it as well, so that the device assert below never runs when checks are off.+ if not is_compiling() and are_checks_enabled():# Only interpolate `sigma` into the message when the check actually fails: a plain# f-string here would format the whole `sigma` tensor (a costly tensor->str) on every# eager call even when it passes β which dominated the eager Gaussian-blur runtime.if not isinstance(host_sigma, torch.Tensor):# The same rounding to the input dtype as the device tensor, on the host.host_sigma = torch.tensor([host_sigma], dtype=input.dtype)- positive = bool((host_sigma > 0).all())- KORNIA_CHECK(positive, "sigma must be positive" if positive else f"sigma must be positive, got {sigma}")+ if host_sigma.device.type == "cpu" or (host_sigma.device.type == "mps" and not _MPS_HAS_ASSERT_ASYNC):+ positive = bool((host_sigma > 0).all())+ KORNIA_CHECK(positive, "sigma must be positive" if positive else f"sigma must be positive, got {sigma}")+ else:+ # Reading a device sigma on the host would wait for every queued kernel (#6335), so check it where it+ # lives: the error is raised at the next synchronization, and on CUDA it is a device-side assert.+ torch._assert_async((host_sigma > 0).all(), "sigma must be positive")if separable:ky, kx = _unpack_2d_ks(kernel_size)diff --git a/testing/augmentation/sync_registry.py b/testing/augmentation/sync_registry.pyindex 599693912..c61876656 100644--- a/testing/augmentation/sync_registry.py+++ b/testing/augmentation/sync_registry.py@@ -98,6 +98,12 @@ def _setup_jpeg(x: torch.Tensor) -> Callable[[], Any]:return lambda: kornia.enhance.jpeg_codec_differentiable(x, quality)+def _setup_gaussian_blur_sigma(x: torch.Tensor) -> Callable[[], Any]:+ # One sigma per sample on the device: its positivity check must not read it back on the host (#6335).+ sigma = torch.linspace(1.0, 2.0, 2 * x.shape[0], device=x.device, dtype=x.dtype).view(-1, 2)+ return lambda: kornia.filters.gaussian_blur2d(x, (5, 5), sigma)++def _setup_crop_by_indices(x: torch.Tensor) -> Callable[[], Any]:# Augmentations pass boxes sampled on the CPU, so the functional entry does too.boxes = torch.tensor([[[2, 3], [17, 3], [17, 18], [2, 18]]], dtype=torch.long).repeat(x.shape[0], 1, 1)@@ -135,6 +141,7 @@ FUNCTIONAL_CASES = [_functional("sharpness", lambda x: functools.partial(kornia.enhance.sharpness, x, 0.5)),_functional("jpeg_codec_differentiable", _setup_jpeg),_functional("gaussian_blur2d", lambda x: functools.partial(kornia.filters.gaussian_blur2d, x, (5, 5), (1.5, 1.5))),+ _functional("gaussian_blur2d[sigma]", _setup_gaussian_blur_sigma),_functional("crop_by_indices", _setup_crop_by_indices),]diff --git a/tests/filters/test_gaussian.py b/tests/filters/test_gaussian.pyindex c8cff4f7f..e75ffaa48 100644--- a/tests/filters/test_gaussian.py+++ b/tests/filters/test_gaussian.py@@ -25,6 +25,7 @@ import pytestimport torchfrom kornia.core._compat import torch_version_ge, torch_version_lt+from kornia.core.check import are_checks_enabled, disable_checks, enable_checksfrom kornia.core.exceptions import BaseErrorfrom kornia.filters import (GaussianBlur2d,@@ -728,13 +729,57 @@ class TestGaussianBlur2d(BaseTester):gaussian_blur2d(sample, (3, 3), (0.0, 1.5))assert "sigma must be positive" in str(errinfo.value)- def test_sigma_tensor_negative_raises_exception(self, device, dtype):- """Test that negative sigma tensor raises an exception."""+ @pytest.mark.parametrize("as_tuple", [False, True])+ def test_sigma_on_the_host_negative_raises_exception(self, as_tuple, device, dtype):+ # A CPU sigma tensor, and a tuple of 0-d tensors, are checked on the host during the call on every device.sample = torch.rand(2, 3, 5, 5, device=device, dtype=dtype)- sigma = torch.tensor([[-1.5, 1.5], [1.5, 1.5]], device=device, dtype=dtype)- with pytest.raises(Exception) as errinfo:+ sigma = torch.tensor([[-1.5, 1.5], [1.5, 1.5]], dtype=dtype)+ if as_tuple:+ sigma = (sigma[0, 0], sigma[0, 1])+ with pytest.raises(BaseError, match="sigma must be positive"):gaussian_blur2d(sample, (3, 3), sigma)- assert "sigma must be positive" in str(errinfo.value)++ def test_sigma_on_the_device_negative_raises_at_the_next_sync_6335(self, device, dtype):+ # kornia#6335: reading a device sigma on the host waited for every queued kernel. torch._assert_async checks it+ # on the device instead, so the call returns and the error surfaces at the next synchronization.+ if device.type != "mps":+ pytest.skip("pins MPS: a CPU sigma is read on the host, and on CUDA the assert poisons the context")+ if not torch_version_ge(2, 13):+ pytest.skip("no MPS kernel for _assert_async before torch 2.13, so sigma is read on the host there")+ sample = torch.rand(2, 3, 5, 5, device=device, dtype=dtype)+ sigma = torch.tensor([[-1.5, 1.5], [1.5, 1.5]], device=device, dtype=dtype)+ gaussian_blur2d(sample, (3, 3), sigma)+ with pytest.raises(RuntimeError, match="sigma must be positive"):+ torch.mps.synchronize()++ def test_sigma_check_is_skipped_when_checks_are_disabled_6335(self, device, dtype):+ # disable_checks() skips the check for a device sigma too: no assert is left to fail at the next sync.+ sample = torch.rand(2, 3, 5, 5, device=device, dtype=dtype)+ sigma = torch.tensor([[-1.5, 1.5], [1.5, 1.5]], device=device, dtype=dtype)+ were_checks_enabled = are_checks_enabled()+ disable_checks()+ try:+ out = gaussian_blur2d(sample, (3, 3), sigma)+ # The kernel only uses sigma squared, so a negative sigma blurs like its absolute value.+ self.assert_close(out, gaussian_blur2d(sample, (3, 3), sigma.abs()))+ finally:+ if were_checks_enabled:+ enable_checks()++ def test_sigma_on_the_device_does_not_synchronize_6335(self, device, dtype):+ if device.type != "cuda":+ pytest.skip("CUDA host synchronizations need a CUDA device")+ sample = torch.rand(2, 3, 16, 16, device=device, dtype=dtype)+ sigma = torch.rand(2, 2, device=device, dtype=dtype) + 0.5+ expected = gaussian_blur2d(sample, (5, 5), sigma.cpu())+ torch.cuda.synchronize()+ previous = torch.cuda.get_sync_debug_mode()+ torch.cuda.set_sync_debug_mode("error")+ try:+ actual = gaussian_blur2d(sample, (5, 5), sigma)+ finally:+ torch.cuda.set_sync_debug_mode(previous)+ self.assert_close(actual, expected, rtol=0, atol=0)def test_kernel_size_even_raises_exception(self, device, dtype):"""Test that even kernel size raises an exception."""