Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

fix(core): check tensor values through one helper without a host sync (#6342)

Dmytro Mishkine3f65932ea49
diff --git a/changelog.d/6342.added.md b/changelog.d/6342.added.md
new file mode 100644
index 000000000..76a9531cb
--- /dev/null
+++ b/changelog.d/6342.added.md
@@ -0,0 +1 @@
+`kornia.core.exceptions.AsyncCheckError`, a `ValueCheckError` that is also a `RuntimeError`. A tensor value check that runs as `torch._assert_async` on an accelerator raises it on the host: for a CPU tensor, and on MPS before torch 2.13. `except RuntimeError` therefore handles that check on every device, and the `gaussian_blur2d` sigma check still raises a `BaseError` on the CPU.
diff --git a/changelog.d/6342.fixed.md b/changelog.d/6342.fixed.md
new file mode 100644
index 000000000..0c347d000
--- /dev/null
+++ b/changelog.d/6342.fixed.md
@@ -0,0 +1 @@
+The tensor value checks of `adjust_gamma`, `adjust_contrast`, `solarize`, `marginal_pdf`, `histogram` and the vertex modes of `Boxes` used to be skipped on MPS; they now run there, as `torch._assert_async` from torch 2.13 and as a host read before, and under TorchScript always as a host read. These checks, and those of `gaussian_blur2d` and the integer mask cast of `AugmentationSequential`, are now skipped when checks are disabled with `disable_checks()`, `python -O` or `KORNIA_CHECKS=0` (they used to run regardless, except in `gaussian_blur2d`). The input-range checks of `equalize`, `equalize3d` and `equalize_clahe` still run then, since they keep the lookup in bounds. All of them are skipped under `torch.vmap`, which used to fail on the missing batching rule of the assert. Under `torch.compile`, all but the `equalize` range checks are also skipped inside `torch.func.grad` and the other functorch transforms, where they used to run. A float `additions` of `solarize` and a tuple `sigma` of `gaussian_blur2d` are checked on the CPU whatever the default device; under a CUDA default device an invalid one used to trigger a device-side assert. `equalize` and `equalize3d` compile with TorchScript again.
diff --git a/docs/source/core.rst b/docs/source/core.rst
index f7a49336b..2b497e2eb 100644
--- a/docs/source/core.rst
+++ b/docs/source/core.rst
@@ -77,7 +77,10 @@ the wrong shape. All of them derive from :exc:`BaseError`, so ``except BaseError
catches any of them. Each subclass also derives from the built-in exception that
matches its failure: :exc:`TypeCheckError` is also a :exc:`TypeError`, and
:exc:`ShapeError`, :exc:`ValueCheckError`, :exc:`DeviceError` and
-:exc:`ImageError` are each also a :exc:`ValueError`. Many functions validate
+:exc:`ImageError` are each also a :exc:`ValueError`. :exc:`AsyncCheckError`,
+the host form of a check that an accelerator runs as ``torch._assert_async``, is
+a :exc:`ValueCheckError` and also a :exc:`RuntimeError`, the error torch raises
+for that check on the device. Many functions validate
their inputs themselves and raise the built-in :exc:`ValueError` or
:exc:`TypeError`, so ``except ValueError`` or ``except TypeError`` catches those
and the matching kornia errors alike; ``except BaseError`` does not catch those
@@ -97,6 +100,9 @@ it.
.. autoexception:: ValueCheckError
:show-inheritance:
+.. autoexception:: AsyncCheckError
+ :show-inheritance:
+
.. autoexception:: DeviceError
:show-inheritance:
diff --git a/kornia/augmentation/container/augment.py b/kornia/augmentation/container/augment.py
index b7ae88537..ca0b3b31f 100644
--- a/kornia/augmentation/container/augment.py
+++ b/kornia/augmentation/container/augment.py
@@ -27,7 +27,7 @@ from kornia.augmentation._3d.base import AugmentationBase3D, RigidAffineAugmenta
from kornia.augmentation.base import _AugmentationBase
from kornia.augmentation.utils.helpers import _boxes_to_padded_tensor
from kornia.constants import DataKey, Resample
-from kornia.core._compat import torch_version_lt
+from kornia.core.check import _check_async
from kornia.core.external import PILImage as Image
from kornia.core.external import numpy as np
from kornia.core.mixin.image_module import _rebuild_container
@@ -152,8 +152,9 @@ class AugmentationSequential(TransformMatrixMinIn, ImageSequential):
- masks are resampled with nearest interpolation by default (see ``extra_args``; padding can still add the
fill value) and come back in their own dtype. Floating masks use the image's working dtype; integer
masks use at least float32 (float64 with a float64 image). Integer labels not exactly representable
- in that working dtype raise ``RuntimeError`` instead of being rounded. On accelerators an asynchronous
- assertion may report at the next synchronization; MPS before torch 2.13 checks on the host.
+ in that working dtype raise ``RuntimeError`` instead of being rounded, unless checks are disabled
+ (:func:`~kornia.core.check.disable_checks`, ``python -O`` or ``KORNIA_CHECKS=0``). On accelerators an
+ asynchronous assertion may report by the next synchronization; MPS before torch 2.13 checks on the host.
- a ``mask`` list contains one tensor per image sample, in sample order. Each entry is
``(H, W)``, ``(C, H, W)`` or ``(1, C, H, W)``, with matching spatial dimensions; channel counts
may differ. Each entry uses its sample's gate, transform parameters and matrix, including in
@@ -1024,12 +1025,7 @@ class AugmentationSequential(TransformMatrixMinIn, ImageSequential):
f"Integer mask labels must be exactly representable in {dtype}. "
"Use a float64 image where supported or remap labels to smaller integers."
)
- if mask.device.type == "mps" and torch_version_lt(2, 13, 0):
- # Older MPS has no asynchronous assertion kernel. Do not skip a correctness check there.
- if not bool(exact):
- raise RuntimeError(message)
- else:
- torch._assert_async(exact, message)
+ _check_async(exact, message)
return converted
@staticmethod
diff --git a/kornia/core/_compat.py b/kornia/core/_compat.py
index 1047d2f4f..29b6e037f 100644
--- a/kornia/core/_compat.py
+++ b/kornia/core/_compat.py
@@ -23,8 +23,6 @@ from typing import Any, Callable, Optional, Tuple, cast
import torch
-from kornia.core.utils import is_compiling
-
def torch_version() -> str:
"""Parse the PyTorch version string and remove build metadata.
@@ -142,7 +140,9 @@ def _emit_deprecation_warning(
``warnings.warn``, so warning there would break ``fullgraph=True`` for any code that calls a deprecated name.
Eager calls still warn on every call.
"""
- if is_compiling():
+ # ``torch.compiler.is_compiling`` rather than ``kornia.core.utils.is_compiling``: kornia.core.check imports this
+ # module, and kornia.core.utils imports kornia.core.check. Every supported torch has the public helper.
+ if torch.compiler.is_compiling():
return
beginning = f"Since kornia {version} the " if version is not None else ""
extra_reason = extra_reason.strip() if extra_reason else ""
diff --git a/kornia/core/check.py b/kornia/core/check.py
index 13001fada..1f94e06f3 100644
--- a/kornia/core/check.py
+++ b/kornia/core/check.py
@@ -26,7 +26,9 @@ from typing import TYPE_CHECKING, Any, Callable, Optional, Sequence, TypeVar, Un
import torch
from torch import float16, float32, float64
+from kornia.core._compat import torch_version_ge
from kornia.core.exceptions import (
+ AsyncCheckError,
BaseError,
DeviceError,
ImageError,
@@ -51,6 +53,7 @@ __all__ = [
"KORNIA_CHECK_SIZES",
"KORNIA_CHECK_TYPE",
"KORNIA_UNWRAP",
+ "AsyncCheckError",
"BaseError",
"DeviceError",
"ImageError",
@@ -85,6 +88,9 @@ def _should_enable_checks() -> bool:
# Module-level flag - evaluated once at import time, but can be changed at runtime
_KORNIA_CHECKS_ENABLED: bool = _should_enable_checks()
+# ``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)
+
if TYPE_CHECKING:
# A check message is a string, or a function without arguments that builds it; see ``KORNIA_CHECK``.
CheckMessage = Union[str, Callable[[], str]]
@@ -287,6 +293,71 @@ def KORNIA_CHECK(condition: bool, msg: Optional[CheckMessage] = None, raises: bo
return True
+def _vmap_is_active() -> bool:
+ """Whether a ``torch.vmap`` level is on the functorch transform stack."""
+ stack = torch._C._functorch.get_interpreter_stack()
+ return stack is not None and any(level.key() == torch._C._functorch.TransformType.Vmap for level in stack)
+
+
+def _check_async(condition: torch.Tensor, msg: str, guard: bool = False) -> None:
+ """Check a boolean tensor ``condition`` where it lives, without reading it back from an accelerator.
+
+ On CUDA, and on MPS from torch 2.13, the check is ``torch._assert_async``: the call returns at once, and a false
+ ``condition`` raises :exc:`RuntimeError` by the next synchronization, possibly earlier: on CUDA often at the next
+ kernel launch, still inside the calling function. On CUDA it is a device-side assert, after which the context
+ cannot be used. Reading the condition on the host instead would wait for every queued kernel.
+
+ On the CPU, on MPS before torch 2.13, which has no assert kernel, and on any other device, the condition is read on
+ the host and a false one raises :exc:`~kornia.core.exceptions.AsyncCheckError` during the call. A meta tensor has
+ no value to check.
+
+ Under ``torch.compile`` and ``torch.export`` the check is ``torch._assert_async`` on every device that has the
+ kernel, so it stays in the graph and raises :exc:`RuntimeError`; Inductor keeps it from torch 2.9 and compiles it
+ to nothing before. On a device without the kernel nothing is checked there. ``torch.jit.trace`` runs the assert on
+ the traced values but drops it from the graph it records, and TorchScript drops it too, so a scripted call checks
+ on the host only. It does so on every device but CUDA, since TorchScript cannot read whether MPS has the kernel.
+ A scripted CUDA call is not checked. The check is skipped when checks are disabled with :func:`disable_checks`,
+ with ``python -O`` or with ``KORNIA_CHECKS=0``, unless ``guard`` is set. It is also skipped under ``torch.vmap``,
+ which has no batching rule for the assert. Eager calls keep it under the other functorch transforms, such as
+ ``torch.func.grad``; a compiled call skips it under all of them, unless ``guard`` is set, since Dynamo cannot
+ inspect the transform stack.
+
+ Args:
+ condition: a boolean tensor with one element, usually ``(...).all()``.
+ msg: the message of the error. It is a string, since the device assert carries it unformatted.
+ guard: run the check even when checks are disabled, and under a compiled functorch transform. Set it where the
+ check keeps a later index in bounds: on the CPU a compiled ``gather`` or ``scatter`` with an index out of
+ range terminates the process. A compiled ``torch.vmap`` with ``fullgraph=True`` then fails to trace, as the
+ assert has no batching rule, so set it only in code that cannot run under ``vmap`` anyway, such as the
+ in-place histograms of the ``equalize`` lookups.
+ """
+ # TorchScript cannot read ``_MPS_HAS_ASSERT_ASYNC``, so a scripted call reads MPS and other devices on the host.
+ on_host = condition.device.type not in ("cuda", "meta")
+ if not torch.jit.is_scripting():
+ if not (guard or _KORNIA_CHECKS_ENABLED):
+ return
+ if torch._C._are_functorch_transforms_active():
+ if torch.compiler.is_compiling():
+ # Dynamo cannot trace the stack walk, so a compiled call skips the check under every functorch
+ # transform. A guard stays: it keeps an index in bounds, and the assert works under grad.
+ if not guard:
+ return
+ elif _vmap_is_active():
+ return
+ kind = condition.device.type
+ has_kernel = kind in ("cpu", "cuda", "meta") or (kind == "mps" and _MPS_HAS_ASSERT_ASYNC)
+ if torch.compiler.is_compiling() or torch.jit.is_tracing():
+ if has_kernel:
+ torch._assert_async(condition, msg)
+ return
+ on_host = not has_kernel or kind == "cpu"
+ if on_host:
+ if not bool(condition):
+ raise AsyncCheckError(msg)
+ else:
+ torch._assert_async(condition, msg)
+
+
def KORNIA_UNWRAP(maybe_obj: Any, typ: Any) -> Any:
"""Unwrap an optional contained value that may or not be present.
diff --git a/kornia/core/exceptions.py b/kornia/core/exceptions.py
index 97bc87b49..d0ea6221e 100644
--- a/kornia/core/exceptions.py
+++ b/kornia/core/exceptions.py
@@ -24,6 +24,7 @@ from typing import Any, Optional
import torch
__all__ = [
+ "AsyncCheckError",
"BaseError",
"DeviceError",
"ImageError",
@@ -38,7 +39,7 @@ class BaseError(Exception):
A failed ``KORNIA_CHECK`` raises it directly; it is neither a :exc:`ValueError` nor a :exc:`TypeError`. Each
subclass also derives from the one of those two built-ins that matches its failure, so the matching ``except``
- clause catches the subclass as well.
+ clause catches the subclass as well. :exc:`AsyncCheckError` is also a :exc:`RuntimeError`.
"""
@@ -102,6 +103,16 @@ class ValueCheckError(BaseError, ValueError):
self.expected_range = expected_range
+class AsyncCheckError(ValueCheckError, RuntimeError):
+ """Raised on the host by a value check that an accelerator runs as ``torch._assert_async``.
+
+ On CUDA, and on MPS from torch 2.13, the same check is not read back on the host: torch raises a
+ :exc:`RuntimeError` by the next synchronization instead, and on CUDA that is a device-side assert after which the
+ context cannot be used. This class is also a :exc:`RuntimeError`, so ``except RuntimeError`` handles a failure on
+ every device, and a :exc:`ValueCheckError` for the callers that catch the host failure as a value check.
+ """
+
+
class DeviceError(BaseError, ValueError):
"""Raised when device mismatch validation fails. Also a :exc:`ValueError`.
diff --git a/kornia/enhance/adjust.py b/kornia/enhance/adjust.py
index 836b86026..b67d91062 100644
--- a/kornia/enhance/adjust.py
+++ b/kornia/enhance/adjust.py
@@ -26,11 +26,11 @@ import torch.nn.functional as F
from torch import nn
from kornia.color import hsv_to_rgb, rgb_to_grayscale, rgb_to_hsv
-from kornia.core._compat import torch_version_ge
from kornia.core.check import (
KORNIA_CHECK,
KORNIA_CHECK_IS_COLOR_OR_GRAY,
KORNIA_CHECK_IS_TENSOR,
+ _check_async,
are_checks_enabled,
)
from kornia.core.exceptions import TypeCheckError
@@ -39,42 +39,6 @@ from kornia.core.utils import _normalize_to_float32_or_float64, _to_device_nonbl
from kornia.image.utils import _to_bcdhw, _to_bchw
-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 materializing ``cond`` on MPS would drain the queued stream on
- every call, so kornia skips the check there by design. The skip is this device check, not a
- missing kernel: torch 2.5.1 had no ``aten::_assert_async`` MPS kernel, torch 2.14 registers
- one, and the check is skipped on MPS either way.
- """
- if cond.device.type == "mps":
- return
- torch._assert_async(cond, msg)
-
-
-# ``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 _lookup_value_check(cond: torch.Tensor, msg: str) -> None:
- """Validate the input domain of a 256-entry lookup, including on MPS.
-
- Same as :func:`_assert_async_value_check` on CPU and CUDA. On MPS that helper skips the check, and an
- index the lookup cannot use then surfaces as torch's raw ``gather: index ... is out of bounds`` error,
- which names neither the op nor the range it needs. From torch ``2.13`` the assert has an MPS kernel, so
- the same asynchronous check runs there: no host read, and the named error is reported at the next
- synchronization. Older releases have none, and the lookups guarded here consume the whole input anyway,
- so the condition is read on the host instead: one stream sync per call. A host read would break a
- ``torch.compile`` graph, so only that older fallback keeps the skip while compiling.
- """
- if cond.device.type == "mps" and not _MPS_HAS_ASSERT_ASYNC:
- if not is_compiling() and not bool(cond):
- raise RuntimeError(msg)
- return
- torch._assert_async(cond, msg)
-
-
def _clip_unit_fresh(image: torch.Tensor) -> torch.Tensor:
"""Clamp a tensor this module just allocated into ``[0, 1]``, in place when no gradient is recorded.
@@ -421,8 +385,10 @@ def adjust_gamma(
See a working example `here <https://www.kornia.org/tutorials/nbs/image_enhancement.html>`__.
.. note::
- The non-negativity check on ``gamma``/``gain`` runs on CPU and CUDA (via ``torch._assert_async``).
- kornia skips it on MPS by design, so invalid values do not raise there.
+ The non-negativity check on ``gamma``/``gain`` reads a CPU value during the call and raises
+ :exc:`~kornia.core.exceptions.AsyncCheckError`, a :exc:`RuntimeError`. A tensor on CUDA, or on MPS
+ from torch 2.13, is checked with ``torch._assert_async`` instead and raises ``RuntimeError`` by the
+ next synchronization; on CUDA that is a device-side assert.
Example:
>>> x = torch.ones(1, 1, 2, 2)
@@ -487,11 +453,11 @@ def adjust_gamma(
gamma = gamma.to(input.device).to(input.dtype)
gain = gain.to(input.device).to(input.dtype)
- _assert_async_value_check(
+ _check_async(
(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(
+ _check_async(
(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.",
)
@@ -553,8 +519,10 @@ def adjust_contrast(image: torch.Tensor, factor: Union[float, torch.Tensor], cli
See a working example `here <https://www.kornia.org/tutorials/nbs/image_enhancement.html>`__.
.. note::
- The non-negativity check on ``factor`` runs on CPU and CUDA (via ``torch._assert_async``).
- kornia skips it on MPS by design, so invalid values do not raise there.
+ The non-negativity check on ``factor`` reads a CPU value during the call and raises
+ :exc:`~kornia.core.exceptions.AsyncCheckError`, a :exc:`RuntimeError`. A tensor on CUDA, or on MPS
+ from torch 2.13, is checked with ``torch._assert_async`` instead and raises ``RuntimeError`` by the
+ next synchronization; on CUDA that is a device-side assert.
Example:
>>> import torch
@@ -581,7 +549,7 @@ def adjust_contrast(image: torch.Tensor, factor: Union[float, torch.Tensor], cli
factor = _make_factor_broadcastable(factor, image)
- _assert_async_value_check(
+ _check_async(
(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.",
@@ -918,9 +886,10 @@ def solarize(
The solarized images with shape :math:`(*, C, H, W)`.
.. note::
- The range check on ``additions`` runs via ``torch._assert_async`` on the device of ``additions``.
- kornia skips it for an ``additions`` tensor on MPS, so invalid values do not raise there, but a
- float, or a CPU tensor, is checked on the CPU and raises for an MPS image too.
+ The range check on ``additions`` reads a float or a CPU tensor during the call and raises
+ :exc:`~kornia.core.exceptions.AsyncCheckError`, a :exc:`RuntimeError`, whatever the device of the image.
+ A tensor on CUDA, or on MPS from torch 2.13, is checked with ``torch._assert_async`` instead and raises
+ ``RuntimeError`` by the next synchronization; on CUDA that is a device-side assert.
Example:
>>> x = torch.rand(1, 4, 3, 3)
@@ -950,14 +919,14 @@ def solarize(
raise TypeError(f"The factor should be either a float or torch.Tensor. Got {type(additions)}")
if isinstance(additions, float):
- # Check the Python value on the host: rounded to float16/bfloat16, a value just past the bound
- # passes, and the check is skipped for a tensor on MPS.
- in_range = torch.tensor(-0.5 <= additions <= 0.5)
+ # Check the Python value on the host, whatever the default device: rounded to float16/bfloat16, a
+ # value just past the bound passes.
+ in_range = torch.tensor(-0.5 <= additions <= 0.5, device="cpu")
additions = torch.as_tensor(additions, device=input.device, dtype=input.dtype)
else:
in_range = ((additions <= 0.5) & (additions >= -0.5)).all()
- _assert_async_value_check(
+ _check_async(
in_range,
"The addition must be in the closed range [-0.5, 0.5]. Clamp it first: min(max(additions, -0.5), 0.5) "
"for floats, additions.clamp(-0.5, 0.5) for tensors.",
@@ -1194,12 +1163,14 @@ def _scale_channel_batched(input: torch.Tensor) -> torch.Tensor:
# Input is expected in [0, 1]. The histogram and the LUT lookup both index with ``scaled.long()``,
# which is out of bounds unless ``scaled`` is in (-1, 256).
# Check that domain without ``.item()``, so there is no device sync and fullgraph still compiles;
- # on MPS before torch 2.13 it costs one host sync instead (see ``_lookup_value_check``). Inputs the
- # lookup can index keep working exactly as before.
- _lookup_value_check(
+ # on MPS before torch 2.13 it costs one host sync instead (see ``_check_async``). Inputs the
+ # lookup can index keep working exactly as before. The check keeps the index in bounds, so it runs
+ # with checks disabled too: a compiled CPU scatter with an index out of range terminates the process.
+ _check_async(
((scaled > -1.0) & (scaled < 256.0)).all(),
"equalize expects input values in [0, 1]. Scale the image into that range first, "
"for example image / 255.0 for 8-bit data.",
+ guard=True,
)
# Count in float32 (float64 stays float64): a count grows with the plane size, which half precision
@@ -1262,9 +1233,10 @@ def equalize(input: torch.Tensor) -> torch.Tensor:
boolean image raises
:exc:`~kornia.core.exceptions.TypeCheckError` (a :exc:`TypeError`); convert 8-bit data with
``image.float() / 255`` first. Values the 256-bin lookup cannot index (outside roughly :math:`[0, 1]`)
- raise a ``RuntimeError`` naming the range. The check is ``torch._assert_async``, which has an MPS kernel
- from torch ``2.13``; on an older MPS release the condition is read on the host instead, one device sync
- per call, and is skipped there under ``torch.compile``.
+ raise a ``RuntimeError`` naming the range, during the call for a CPU image, even when checks are
+ disabled, since the check keeps the lookup in bounds. On CUDA, and on MPS from torch ``2.13``, the check
+ is ``torch._assert_async`` and raises by the next synchronization; on an older MPS release the condition
+ is read on the host instead, one device sync per call, and is skipped there under ``torch.compile``.
Example:
>>> x = torch.rand(1, 2, 3, 3)
@@ -1301,9 +1273,10 @@ def equalize3d(input: torch.Tensor) -> torch.Tensor:
floating-point roundoff; just above that, whether it changes depends on the values. An integer or
boolean volume raises :exc:`~kornia.core.exceptions.TypeCheckError`, as for :func:`equalize`. Values
the 256-bin lookup cannot index (outside roughly :math:`[0, 1]`) raise a ``RuntimeError`` naming the
- range. The check is ``torch._assert_async``, which has an MPS kernel from torch ``2.13``; on an older
- MPS release the condition is read on the host instead, one device sync per call, and is skipped there
- under ``torch.compile``.
+ range, during the call for a CPU volume, even when checks are disabled, as for :func:`equalize`. On CUDA,
+ and on MPS from torch ``2.13``, the check is ``torch._assert_async`` and raises by the next
+ synchronization; on an older MPS release the condition is read on the host instead, one device sync per
+ call, and is skipped there under ``torch.compile``.
"""
_check_floating_image(input, "equalize3d")
diff --git a/kornia/enhance/equalization.py b/kornia/enhance/equalization.py
index cf737d193..c6bb557f0 100644
--- a/kornia/enhance/equalization.py
+++ b/kornia/enhance/equalization.py
@@ -23,10 +23,11 @@ from typing import Tuple, Union
import torch
import torch.nn.functional as F
+from kornia.core.check import _check_async
from kornia.core.utils import _normalize_to_float32_or_float64, _to_device_nonblocking
from kornia.image.utils import perform_keep_shape_image
-from .adjust import _check_floating_image, _lookup_value_check
+from .adjust import _check_floating_image
from .histogram import histogram
@@ -526,10 +527,9 @@ def equalize_clahe(
``slow_and_differentiable=True`` keeps its soft histogram centred on the levels ``k / 255``. An integer
or boolean image raises :exc:`~kornia.core.exceptions.TypeCheckError` (a :exc:`TypeError`); convert
8-bit data with ``image.float() / 255`` first, as for :func:`kornia.enhance.equalize`. Values the lookup
- cannot index (outside roughly :math:`[0, 1]`) raise a ``RuntimeError`` naming the range. The check is
- ``torch._assert_async``, which has an MPS kernel from torch ``2.13``; on an older MPS release the
- condition is read on the host instead, one device sync per call, and is skipped there under
- ``torch.compile``, as for :func:`kornia.enhance.equalize`.
+ cannot index (outside roughly :math:`[0, 1]`) raise a ``RuntimeError`` naming the range, at the same
+ point as for :func:`kornia.enhance.equalize`: during the call for a CPU image, and by the next
+ synchronization on CUDA and on MPS from torch ``2.13``, even when checks are disabled.
"""
_check_floating_image(input, "equalize_clahe")
@@ -561,11 +561,13 @@ def _equalize_clahe(
# The tile LUTs are gathered below with ``(interp_tiles * 255).long()``, which is in bounds
# only for values in (-1/255, 256/255). Check that domain without ``.item()``, so there is no
# device sync and fullgraph still compiles; on MPS before torch 2.13 it costs one host sync instead
- # (see ``_lookup_value_check``). Inputs the lookup can index are unchanged.
- _lookup_value_check(
+ # (see ``_check_async``). Inputs the lookup can index are unchanged. The check keeps the index in
+ # bounds, so it runs with checks disabled too: a compiled CPU gather out of range terminates the process.
+ _check_async(
((input * 255.0 > -1.0) & (input * 255.0 < 256.0)).all(),
"equalize_clahe expects input values in [0, 1]. Scale the image into that range first, "
"for example image / 255.0 for 8-bit data.",
+ guard=True,
)
imgs: torch.Tensor = input # B x C x H x W
diff --git a/kornia/enhance/histogram.py b/kornia/enhance/histogram.py
index 4afcad7e1..9dfdea33b 100644
--- a/kornia/enhance/histogram.py
+++ b/kornia/enhance/histogram.py
@@ -20,10 +20,9 @@ from typing import Optional, Tuple
import torch
+from kornia.core.check import _check_async
from kornia.core.exceptions import ShapeError
-from .adjust import _assert_async_value_check
-
def marginal_pdf(
values: torch.Tensor, bins: torch.Tensor, sigma: torch.Tensor, epsilon: float = 1e-10
@@ -62,7 +61,7 @@ def marginal_pdf(
# Asynchronous like the other tensor-parameter checks in kornia.enhance: no host sync, and a compiled graph
# keeps the check instead of skipping it.
- _assert_async_value_check(torch.isfinite(sigma) & (sigma > 0), "Bandwidth must be finite and greater than zero.")
+ _check_async(torch.isfinite(sigma) & (sigma > 0), "Bandwidth must be finite and greater than zero.")
residuals = values - bins.unsqueeze(0).unsqueeze(0)
kernel_values = torch.exp(-0.5 * (residuals / sigma).pow(2))
@@ -116,8 +115,8 @@ def histogram(x: torch.Tensor, bins: torch.Tensor, bandwidth: torch.Tensor, epsi
Rows are independent samples: x has shape (B, D), bins is the shared
one-dimensional center grid, and the result has shape (B, N_bins).
histogram2d uses the same batch convention for a joint density. bandwidth must be
- finite and positive; the check runs on CPU and CUDA via ``torch._assert_async`` and
- raises ``RuntimeError``. kornia skips it on MPS by design, so invalid values do not raise there.
+ finite and positive; the check raises a ``RuntimeError`` during the call for a CPU bandwidth, and by
+ the next synchronization for one on CUDA, or on MPS from torch 2.13, where it is ``torch._assert_async``.
For float16 and bfloat16 samples and bins, the kernels are evaluated in float32 and the result
is cast back to that dtype.
diff --git a/kornia/filters/gaussian.py b/kornia/filters/gaussian.py
index 792d92206..5e2fddd8f 100644
--- a/kornia/filters/gaussian.py
+++ b/kornia/filters/gaussian.py
@@ -21,14 +21,14 @@ import torch
import torch.nn.functional as F
from torch import nn
-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,
+ _check_async,
are_checks_enabled,
)
+from kornia.core.exceptions import AsyncCheckError
from kornia.core.ops import _device_literal
from kornia.core.utils import _autocast_disabled, _to_device_nonblocking, is_autocast_enabled, is_compiling
@@ -39,9 +39,6 @@ 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."""
@@ -134,8 +131,9 @@ 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, 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
+ ~kornia.core.exceptions.AsyncCheckError: if sigma values are not positive, for a tuple or a CPU tensor
+ ``sigma``. It is also a :exc:`RuntimeError`.
+ RuntimeError: by 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.
@@ -143,9 +141,10 @@ def gaussian_blur2d(
.. 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
+ back: a value that is not positive raises ``RuntimeError`` by 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``.
+ older release ``sigma`` is read on the host instead. The check is skipped under ``torch.compile`` and when
+ checks are disabled with :func:`~kornia.core.check.disable_checks`.
.. note::
See a working example `here <https://www.kornia.org/tutorials/nbs/gaussian_blur.html>`__.
@@ -205,8 +204,8 @@ 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):
- # Built on the host, so that it is checked there like the Python numbers.
- host_sigma = torch.tensor([sigma], dtype=input.dtype)
+ # Built on the host, whatever the default device, so that it is checked there like the Python numbers.
+ host_sigma = torch.tensor([sigma], dtype=input.dtype, device="cpu")
sigma = _to_device_nonblocking(host_sigma, input.device)
else:
KORNIA_CHECK_IS_TENSOR(sigma)
@@ -216,22 +215,19 @@ 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.
- # ``disable_checks()`` skips it as well, so that the device assert below never runs when checks are off.
+ # Skipped under compile: a sigma built on the host from Python numbers would become a device assert of the graph.
+ # ``are_checks_enabled()`` spares building the condition when checks are disabled; the helper would skip it anyway.
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)
- 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")
+ # The same rounding to the input dtype as the device tensor, on the host whatever the default device.
+ host_sigma = torch.tensor([host_sigma], dtype=input.dtype, device="cpu")
+ # Read on the host for a tuple or a CPU tensor. A device sigma is checked where it lives (#6335): reading it
+ # would wait for every queued kernel, so a value that is not positive raises by the next synchronization.
+ try:
+ _check_async((host_sigma > 0).all(), "sigma must be positive")
+ except AsyncCheckError:
+ # Only the host read raises here, so the value is formatted on the host, and only when the check fails.
+ raise AsyncCheckError(f"sigma must be positive, got {host_sigma}") from None
if separable:
ky, kx = _unpack_2d_ks(kernel_size)
diff --git a/kornia/geometry/boxes.py b/kornia/geometry/boxes.py
index d9c22520a..3a6f91016 100644
--- a/kornia/geometry/boxes.py
+++ b/kornia/geometry/boxes.py
@@ -22,6 +22,7 @@ from typing import Any, Optional, Tuple, cast
import torch
from torch import Size
+from kornia.core.check import _check_async
from kornia.core.ops import eye_like
from kornia.core.utils import is_compiling, is_exporting
from kornia.geometry.linalg import transform_points
@@ -112,19 +113,6 @@ def _validate_box_values(boxes: torch.Tensor, width: torch.Tensor, height: torch
raise ValueError("Some boxes have negative heights or 0.")
-def _assert_finite_vertices(boxes: torch.Tensor) -> None:
- """Reject a non-finite vertex coordinate without reading the data on the host.
-
- ``AugmentationSequential`` imports ``'bbox'`` data through ``'vertices_plus'`` inside a ``fullgraph=True``
- compile, where a Python ``if`` on the data would break the graph. ``torch._assert_async`` raises
- ``RuntimeError`` instead. As in :mod:`kornia.enhance`, the check is skipped on MPS, where materializing the
- condition would drain the queued stream on every call.
- """
- if boxes.device.type == "mps":
- return
- torch._assert_async(torch.isfinite(boxes).all(), "Some boxes have non-finite coordinates.")
-
-
def _boxes_to_quadrilaterals(boxes: torch.Tensor, mode: str = "xyxy", validate_boxes: bool = True) -> torch.Tensor:
"""Convert from boxes to quadrilaterals."""
mode = mode.lower()
@@ -147,7 +135,7 @@ def _boxes_to_quadrilaterals(boxes: torch.Tensor, mode: str = "xyxy", validate_b
# finiteness asynchronously so that they stay fullgraph-compilable.
# The coordinate modes check finiteness together with the extents below, in one host read.
if validate_boxes and not is_exporting() and boxes.numel() > 0 and mode.startswith("vertices"):
- _assert_finite_vertices(boxes)
+ _check_async(torch.isfinite(boxes).all(), "Some boxes have non-finite coordinates.")
if mode.startswith("vertices"):
if mode == "vertices":
@@ -244,8 +232,9 @@ class Boxes:
:func:`~kornia.geometry.bbox.nms` takes exclusive ``xyxy``.
- With ``validate_boxes=True``, every mode rejects a non-finite coordinate. The ``'xy*'`` modes raise
``ValueError`` and also reject non-positive extents. The vertex modes raise ``RuntimeError`` through
- ``torch._assert_async`` (on CPU and CUDA, skipped on MPS), so they stay ``fullgraph``-compilable, and take
- no extent or shape check, so the arbitrary quadrilaterals of :meth:`transform_boxes` import unchanged.
+ ``torch._assert_async`` (by the next synchronization on CUDA, and on MPS from torch 2.13), so they stay
+ ``fullgraph``-compilable, and take no extent or shape check, so the arbitrary quadrilaterals of
+ :meth:`transform_boxes` import unchanged.
- The constructor rejects an integer tensor unless ``raise_if_not_floating_point=False`` (a list is
checked by its first element's dtype); :meth:`from_tensor` casts integer input to the default dtype.
- :meth:`merge` and :meth:`index_put` are non-mutating by default.
@@ -699,7 +688,7 @@ class Boxes:
validate_boxes: Reject a non-finite coordinate in every mode: ``ValueError`` for the ``'xy*'`` modes,
which also reject non-positive extents in each mode's convention, and ``RuntimeError`` from
- ``torch._assert_async`` for the vertex modes (skipped on MPS), which take no extent or shape check.
+ ``torch._assert_async`` for the vertex modes, which take no extent or shape check.
The ``'xy*'`` checks read the data, so graph capture (``torch.compile``, ``torch.export``) skips
them.
@@ -1116,7 +1105,7 @@ class VideoBoxes(Boxes):
bottom-left), stored unchanged; integer input is cast to
``torch.get_default_dtype()``. Lists of tensors are not supported yet.
validate_boxes: Reject a non-finite coordinate with ``RuntimeError``
- (``torch._assert_async``, skipped on MPS). There is no extent or shape
+ (``torch._assert_async``). There is no extent or shape
check, as for ``'vertices_plus'`` in
:meth:`~kornia.geometry.boxes.Boxes.from_tensor`.
diff --git a/testing/half_precision_eager_rng.py b/testing/half_precision_eager_rng.py
index 5a7d999b6..596d31982 100644
--- a/testing/half_precision_eager_rng.py
+++ b/testing/half_precision_eager_rng.py
@@ -172,7 +172,7 @@ AUDITED_EAGER_RNG_CALLS = tuple(
(f"tests/core/test_check.py::TestCheckShape::{test_name}",),
"value-independent",
)
- for test_name, lines in (("test_valid", range(78, 82)), ("test_invalid", range(90, 94)))
+ for test_name, lines in (("test_valid", range(84, 88)), ("test_invalid", range(96, 100)))
for line in lines
),
*(
diff --git a/tests/api_surface.json b/tests/api_surface.json
index 954f0eca3..facfcca87 100644
--- a/tests/api_surface.json
+++ b/tests/api_surface.json
@@ -246,6 +246,7 @@
"vec_like"
],
"kornia.core.check": [
+ "AsyncCheckError",
"BaseError",
"DeviceError",
"ImageError",
@@ -272,6 +273,7 @@
"enable_checks"
],
"kornia.core.exceptions": [
+ "AsyncCheckError",
"BaseError",
"DeviceError",
"ImageError",
diff --git a/tests/augmentation/test_conventions_intensity_values.py b/tests/augmentation/test_conventions_intensity_values.py
index 7170a409f..3b82958c0 100644
--- a/tests/augmentation/test_conventions_intensity_values.py
+++ b/tests/augmentation/test_conventions_intensity_values.py
@@ -26,7 +26,8 @@ import torch
import kornia.augmentation as K
from kornia.augmentation._2d.intensity.base import _clamp_unit_range
from kornia.augmentation.random_generator import RectangleEraseGenerator
-from kornia.core.exceptions import BaseError, ShapeError
+from kornia.core._compat import torch_version_ge
+from kornia.core.exceptions import AsyncCheckError, BaseError, ShapeError
from kornia.enhance import (
adjust_brightness,
adjust_contrast,
@@ -407,14 +408,20 @@ class TestIntensityColourConventions(BaseTester):
self.assert_close(out, raw.clamp(0.0, 1.0))
assert float((out - raw).abs().max()) > unclamped_gap / 2
- def test_convention_random_gamma_negative_exponent_is_unchecked_on_mps(self, device, dtype):
- if device.type != "mps":
- pytest.skip("MPS only: CPU rejects negative gamma; CUDA would invalidate the context with a device assert")
- # kornia does not run the non-negativity check for an MPS image, so gamma=-1 is evaluated as
- # clamp(gain / input, 0, 1).
+ def test_convention_random_gamma_negative_exponent_is_rejected(self, device, dtype):
+ if device.type == "cuda":
+ pytest.skip("not on CUDA: the value check is a device-side assert that invalidates the context")
+ # The non-negativity check of adjust_gamma runs on every device. It reads a CPU value during the call, and so
+ # on MPS before torch 2.13, which has no assert kernel; from 2.13 the MPS assert raises at the next sync.
image = torch.tensor([0.2, 0.5, 0.8], device=device, dtype=dtype).reshape(1, 3, 1, 1)
- out = K.RandomGamma((-1.0, -1.0), (0.1, 0.1), p=1.0)(image)
- self.assert_close(out, image.new_tensor([0.5, 0.2, 0.125]).reshape_as(image))
+ augmentation = K.RandomGamma((-1.0, -1.0), (0.1, 0.1), p=1.0)
+ if device.type == "mps" and torch_version_ge(2, 13):
+ augmentation(image)
+ with pytest.raises(RuntimeError, match="Gamma must be non-negative"):
+ torch.mps.synchronize()
+ else:
+ with pytest.raises(AsyncCheckError, match="Gamma must be non-negative"):
+ augmentation(image)
def test_convention_random_saturation_clamps_input_and_rgb_4430(self, device, dtype):
pixels = [[-0.1, 0.5, 0.5], [1.5, 0.0, 0.0], [-0.1, -0.5, -0.9], [2.0, 1.0, 0.5]]
@@ -1092,7 +1099,7 @@ class TestIntensityColourConventions(BaseTester):
)
def test_convention_intensity_constructors_reject_out_of_bounds(self, device, dtype, case, stage, error, match):
if case in ("gamma_negative", "gain_negative") and device.type != "cpu":
- pytest.skip("CPU only: on CUDA the value assert is a device-side assert; kornia skips it on MPS")
+ pytest.skip("CPU only: a device-side assert on CUDA, and raised at the next sync on MPS from torch 2.13")
factories = {
"sharpness_negative": lambda: K.RandomSharpness(-1.0, p=1.0),
"posterize_bits_above_eight": lambda: K.RandomPosterize(bits=9, p=1.0),
diff --git a/tests/core/test_check.py b/tests/core/test_check.py
index 2fc5b4c63..7aeff1594 100644
--- a/tests/core/test_check.py
+++ b/tests/core/test_check.py
@@ -16,11 +16,15 @@
#
import re
+import subprocess
+import sys
+import textwrap
from typing import Optional, Union
import pytest
import torch
+from kornia.core._compat import torch_version_ge
from kornia.core.check import (
KORNIA_CHECK,
KORNIA_CHECK_DM_DESC,
@@ -38,11 +42,13 @@ from kornia.core.check import (
KORNIA_CHECK_SHAPE,
KORNIA_CHECK_SIZES,
KORNIA_CHECK_TYPE,
+ _check_async,
are_checks_enabled,
disable_checks,
enable_checks,
)
from kornia.core.exceptions import (
+ AsyncCheckError,
BaseError,
DeviceError,
ImageError,
@@ -901,3 +907,176 @@ class TestDeferredMessage:
x = torch.rand(batch, batch + 3)
assert torch.equal(compiled(x), x * 2)
assert counter.frame_count == 1
+
+
+class TestCheckAsync(BaseTester):
+ """``_check_async``: a tensor condition checked where it lives, without a host read on an accelerator."""
+
+ def setup_method(self):
+ enable_checks()
+
+ def teardown_method(self):
+ enable_checks()
+
+ @staticmethod
+ def _reads_on_the_host(device: torch.device) -> bool:
+ return device.type == "cpu" or (device.type == "mps" and not torch_version_ge(2, 13))
+
+ def test_smoke(self, device):
+ assert _check_async(torch.ones(3, device=device, dtype=torch.bool).all(), "never raised") is None
+
+ def test_invalid_on_the_host_raises_at_once(self, device):
+ if not self._reads_on_the_host(device):
+ pytest.skip("on CUDA, and on MPS from torch 2.13, the check is torch._assert_async")
+ with pytest.raises(AsyncCheckError, match="x must be positive"):
+ _check_async((torch.tensor([1.0, -1.0], device=device) > 0).all(), "x must be positive")
+
+ def test_invalid_on_mps_raises_at_the_next_sync(self, device):
+ if device.type != "mps" or not torch_version_ge(2, 13):
+ pytest.skip("pins the MPS assert kernel of torch 2.13")
+ _check_async((torch.tensor([1.0, -1.0], device=device) > 0).all(), "x must be positive")
+ with pytest.raises(RuntimeError, match="x must be positive"):
+ torch.mps.synchronize()
+
+ def test_invalid_on_cuda_is_a_device_assert(self, device):
+ # The assert leaves the CUDA context unusable, so it runs in a process of its own.
+ if device.type != "cuda":
+ pytest.skip("pins the CUDA device-side assert")
+ script = textwrap.dedent(
+ """
+ import torch
+ from kornia.core.check import _check_async
+
+ _check_async((torch.tensor([1.0, -1.0], device="cuda") > 0).all(), "x must be positive")
+ print("returned")
+ try:
+ torch.cuda.synchronize()
+ except RuntimeError as error:
+ print(type(error).__name__)
+ """
+ )
+ # Trusted, fixed command (the current interpreter running a literal script); no external input.
+ result = subprocess.run( # noqa: S603
+ [sys.executable, "-c", script], capture_output=True, text=True, check=False, timeout=300
+ )
+ # torch 2.5.1 has no AcceleratorError and raises a plain RuntimeError.
+ assert result.stdout.split() in (["returned", "AcceleratorError"], ["returned", "RuntimeError"]), (
+ result.stdout + result.stderr
+ )
+ assert "x must be positive" in result.stderr
+
+ def test_valid_on_cuda_does_not_synchronize(self, device):
+ if device.type != "cuda":
+ pytest.skip("CUDA host synchronizations need a CUDA device")
+ x = torch.rand(8, device=device) + 0.5
+ torch.cuda.synchronize()
+ previous = torch.cuda.get_sync_debug_mode()
+ torch.cuda.set_sync_debug_mode("error")
+ try:
+ _check_async((x > 0).all(), "x must be positive")
+ finally:
+ torch.cuda.set_sync_debug_mode(previous)
+
+ def test_meta_has_nothing_to_check(self):
+ _check_async(torch.zeros((), dtype=torch.bool, device="meta"), "never raised")
+
+ def test_skipped_when_checks_are_disabled(self):
+ disable_checks()
+ _check_async(torch.tensor(False), "never raised")
+
+ def test_skipped_under_vmap(self, device):
+ # vmap has no batching rule for torch._assert_async, so the check is skipped rather than failing the call.
+ def op(x: torch.Tensor) -> torch.Tensor:
+ _check_async((x > 0).all(), "x must be positive")
+ return x * 2
+
+ x = torch.rand(3, 4, device=device) + 0.5
+ self.assert_close(torch.vmap(op)(x), x * 2)
+
+ def test_guard_runs_when_checks_are_disabled(self):
+ # A guard keeps a later index in bounds, which a compiled CPU gather or scatter could not survive.
+ disable_checks()
+ with pytest.raises(AsyncCheckError, match="index out of range"):
+ _check_async(torch.tensor(False), "index out of range", guard=True)
+
+ def test_runs_under_the_other_functorch_transforms(self):
+ # Only vmap lacks a batching rule for the assert: grad, jvp and functionalize keep the check in eager code.
+ def op(x: torch.Tensor) -> torch.Tensor:
+ _check_async((x > 0).all(), "x must be positive")
+ return (x * 2).sum()
+
+ invalid = -torch.ones(3)
+ with pytest.raises(AsyncCheckError, match="x must be positive"):
+ torch.func.grad(op)(invalid)
+ with pytest.raises(AsyncCheckError, match="x must be positive"):
+ torch.func.jvp(op, (invalid,), (torch.ones(3),))
+ with pytest.raises(AsyncCheckError, match="x must be positive"):
+ torch.func.functionalize(op)(invalid)
+
+ def test_dynamo_under_functorch_transforms(self, device, torch_optimizer, optimizer_backend):
+ # Dynamo cannot trace the walk of the transform stack, so a compiled vmap or grad skips the check instead of
+ # breaking the graph.
+ if optimizer_backend == "jit":
+ pytest.skip("TorchScript does not script functorch transforms")
+
+ def op(x: torch.Tensor) -> torch.Tensor:
+ _check_async((x > 0).all(), "x must be positive")
+ return (x * 2).sum()
+
+ x = torch.rand(2, 3, device=device) + 0.5
+ batched = torch_optimizer(torch.vmap(op), fullgraph=True)
+ self.assert_close(batched(x), (x * 2).sum(1))
+ gradient = torch_optimizer(torch.func.grad(op), fullgraph=True)
+ self.assert_close(gradient(x[0]), torch.full_like(x[0], 2.0))
+
+ def test_jit_raises_on_the_host(self, device):
+ # TorchScript cannot read whether MPS has the assert kernel (from torch 2.13), so a scripted call reads a
+ # condition on any device but CUDA on the host, and raises during the call.
+ if device.type == "cuda":
+ pytest.skip("TorchScript drops torch._assert_async, so a scripted CUDA call is not checked")
+
+ def op(x: torch.Tensor) -> torch.Tensor:
+ _check_async((x > 0).all(), "x must be positive")
+ return x * 2
+
+ scripted = torch.jit.script(op)
+ assert torch.equal(scripted(torch.ones(2, device=device)), torch.full((2,), 2.0, device=device))
+ with pytest.raises(torch.jit.Error, match="AsyncCheckError: x must be positive"):
+ scripted(-torch.ones(2, device=device))
+
+ def test_dynamo(self, device, torch_optimizer, optimizer_backend):
+ if optimizer_backend == "jit":
+ pytest.skip("covered by test_jit_raises_on_the_host")
+
+ def op(x: torch.Tensor) -> torch.Tensor:
+ _check_async((x > 0).all(), "x must be positive")
+ return x * 2
+
+ compiled = torch_optimizer(op, fullgraph=True)
+ x = torch.rand(2, 3, device=device) + 0.5
+ self.assert_close(compiled(x), x * 2)
+ if device.type != "cpu":
+ pytest.skip("an invalid value would fail on the device; the CPU kernel raises in the process")
+ if not torch_version_ge(2, 9):
+ pytest.skip("Inductor compiles torch._assert_async to nothing before torch 2.9")
+ with pytest.raises(RuntimeError, match="x must be positive"):
+ compiled(-x)
+
+ def test_dynamo_guard_under_functorch_transforms(self, device, torch_optimizer, optimizer_backend):
+ # A guard keeps a later index in bounds, so a compiled grad keeps it, unlike the checks without one.
+ if optimizer_backend == "jit":
+ pytest.skip("TorchScript does not script functorch transforms")
+
+ def op(x: torch.Tensor) -> torch.Tensor:
+ _check_async((x > 0).all(), "x must be positive", guard=True)
+ return (x * 2).sum()
+
+ x = torch.full((3,), 0.5, device=device)
+ gradient = torch_optimizer(torch.func.grad(op), fullgraph=True)
+ self.assert_close(gradient(x), torch.full_like(x, 2.0))
+ if device.type != "cpu":
+ pytest.skip("an invalid value would fail on the device; the CPU kernel raises in the process")
+ if not torch_version_ge(2, 9):
+ pytest.skip("Inductor compiles torch._assert_async to nothing before torch 2.9")
+ with pytest.raises(RuntimeError, match="x must be positive"):
+ gradient(-x)
diff --git a/tests/core/test_exceptions.py b/tests/core/test_exceptions.py
index 4c58c9229..eea02cf57 100644
--- a/tests/core/test_exceptions.py
+++ b/tests/core/test_exceptions.py
@@ -37,6 +37,7 @@ from kornia.core.check import (
KORNIA_CHECK_TYPE,
)
from kornia.core.exceptions import (
+ AsyncCheckError,
BaseError,
DeviceError,
ImageError,
@@ -153,3 +154,26 @@ class TestExceptionBases(BaseTester):
assert clone.args == raised.args
assert str(clone) == str(raised)
assert vars(clone) == vars(raised)
+
+
+class TestAsyncCheckError:
+ """The host form of a check that runs ``torch._assert_async`` on an accelerator."""
+
+ def test_convention_catchable_as_runtime_and_value_error(self):
+ # torch raises a RuntimeError for the same check on an accelerator, so ``except RuntimeError`` handles every
+ # device; ``except BaseError`` and ``except ValueError`` keep catching it like any other value check.
+ assert AsyncCheckError.__bases__ == (ValueCheckError, RuntimeError)
+ error = AsyncCheckError("x must be positive")
+ assert isinstance(error, (BaseError, ValueCheckError, ValueError, RuntimeError))
+ assert error.actual_value is None
+ assert error.expected_range is None
+
+ def test_pickle_and_copy_keep_class_and_message(self):
+ error = AsyncCheckError("x must be positive")
+ protocols = range(2, pickle.HIGHEST_PROTOCOL + 1)
+ clones = [pickle.loads(pickle.dumps(error, protocol=p)) for p in protocols] # noqa: S301 - our own bytes
+ clones += [copy.copy(error), copy.deepcopy(error)]
+ for clone in clones:
+ assert type(clone) is AsyncCheckError
+ assert clone.args == error.args
+ assert vars(clone) == vars(error)
diff --git a/tests/enhance/test_adjust.py b/tests/enhance/test_adjust.py
index aeae2104e..8e15b5efe 100644
--- a/tests/enhance/test_adjust.py
+++ b/tests/enhance/test_adjust.py
@@ -26,6 +26,7 @@ from kornia import enhance
from kornia.constants import pi
from kornia.core._compat import torch_version_ge
from kornia.core.check import are_checks_enabled, disable_checks, enable_checks
+from kornia.core.exceptions import AsyncCheckError
from testing.base import DYNAMO_UNAVAILABLE_REASON, BaseTester, dynamo_is_available
@@ -560,25 +561,46 @@ class TestAdjustContrast(BaseTester):
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)")
+ pytest.skip("the value check raises during the call only on CPU; see test_mps_checks_the_factor")
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.
+ def test_mps_checks_the_factor(self, device, dtype):
+ # The factor is checked on MPS as well: from torch 2.13 by the asynchronous assert, which raises at the next
+ # synchronization, and before, without that kernel, on the host during the call.
if device.type != "mps":
- pytest.skip("pins the MPS-only no-CPU-fallback behavior")
+ pytest.skip("pins the MPS 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
+ if torch_version_ge(2, 13):
+ kornia.enhance.adjust_contrast(img, factor)
+ with pytest.raises(RuntimeError, match="non-negative"):
+ torch.mps.synchronize()
+ else:
+ with pytest.raises(AsyncCheckError, match="non-negative"):
+ kornia.enhance.adjust_contrast(img, factor)
+
+ def test_factor_check_is_skipped_when_checks_are_disabled(self, device, dtype):
+ img = torch.rand(1, 3, 4, 4, device=device, dtype=dtype)
+ factor = torch.tensor([-0.5], device=device, dtype=dtype)
+ were_checks_enabled = are_checks_enabled()
+ disable_checks()
+ try:
+ out = kornia.enhance.adjust_contrast(img, factor, clip_output=False)
+ finally:
+ if were_checks_enabled:
+ enable_checks()
+ self.assert_close(out, img * -0.5)
+
+ def test_vmap_over_the_factor(self, device, dtype):
+ # vmap has no batching rule for the value assert, which is skipped under functorch transforms.
+ img = torch.rand(3, 4, 4, device=device, dtype=dtype)
+ factors = torch.tensor([0.5, 1.0, 1.5], device=device, dtype=dtype)
+ out = torch.vmap(lambda factor: kornia.enhance.adjust_contrast(img, factor))(factors)
+ expected = torch.stack([kornia.enhance.adjust_contrast(img, factor) for factor in factors])
+ self.assert_close(out, expected)
def test_factor_one_with_mean_subtraction(self, device, dtype):
# prepare input data
@@ -1126,6 +1148,21 @@ class TestEqualize(BaseTester):
with pytest.raises(RuntimeError, match=r"expects input values in \[0, 1\]"):
_sync(kornia.enhance.equalize(x).device)
+ def test_out_of_range_input_names_the_range_with_checks_disabled(self, device, dtype):
+ # The range check keeps the lookup in bounds, so it runs with checks disabled too (``python -O``,
+ # ``KORNIA_CHECKS=0``): a compiled CPU scatter with an index out of range terminates the process.
+ if device.type == "cuda":
+ pytest.skip("not on CUDA: the value assert is a device-side assert that poisons the context")
+ x = torch.linspace(0, 1, 64, device=device, dtype=dtype).reshape(1, 1, 8, 8) * 2.0
+ were_checks_enabled = are_checks_enabled()
+ disable_checks()
+ try:
+ with pytest.raises(RuntimeError, match=r"expects input values in \[0, 1\]"):
+ _sync(kornia.enhance.equalize(x).device)
+ finally:
+ if were_checks_enabled:
+ enable_checks()
+
def test_input_the_lookup_can_index_is_still_accepted(self, device, dtype):
# The check covers exactly the values that crashed, so a hair above 1 keeps working.
x = torch.linspace(0, 1, 64, device=device, dtype=dtype).reshape(1, 1, 8, 8) * 1.0001
@@ -1151,7 +1188,22 @@ class TestEqualize(BaseTester):
with pytest.raises(RuntimeError, match=r"expects input values in \[0, 1\]"):
_sync(compiled(x).device)
- @pytest.mark.skip(reason="TorchScript cannot read the module-level _MPS_HAS_ASSERT_ASYNC flag")
+ def test_dynamo_grad_out_of_range_input_names_the_range(self, device, dtype):
+ # The range check keeps the lookup in bounds, so a compiled torch.func.grad keeps it, although a compiled
+ # functorch transform skips the value checks that guard no index.
+ if device.type == "cuda":
+ pytest.skip("not on CUDA: the value assert is a device-side assert that poisons the context")
+ if device.type == "mps" and not torch_version_ge(2, 13):
+ pytest.skip("no MPS kernel for _assert_async before torch 2.13, so the check is skipped here")
+ if not torch_version_ge(2, 14):
+ pytest.skip("torch 2.9.1 and older end an error raised in a compiled torch.func.grad in an internal assert")
+ x = torch.linspace(0, 1, 64, device=device, dtype=dtype).reshape(1, 1, 8, 8) * 2.0
+ torch._dynamo.reset()
+ gradient = torch.func.grad(lambda image: kornia.enhance.equalize(image).sum())
+ compiled = torch.compile(gradient, fullgraph=True, backend="eager")
+ with pytest.raises(RuntimeError, match=r"expects input values in \[0, 1\]"):
+ _sync(compiled(x).device)
+
def test_jit(self, device, dtype):
batch_size, channels, height, width = 1, 2, 3, 3
inp = torch.ones(batch_size, channels, height, width, device=device, dtype=dtype)
@@ -1250,7 +1302,6 @@ class TestEqualize3D(BaseTester):
inputs3d = torch.ones(bs, channels, depth, height, width, device=device, dtype=torch.float64)
self.gradcheck(kornia.enhance.equalize3d, (inputs3d,), fast_mode=False)
- @pytest.mark.skip(reason="TorchScript cannot read the module-level _MPS_HAS_ASSERT_ASYNC flag")
def test_jit(self, device, dtype):
batch_size, channels, depth, height, width = 1, 2, 1, 3, 3
inp = torch.ones(batch_size, channels, depth, height, width, device=device, dtype=dtype)
@@ -1435,6 +1486,13 @@ class TestSolarize(BaseTester):
with pytest.raises(RuntimeError, match=r"closed range \[-0\.5, 0\.5\]"):
TestSolarize.f(img, 0.5, addition)
+ def test_float_additions_checked_on_the_host_under_any_default_device(self, device, dtype):
+ # The float is checked on the CPU whatever the default device: under a meta default the check used to have
+ # nothing to read, so an invalid float passed, and under a CUDA default it was a device-side assert.
+ img = torch.ones(2, 3, 4, 5, device=device, dtype=dtype)
+ with torch.device("meta"), pytest.raises(AsyncCheckError, match=r"closed range \[-0\.5, 0\.5\]"):
+ TestSolarize.f(img, 0.5, 0.7)
+
@pytest.mark.parametrize("addition", [0.5001, -0.5001])
def test_float_additions_checked_before_rounding(self, device, dtype, addition):
# A float is checked as given, on the host, for every device: float16/bfloat16 round 0.5001 to 0.5,
diff --git a/tests/enhance/test_conventions_enhance.py b/tests/enhance/test_conventions_enhance.py
index 47960d2b8..4d9f6bf95 100644
--- a/tests/enhance/test_conventions_enhance.py
+++ b/tests/enhance/test_conventions_enhance.py
@@ -221,7 +221,7 @@ class TestEnhanceConventions(BaseTester):
def test_convention_histogram_zero_bandwidth_is_rejected_5315(self, device, dtype):
if device.type != "cpu":
- # The check is torch._assert_async: skipped on MPS by design, a device-side assert on CUDA.
+ # On CUDA and MPS (torch >= 2.13) torch._assert_async raises at the next sync; CUDA then cannot recover.
pytest.skip("bandwidth check raises synchronously only on CPU")
values = torch.tensor([[0.0, 1.0]], device=device, dtype=dtype)
bins = torch.tensor([0.0, 1.0], device=device, dtype=dtype)
diff --git a/tests/enhance/test_equalization.py b/tests/enhance/test_equalization.py
index 8e91dd3be..5b56921fb 100644
--- a/tests/enhance/test_equalization.py
+++ b/tests/enhance/test_equalization.py
@@ -23,6 +23,7 @@ import torch
from kornia import enhance
from kornia.core._compat import torch_version_ge
+from kornia.core.check import are_checks_enabled, disable_checks, enable_checks
from kornia.enhance.equalization import _compute_tiles
from kornia.geometry import rotate
@@ -309,6 +310,22 @@ class TestEqualization(BaseTester):
with pytest.raises(RuntimeError, match=r"equalize_clahe expects input values in \[0, 1\]"):
_sync(enhance.equalize_clahe(x).device)
+ def test_out_of_range_input_names_the_range_with_checks_disabled(self, device, dtype):
+ # The range check keeps the gather in bounds, so it runs with checks disabled too (``python -O``,
+ # ``KORNIA_CHECKS=0``): compiled on the CPU, the gather with an index out of range terminates the process.
+ if device.type == "cuda":
+ pytest.skip("not on CUDA: the value assert is a device-side assert that poisons the context")
+ torch.manual_seed(0)
+ x = torch.rand(2, 3, 32, 40, device=device, dtype=dtype) * 2.0
+ were_checks_enabled = are_checks_enabled()
+ disable_checks()
+ try:
+ with pytest.raises(RuntimeError, match=r"equalize_clahe expects input values in \[0, 1\]"):
+ _sync(enhance.equalize_clahe(x).device)
+ finally:
+ if were_checks_enabled:
+ enable_checks()
+
def test_input_the_lookup_can_index_is_still_accepted(self, device, dtype):
# The check covers exactly the domain the gather can index, so a hair above 1 keeps working.
x = torch.rand(2, 3, 32, 40, device=device, dtype=dtype) * 1.0001
@@ -335,6 +352,22 @@ class TestEqualization(BaseTester):
with pytest.raises(RuntimeError, match=r"equalize_clahe expects input values in \[0, 1\]"):
_sync(compiled(x).device)
+ def test_dynamo_grad_out_of_range_input_names_the_range(self, device, dtype):
+ # The range check keeps the gather in bounds, so a compiled torch.func.grad keeps it, although a compiled
+ # functorch transform skips the value checks that guard no index.
+ if device.type == "cuda":
+ pytest.skip("not on CUDA: the value assert is a device-side assert that poisons the context")
+ if device.type == "mps" and not torch_version_ge(2, 13):
+ pytest.skip("no MPS kernel for _assert_async before torch 2.13, so the check is skipped here")
+ if not torch_version_ge(2, 14):
+ pytest.skip("Dynamo in torch 2.9.1 and older cannot compile torch.func.grad over equalize_clahe")
+ x = torch.linspace(0, 2, 2 * 3 * 32 * 40, device=device, dtype=dtype).reshape(2, 3, 32, 40)
+ torch._dynamo.reset()
+ gradient = torch.func.grad(lambda image: enhance.equalize_clahe(image).sum())
+ compiled = torch.compile(gradient, fullgraph=True, backend="eager")
+ with pytest.raises(RuntimeError, match=r"equalize_clahe expects input values in \[0, 1\]"):
+ _sync(compiled(x).device)
+
@pytest.fixture
def img(self, device, dtype):
height, width = 20, 20
diff --git a/tests/filters/test_gaussian.py b/tests/filters/test_gaussian.py
index e75ffaa48..713f52786 100644
--- a/tests/filters/test_gaussian.py
+++ b/tests/filters/test_gaussian.py
@@ -721,6 +721,8 @@ class TestGaussianBlur2d(BaseTester):
with pytest.raises(Exception) as errinfo:
gaussian_blur2d(sample, (3, 3), (-1.5, 1.5))
assert "sigma must be positive" in str(errinfo.value)
+ # The host check names the value it read.
+ assert "got tensor([[-1.5" in str(errinfo.value)
def test_sigma_zero_raises_exception(self, device, dtype):
"""Test that zero sigma raises an exception."""
@@ -781,6 +783,28 @@ class TestGaussianBlur2d(BaseTester):
torch.cuda.set_sync_debug_mode(previous)
self.assert_close(actual, expected, rtol=0, atol=0)
+ def test_sigma_tuple_is_checked_on_the_host_under_any_default_device_6337(self, device, dtype):
+ # A tuple sigma is built on the CPU whatever the default device: under a meta default it used to land on meta,
+ # where the check had nothing to read and an invalid sigma passed; under a CUDA default it was a device assert.
+ sample = torch.rand(1, 1, 5, 5, device=device, dtype=dtype)
+ with torch.device("meta"), pytest.raises(BaseError, match="sigma must be positive"):
+ gaussian_blur2d(sample, (3, 3), (-1.5, 1.5))
+
+ def test_sigma_tuple_under_a_cuda_default_device_does_not_synchronize_6337(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)
+ expected = gaussian_blur2d(sample, (5, 5), (1.5, 0.5))
+ torch.cuda.synchronize()
+ previous = torch.cuda.get_sync_debug_mode()
+ with torch.device(device):
+ torch.cuda.set_sync_debug_mode("error")
+ try:
+ actual = gaussian_blur2d(sample, (5, 5), (1.5, 0.5))
+ 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."""
sample = torch.rand(1, 3, 5, 5, device=device, dtype=dtype)
diff --git a/tests/geometry/test_boxes.py b/tests/geometry/test_boxes.py
index 32ef4fef2..449cee53c 100644
--- a/tests/geometry/test_boxes.py
+++ b/tests/geometry/test_boxes.py
@@ -23,6 +23,7 @@ from functools import partial
import pytest
import torch
+from kornia.core.check import are_checks_enabled, disable_checks, enable_checks
from kornia.geometry import boxes as boxes_module
from kornia.geometry.bbox import bbox_to_mask, bbox_to_mask3d, infer_bbox_shape, infer_bbox_shape3d
from kornia.geometry.boxes import Boxes, Boxes3D, VideoBoxes
@@ -85,7 +86,7 @@ class TestBoxes2D(BaseTester):
# Kornia#4177: vertex modes accept arbitrary finite quadrilaterals, but
# validate_boxes=True rejects non-finite coordinates.
if device.type != "cpu":
- # The check is torch._assert_async: skipped on MPS by design, a device-side assert on CUDA.
+ # On CUDA and MPS (torch >= 2.13) torch._assert_async raises at the next sync; CUDA then cannot recover.
pytest.skip("the vertex check raises synchronously only on CPU")
vertices = torch.tensor(
[[[0.0, 0.0], [4.0, 0.0], [4.0, 4.0], [0.0, 4.0]]],
@@ -2343,6 +2344,18 @@ class TestVideoBoxes(BaseTester):
self.assert_close(video_boxes.data, boxes.reshape(-1, 1, 4, 2), atol=0.0, rtol=0.0)
+ def test_vertex_check_is_skipped_when_checks_are_disabled(self, device, dtype):
+ boxes = self._sample_video_boxes(device, dtype)
+ boxes[0, 0, 0, 0, 0] = float("nan")
+ were_checks_enabled = are_checks_enabled()
+ disable_checks()
+ try:
+ video_boxes = VideoBoxes.from_tensor(boxes, validate_boxes=True)
+ finally:
+ if were_checks_enabled:
+ enable_checks()
+ assert video_boxes.data.shape == boxes.reshape(-1, 1, 4, 2).shape
+
@pytest.mark.parametrize("value", [float("nan"), float("inf"), float("-inf")])
def test_validate_boxes_rejects_non_finite_vertices_4177(self, value, device, dtype):
if device.type != "cpu":